mslxdff 0.1.123 → 0.1.124

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mslxdff",
3
- "version": "0.1.123",
3
+ "version": "0.1.124",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,6 +13,59 @@ export async function handleWorkbuddy(args) {
13
13
  child.on("close", (code) => process.exit(code ?? 0));
14
14
  child.on("error", (err) => { console.error(`workbuddy checkin failed: ${err.message}`); process.exit(1); });
15
15
  await new Promise(() => {});
16
+ } else if (sub === "growth" || sub === "earn" || sub === "tasks") {
17
+ const asJson = args.includes("--json") || args.includes("-json");
18
+ const ci = args.indexOf("--codes");
19
+ const codes = ci >= 0 && args[ci + 1] ? String(args[ci + 1]).split(",").filter(Boolean) : undefined;
20
+ const ai = args.indexOf("--account");
21
+ const prefix = ai >= 0 && args[ai + 1] ? String(args[ai + 1]) : "";
22
+ let items = await loadWorkbuddyAccounts();
23
+ if (prefix) items = items.filter((it) => String(it.uid).startsWith(prefix));
24
+ if (!items.length) { console.log("no workbuddy accounts — run node workbuddy-token-auto.js"); process.exit(0); }
25
+ await refreshExpiringAccounts(items);
26
+ const { runGrowthAll } = await import("../../providers/workbuddy/growth.js");
27
+ if (!asJson) console.log(`workbuddy growth (${items.length} account(s), serial):`);
28
+ const res = await runGrowthAll({
29
+ accounts: items.map((it) => ({ uid: it.uid, at: it.key, domain: it.domain, enterpriseId: it.enterpriseId })),
30
+ codes,
31
+ onAccount: (row) => {
32
+ if (asJson) return;
33
+ const u = String(row.uid).slice(0, 8);
34
+ if (!row.ok && row.error) { console.log(` [${u}] 失败: ${row.error}`); return; }
35
+ for (const t of row.tasks) {
36
+ if (t.skipped) console.log(` [${u}] ${t.task_code} 跳过(${t.skipped})`);
37
+ else console.log(` [${u}] ${t.task_code} 触发 ${t.fired}/${t.times} → ${t.status || "?"}${t.credit ? ` +${t.credit}` : ""}`);
38
+ }
39
+ console.log(` [${u}] 合计 +${row.credit} 积分 / +${row.energy} 能量`);
40
+ },
41
+ });
42
+ if (asJson) console.log(JSON.stringify(res, null, 2));
43
+ else console.log(`总计 +${res.creditTotal} 积分`);
44
+ process.exit(0);
45
+ } else if (sub === "travel" || sub === "cat" || sub === "cat-travel") {
46
+ const asJson = args.includes("--json") || args.includes("-json");
47
+ const ai = args.indexOf("--account");
48
+ const prefix = ai >= 0 && args[ai + 1] ? String(args[ai + 1]) : "";
49
+ let items = await loadWorkbuddyAccounts();
50
+ if (prefix) items = items.filter((it) => String(it.uid).startsWith(prefix));
51
+ if (!items.length) { console.log("no workbuddy accounts — run node workbuddy-token-auto.js"); process.exit(0); }
52
+ await refreshExpiringAccounts(items);
53
+ const { runCatTravel } = await import("../../providers/workbuddy/cat-travel.js");
54
+ if (!asJson) console.log(`workbuddy cat-travel (${items.length} account(s)):`);
55
+ const rows = [];
56
+ for (const it of items) {
57
+ const u = String(it.uid).slice(0, 8);
58
+ const r = await runCatTravel({
59
+ uid: it.uid, at: it.key, domain: it.domain, enterpriseId: it.enterpriseId,
60
+ onStep: asJson ? null : (s) => console.log(` [${u}] ${s.step} ${s.ok ? "✓" : "✗"} ${s.message}${s.reward ? ` (+${s.reward})` : ""}`),
61
+ });
62
+ if (!asJson) console.log(` [${u}] ${r.summary}`);
63
+ rows.push({ uid: it.uid, outcome: r.outcome, credits: r.credits, ok: r.ok, steps: r.steps });
64
+ }
65
+ const total = rows.reduce((s, r) => s + (r.credits || 0), 0);
66
+ if (asJson) console.log(JSON.stringify({ results: rows, credits: total }, null, 2));
67
+ else console.log(`总计 +${total} 积分`);
68
+ process.exit(0);
16
69
  } else if (sub === "balance" || sub === "balances" || sub === "credit" || sub === "credits") {
17
70
  const asJson = args.includes("--json") || args.includes("-json");
18
71
  const { loadProviderConfigs } = await import("../../state.js");
@@ -85,7 +138,59 @@ export async function handleWorkbuddy(args) {
85
138
  console.log(`removed workbuddy ${uid} (now ${auths.length} account(s))`);
86
139
  process.exit(0);
87
140
  } else {
88
- console.error("usage: mslxdff -workbuddy checkin | balance [--json] | list | remove <uid>");
141
+ console.error("usage: mslxdff -workbuddy checkin | growth [--codes a,b] [--account <uid>] | travel | balance [--json] | list | remove <uid>");
89
142
  process.exit(1);
90
143
  }
91
144
  }
145
+
146
+ // 账号加载(state 优先,缺则扫 auths/workbuddy-*.json),供 growth/travel 使用。
147
+ async function loadWorkbuddyAccounts() {
148
+ const { loadProviderConfigs } = await import("../../state.js");
149
+ const cfg = loadProviderConfigs().workbuddy || {};
150
+ const auths = Array.isArray(cfg.auths) ? cfg.auths : [];
151
+ const keys = Array.isArray(cfg.keys) ? cfg.keys : [];
152
+ const items = auths.map((a, i) => ({
153
+ uid: a.uid, domain: a.domain || "www.codebuddy.cn", enterpriseId: a.enterpriseId || "",
154
+ key: keys[i] || "", auth: a,
155
+ })).filter((it) => it.uid && it.key);
156
+ if (items.length) return items;
157
+ try {
158
+ const { readdirSync, readFileSync, existsSync } = await import("node:fs");
159
+ const { join } = await import("node:path");
160
+ const { resolveAuthDir } = await import("../../providers/workbuddy/account-store.js");
161
+ const dir = resolveAuthDir();
162
+ if (existsSync(dir)) {
163
+ for (const f of readdirSync(dir).filter((x) => x.startsWith("workbuddy-") && x.endsWith(".json"))) {
164
+ try {
165
+ const j = JSON.parse(readFileSync(join(dir, f), "utf8"));
166
+ if (j?.account?.uid && j?.auth?.accessToken) {
167
+ const domain = j.auth.domain || "www.codebuddy.cn";
168
+ items.push({
169
+ uid: j.account.uid, domain, enterpriseId: j.account.enterpriseId || "",
170
+ key: j.auth.accessToken,
171
+ auth: { uid: j.account.uid, domain, enterpriseId: j.account.enterpriseId || "", refreshToken: j.auth.refreshToken || "" },
172
+ });
173
+ }
174
+ } catch {}
175
+ }
176
+ }
177
+ } catch {}
178
+ return items;
179
+ }
180
+
181
+ // 临期 token 续期(<1h),refresh 结果经 store 回写 state 与 auths 文件。
182
+ async function refreshExpiringAccounts(items) {
183
+ const { compatFetch } = await import("../../compat.js");
184
+ const { createAuthService, decodeJwtExp } = await import("../../providers/workbuddy/auth.js");
185
+ const keys = items.map((it) => it.key);
186
+ const authList = items.map((it) => it.auth);
187
+ const svc = createAuthService({ fetchImpl: compatFetch, store: { keys, authList } });
188
+ await Promise.all(authList.map(async (auth, i) => {
189
+ try {
190
+ const exp = decodeJwtExp(keys[i]);
191
+ if (exp && exp - Date.now() / 1000 < 3600) await svc.refreshTokenFor(keys[i], auth);
192
+ } catch {}
193
+ }));
194
+ items.forEach((it, i) => { it.key = keys[i]; });
195
+ return items;
196
+ }
@@ -0,0 +1,125 @@
1
+ import { compatFetch } from "../../compat.js";
2
+ import { growthRequest } from "./growth-api.js";
3
+ import { fireGrowthEvent } from "./growth.js";
4
+ // WorkBuddy 猫猫旅行(/activity/growth/buddy/*,无 /v2 前缀):
5
+ // 同意协议 → 首次领养(+300)→ 派出 → 到站领奖。
6
+ // 领养门槛「first_buddy task not completed yet」= 需至少一次对话,
7
+ // 用一次 chat_request_send 事件(免费模型、成本 0)即可解锁。
8
+
9
+ const BUDDY_GATE_MARKER = "first_buddy task not completed yet";
10
+ const DEFAULT_LOCATION_ID = 4;
11
+
12
+ // sleep 必须保活事件循环(CLI 场景 unref 会让 Node 提前退出,见 growth.js 同注)。
13
+ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
14
+
15
+ export async function runCatTravel({
16
+ uid, at, domain, enterpriseId,
17
+ locationId = DEFAULT_LOCATION_ID,
18
+ fetchImpl = compatFetch, sleepFn = defaultSleep,
19
+ gaps = {}, onStep = null,
20
+ } = {}) {
21
+ const g = { pollMs: 1500, ...gaps };
22
+ const api = { uid, at, domain, enterpriseId, fetchImpl };
23
+ const steps = [];
24
+ let credits = 0;
25
+ const add = (step, ok, message, reward = 0, skipped = false) => {
26
+ credits += reward;
27
+ const s = { step, ok, skipped, reward, message };
28
+ steps.push(s);
29
+ try { onStep?.(s); } catch {}
30
+ };
31
+ const done = (ok, outcome, summary) => ({ ok, outcome, credits, steps, summary });
32
+
33
+ // 1) 猫档案:data.buddy 为 null 即未领养
34
+ const info = await growthRequest({ ...api, method: "GET", path: "/activity/growth/buddy/info" });
35
+ if (!info.ok) {
36
+ add("info", false, `查询猫档案失败:${info.msg || info.status}`);
37
+ return done(false, "error", "查询猫档案失败");
38
+ }
39
+ const buddy = info.data?.buddy || null;
40
+
41
+ // 2) 无猫:协议 → 领养(门槛未达标时自动补一次对话再试)
42
+ if (!buddy) {
43
+ const agr = await growthRequest({ ...api, method: "POST", path: "/activity/growth/buddy/agreement", body: { agree: true } });
44
+ if (!agr.ok) {
45
+ add("agreement", false, `同意协议失败:${agr.msg || agr.status}`);
46
+ return done(false, "error", "同意协议失败");
47
+ }
48
+ add("agreement", true, "已同意活动协议");
49
+
50
+ let first = await growthRequest({ ...api, method: "POST", path: "/activity/growth/buddy/first" });
51
+ if (!first.ok && first.status === 400 && String(first.msg || "").toLowerCase().includes(BUDDY_GATE_MARKER)) {
52
+ const fr = await fireGrowthEvent(api, { eventCodes: ["chat_request_send"] });
53
+ if (fr.ok) {
54
+ add("gate", true, "领养门槛未达标,已补一次对话解锁");
55
+ await sleepFn(g.pollMs);
56
+ first = await growthRequest({ ...api, method: "POST", path: "/activity/growth/buddy/first" });
57
+ } else {
58
+ add("gate", false, `门槛补齐失败:${fr.msg || fr.status}`, 0, true);
59
+ }
60
+ }
61
+ if (first.ok) {
62
+ const data = first.data || {};
63
+ const got = Number(data.credit || 0);
64
+ const reward = got > 0 ? got : 300;
65
+ const energy = Number(data.energy || 0);
66
+ let msg = `领养成功,已发放 ${reward} 积分`;
67
+ if (energy) msg += ` + ${energy} 能量`;
68
+ const badge = data.badge?.name;
69
+ if (badge) msg += `,解锁徽章「${badge}」`;
70
+ add("adopt", true, msg, reward);
71
+ return done(true, "adopted", msg);
72
+ }
73
+ if (first.status === 400 && String(first.msg || "").toLowerCase().includes(BUDDY_GATE_MARKER)) {
74
+ add("adopt", true, "本次无法领养:对话门槛未达标", 0, true);
75
+ return done(true, "gate_blocked", "本次无法领养(对话门槛未达标)");
76
+ }
77
+ add("adopt", false, `领养失败:${first.msg || first.status}`);
78
+ return done(false, "error", "领养失败");
79
+ }
80
+ add("adopt", true, `已有猫:${buddy.name || buddy.id}`, 0, true);
81
+
82
+ // 3) 旅行状态
83
+ const st = await growthRequest({ ...api, method: "GET", path: "/activity/growth/buddy/travel/status" });
84
+ if (!st.ok) {
85
+ add("status", false, `查询旅行状态失败:${st.msg || st.status}`);
86
+ return done(false, "error", "查询旅行状态失败");
87
+ }
88
+ const state = String(st.data?.state || "");
89
+ const recordId = Number(st.data?.record_id || 0);
90
+
91
+ // 4) 到站领奖 / 空闲派出
92
+ if (state === "arrived") {
93
+ if (recordId <= 0) {
94
+ add("claim", false, "已到站但缺少 record_id,无法领奖");
95
+ return done(false, "error", "领奖失败(缺少 record_id)");
96
+ }
97
+ const cl = await growthRequest({ ...api, method: "POST", path: "/activity/growth/buddy/travel/claim", body: { record_id: recordId } });
98
+ if (!cl.ok) {
99
+ add("claim", false, `领奖失败:${cl.msg || cl.status}`);
100
+ return done(false, "error", "领奖失败");
101
+ }
102
+ const reward = Number(cl.data?.reward_credit || 0);
103
+ add("claim", true, `领奖成功,获得 ${reward} 积分`, reward);
104
+ return done(true, reward > 0 ? "travel_claimed" : "travel_none", reward > 0 ? `完成,共获得 ${reward} 积分` : "完成,本次无新增积分");
105
+ }
106
+ if (state === "idle") {
107
+ if (st.data?.daily_limit_reached) {
108
+ add("depart", true, "今日已派出过,明日可再次派出", 0, true);
109
+ return done(true, "travel_none", "今日已派出过");
110
+ }
111
+ const dp = await growthRequest({ ...api, method: "POST", path: "/activity/growth/buddy/travel/depart", body: { location_id: locationId } });
112
+ if (!dp.ok) {
113
+ add("depart", false, `派出失败:${dp.msg || dp.status}`);
114
+ return done(false, "error", "派出失败");
115
+ }
116
+ add("depart", true, "已派出猫咪旅行,到站后可领奖");
117
+ return done(true, "departed", "已派出猫咪旅行,到站后可领奖");
118
+ }
119
+ if (state === "traveling") {
120
+ add("depart", true, `猫咪正在旅行中(record=${recordId})`, 0, true);
121
+ return done(true, "traveling", "猫咪正在旅行中,到站后可领奖");
122
+ }
123
+ add("status", true, `未知旅行状态 ${state},未执行动作`, 0, true);
124
+ return done(true, "unknown", `未知旅行状态 ${state}`);
125
+ }
@@ -0,0 +1,67 @@
1
+ import { compatFetch, timeoutSignal } from "../../compat.js";
2
+ // WorkBuddy growth 域(/activity/growth/* 与 /v2/activity/growth/*)底层请求。
3
+ // 双域容灾与签到同款;业务失败结构化返回(ok:false + code/msg),不抛异常。
4
+ // 注意:领奖路径 /activity/growth/tasks/{code}/claim 无 /v2 前缀(上游实测形态)。
5
+
6
+ export const GROWTH_BASES = [
7
+ "https://copilot.tencent.com",
8
+ "https://www.codebuddy.cn",
9
+ ];
10
+
11
+ export function growthHeaders({ at, uid, domain, enterpriseId }) {
12
+ return {
13
+ Authorization: `Bearer ${at}`,
14
+ "Content-Type": "application/json",
15
+ Accept: "application/json",
16
+ "X-User-Id": uid,
17
+ "X-Domain": domain || "www.codebuddy.cn",
18
+ "X-Product": "SaaS",
19
+ "User-Agent": "CLI/2.115.0 WorkBuddy/2.115.0",
20
+ Origin: "https://www.codebuddy.cn",
21
+ Referer: "https://www.codebuddy.cn/",
22
+ ...(enterpriseId ? { "X-Enterprise-Id": enterpriseId } : {}),
23
+ };
24
+ }
25
+
26
+ export async function growthRequest({
27
+ uid, at, domain, enterpriseId,
28
+ method = "GET", path, body,
29
+ fetchImpl = compatFetch, timeoutMs = 15000,
30
+ } = {}) {
31
+ const headers = growthHeaders({ at, uid, domain, enterpriseId });
32
+ let last = null;
33
+ for (const base of GROWTH_BASES) {
34
+ const url = base + path;
35
+ let res;
36
+ try {
37
+ res = await fetchImpl(url, {
38
+ method,
39
+ headers,
40
+ ...(method.toUpperCase() === "GET" ? {} : { body: JSON.stringify(body ?? {}) }),
41
+ signal: timeoutSignal(timeoutMs),
42
+ });
43
+ } catch (e) {
44
+ last = { ok: false, status: 0, code: null, msg: `网络失败: ${String(e?.message || e).slice(0, 200)}`, data: {}, url };
45
+ continue;
46
+ }
47
+ let payload = null;
48
+ try { payload = await res.json(); } catch { payload = null; }
49
+ if (!payload || typeof payload !== "object") {
50
+ last = { ok: false, status: res.status, code: null, msg: `非 JSON 响应 HTTP ${res.status}`, data: {}, url };
51
+ if (res.status === 401 || res.status === 403) return { ...last, needRefresh: true };
52
+ continue;
53
+ }
54
+ const out = {
55
+ ok: res.status === 200 && payload.code === 0,
56
+ status: res.status,
57
+ code: payload.code,
58
+ msg: payload.msg || "",
59
+ data: payload.data || {},
60
+ url,
61
+ };
62
+ if (out.ok) return out;
63
+ if (res.status === 401 || res.status === 403) return { ...out, needRefresh: true };
64
+ last = out;
65
+ }
66
+ return last || { ok: false, status: 0, code: null, msg: "无可用域", data: {} };
67
+ }
@@ -0,0 +1,63 @@
1
+ // WorkBuddy 成长任务策略表:哪些任务可自动完成 / 用什么事件 / 何时只能人工。
2
+ // 来源:workbuddy2api admin/growth_plans.py 的逐条实测结论(1131 事件枚举 + 客户端机制证据)。
3
+ // 未登记任务默认 MANUAL——宁可漏做,不盲发请求污染上游日志。
4
+
5
+ export const PLAN_LEVELS = { AUTO: "auto", MULTI: "multi", MANUAL: "manual", SKIP: "skip" };
6
+ export const MAX_TIMES = 10;
7
+
8
+ function plan(code, level, eventCodes = [], reason = "", model = "") {
9
+ return {
10
+ code, level, eventCodes, model, reason,
11
+ actionable: (level === PLAN_LEVELS.AUTO || level === PLAN_LEVELS.MULTI) && eventCodes.length > 0,
12
+ };
13
+ }
14
+
15
+ export const TASK_PLANS = {
16
+ // —— 上游实测可自动 ——
17
+ chat_5: plan("chat_5", PLAN_LEVELS.MULTI, ["chat_request_send"], "对话类:带 growthEvent 的对话请求,按 target 次数重复"),
18
+ automation_1: plan("automation_1", PLAN_LEVELS.AUTO, ["automated_task_create_suc"], "自动化任务:创建成功事件"),
19
+ skill_1: plan("skill_1", PLAN_LEVELS.AUTO, ["skill_info"], "尝鲜技能:skill_info 事件"),
20
+ "Model_chat_GLM5.2": plan("Model_chat_GLM5.2", PLAN_LEVELS.AUTO, ["chat_request_send"], "模型体验:必须真实调用 glm-5.2(发事件包无效)", "glm-5.2"),
21
+ // —— 机制上必须客户端(上游枚举 1131 事件未命中)——
22
+ RichMeow_Chat: plan("RichMeow_Chat", PLAN_LEVELS.MANUAL, [], "桌面端对话:上游按客户端类型判定,需真实桌面端"),
23
+ expert_5: plan("expert_5", PLAN_LEVELS.MANUAL, [], "召唤专家:客户端本地专家包下载+激活,非服务端事件"),
24
+ expert_5_paid: plan("expert_5_paid", PLAN_LEVELS.MANUAL, [], "召唤专家(付费版):同上"),
25
+ Expert_team_use_3: plan("Expert_team_use_3", PLAN_LEVELS.MANUAL, [], "召唤专家团:同上"),
26
+ Hp_Appearance: plan("Hp_Appearance", PLAN_LEVELS.MANUAL, [], "和平精英主题:桌面端本地设置状态"),
27
+ create_canvas: plan("create_canvas", PLAN_LEVELS.MANUAL, [], "设计创意模式:需真实创建画布"),
28
+ template_5: plan("template_5", PLAN_LEVELS.MANUAL, ["agent_task_created_with_template"], "使用模板:尝试模板事件未验证,暂按人工"),
29
+ playbook_prompt: plan("playbook_prompt", PLAN_LEVELS.MANUAL, [], "灵感案例:未找到有效事件"),
30
+ Library_read: plan("Library_read", PLAN_LEVELS.MANUAL, [], "资料库:未找到有效事件"),
31
+ Expert_Philanthropy: plan("Expert_Philanthropy", PLAN_LEVELS.MANUAL, [], "公益专家:未找到有效事件"),
32
+ Buddy_App: plan("Buddy_App", PLAN_LEVELS.MANUAL, [], "发现应用:未找到有效事件"),
33
+ Buddy_App_QQ: plan("Buddy_App_QQ", PLAN_LEVELS.MANUAL, [], "企鹅教师助手:未找到有效事件"),
34
+ Expert_lighthouse: plan("Expert_lighthouse", PLAN_LEVELS.MANUAL, [], "腾讯轻量云专家:未找到有效事件"),
35
+ // —— 无收益 ——
36
+ black_cat: plan("black_cat", PLAN_LEVELS.SKIP, [], "夜猫子折扣活动,奖励为 0"),
37
+ };
38
+
39
+ const DEFAULT_PLAN = plan("", PLAN_LEVELS.MANUAL, [], "未登记的任务类型,需人工确认");
40
+
41
+ export function planFor(code) {
42
+ return TASK_PLANS[code] || DEFAULT_PLAN;
43
+ }
44
+
45
+ export function classifyTask(task = {}) {
46
+ const code = task.task_code || "";
47
+ const p = planFor(code);
48
+ let level = p.level;
49
+ const reward = Number(task.reward_credit || 0);
50
+ if (reward <= 0 && level !== PLAN_LEVELS.SKIP) level = PLAN_LEVELS.SKIP;
51
+ const prog = task.progress || {};
52
+ const target = Number(prog.target);
53
+ const current = Number(prog.current || 0);
54
+ const rawNeed = Number.isInteger(target) && target > current ? target - current : 1;
55
+ return {
56
+ ...task,
57
+ level,
58
+ actionable: (level === PLAN_LEVELS.AUTO || level === PLAN_LEVELS.MULTI) && p.eventCodes.length > 0,
59
+ strategy: p.reason,
60
+ model: p.model,
61
+ need_times: Math.max(1, Math.min(rawNeed, MAX_TIMES)),
62
+ };
63
+ }
@@ -0,0 +1,181 @@
1
+ import { compatFetch, timeoutSignal, uuid } from "../../compat.js";
2
+ import { GROWTH_BASES, growthHeaders, growthRequest } from "./growth-api.js";
3
+ import { PLAN_LEVELS, MAX_TIMES, planFor, classifyTask } from "./growth-plans.js";
4
+ // WorkBuddy 成长计划任务:拉列表 → 参与(accept) → 触发(growthEvent) → 领奖(claim)。
5
+ // 机制(上游实测):进度由请求体 extra_vars.growthEvent 驱动;未 accept 不累计;
6
+ // completed ≠ claimed(要另调领奖)。串行 + 节流是硬要求,同账号禁并行。
7
+ // 策略表(哪些任务可自动 / 用什么事件)见 growth-plans.js。
8
+
9
+ export { PLAN_LEVELS, MAX_TIMES, TASK_PLANS, planFor, classifyTask } from "./growth-plans.js";
10
+
11
+ // 注意:sleep 必须保活事件循环(不能 unref)——CLI 场景下 unref 的定时器
12
+ // 会让 Node 在等待期间判定 event loop 空而提前退出(exit 13 unsettled await)。
13
+ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
14
+
15
+ export async function waitFor(fn, { timeoutMs = 8000, intervalMs = 500, sleepFn = defaultSleep } = {}) {
16
+ const deadline = Date.now() + timeoutMs;
17
+ for (;;) {
18
+ let v = false;
19
+ try { v = await fn(); } catch {}
20
+ if (v) return true;
21
+ if (Date.now() >= deadline) return false;
22
+ await sleepFn(intervalMs);
23
+ }
24
+ }
25
+
26
+ export async function growthTasks(api = {}) {
27
+ const r = await growthRequest({ ...api, method: "GET", path: "/v2/activity/growth/tasks" });
28
+ return { ...r, tasks: r.ok ? (r.data?.tasks || []) : [] };
29
+ }
30
+
31
+ export async function growthAccept(api = {}, codes = []) {
32
+ return growthRequest({ ...api, method: "POST", path: "/v2/activity/growth/tasks/accept", body: { task_codes: [...codes] } });
33
+ }
34
+
35
+ export async function growthClaim(api = {}, code) {
36
+ return growthRequest({ ...api, method: "POST", path: `/activity/growth/tasks/${code}/claim` });
37
+ }
38
+
39
+ // 通过带 growthEvent 的模型请求触发进度:正常 200 + 免费模型 + max_tokens=1(成本 0)。
40
+ // 读首块即主动断开,不等待全文。
41
+ export async function fireGrowthEvent(api = {}, { eventCodes = [], model, eventId, timeoutMs = 60000 } = {}) {
42
+ const { uid, at, domain, enterpriseId, fetchImpl = compatFetch } = api;
43
+ const id = eventId || uuid();
44
+ const body = {
45
+ model: model || process.env.MSLXDFF_WORKBUDDY_GROWTH_MODEL || "hy3",
46
+ stream: true,
47
+ max_tokens: 1,
48
+ messages: [{ role: "user", content: "hi" }],
49
+ extra_vars: { growthEvent: JSON.stringify(eventCodes.map((c) => ({ eventCode: c, id }))) },
50
+ };
51
+ let last = { ok: false, status: 0 };
52
+ for (const base of GROWTH_BASES) {
53
+ let res;
54
+ try {
55
+ res = await fetchImpl(`${base}/v2/chat/completions`, {
56
+ method: "POST",
57
+ headers: growthHeaders({ at, uid, domain, enterpriseId }),
58
+ body: JSON.stringify(body),
59
+ signal: timeoutSignal(timeoutMs),
60
+ });
61
+ } catch (e) {
62
+ last = { ok: false, status: 0, msg: String(e?.message || e).slice(0, 200) };
63
+ continue;
64
+ }
65
+ try {
66
+ const reader = res.body?.getReader?.();
67
+ if (reader) { await reader.read(); await reader.cancel?.(); }
68
+ } catch {}
69
+ if (res.status === 200) return { ok: true, status: 200 };
70
+ last = { ok: false, status: res.status, msg: `HTTP ${res.status}` };
71
+ }
72
+ return last;
73
+ }
74
+
75
+ // 单账号闭环:拉列表 → 逐任务(accept→等落库→触发×N→等复查) → 统一领奖。
76
+ export async function runGrowthAccount({
77
+ uid, at, domain, enterpriseId,
78
+ codes, model,
79
+ fetchImpl = compatFetch, sleepFn = defaultSleep,
80
+ gaps = {}, onStep = null,
81
+ } = {}) {
82
+ const g = { eventMs: 1200, accountMs: 1000, pollMs: 500, acceptTimeoutMs: 8000, verifyTimeoutMs: 8000, ...gaps };
83
+ const api = { uid, at, domain, enterpriseId, fetchImpl };
84
+ const step = (e) => { try { onStep?.(e); } catch {} };
85
+ const out = { uid, ok: true, tasks: [], credit: 0, energy: 0 };
86
+
87
+ const listed = await growthTasks(api);
88
+ if (!listed.ok) { out.ok = false; out.error = listed.msg || "拉取任务列表失败"; return out; }
89
+ const byCode = new Map(listed.tasks.map((t) => [t.task_code, t]));
90
+ const wanted = Array.isArray(codes) && codes.length ? codes : listed.tasks.map((t) => t.task_code);
91
+
92
+ const latestOf = async (code) => {
93
+ const r = await growthTasks(api);
94
+ return r.ok ? r.tasks.find((t) => t.task_code === code) : undefined;
95
+ };
96
+
97
+ for (const code of wanted) {
98
+ const raw = byCode.get(code);
99
+ if (!raw) { out.tasks.push({ task_code: code, ok: false, skipped: "任务不存在" }); continue; }
100
+ const info = classifyTask(raw);
101
+ if (info.accept_status === "claimed") {
102
+ out.tasks.push({ task_code: code, title: info.title, ok: true, skipped: "已领取", status: "claimed" });
103
+ step({ phase: "task", task_code: code, skipped: "已领取" });
104
+ continue;
105
+ }
106
+ if (!info.actionable) {
107
+ out.tasks.push({ task_code: code, title: info.title, ok: false, skipped: info.strategy || "需人工完成", level: info.level });
108
+ step({ phase: "task", task_code: code, skipped: info.strategy });
109
+ continue;
110
+ }
111
+ if (info.accept_status === "not_accepted") {
112
+ const ar = await growthAccept(api, [code]);
113
+ step({ phase: "accept", task_code: code, ok: ar.ok, msg: ar.msg });
114
+ if (ar.ok) {
115
+ await waitFor(async () => {
116
+ const t = await latestOf(code);
117
+ return !!t && !!t.accept_status && t.accept_status !== "not_accepted";
118
+ }, { timeoutMs: g.acceptTimeoutMs, intervalMs: g.pollMs, sleepFn });
119
+ }
120
+ }
121
+ let fired = 0;
122
+ for (let i = 0; i < info.need_times; i++) {
123
+ const r = await fireGrowthEvent(api, { eventCodes: info.eventCodes || planFor(code).eventCodes, model: info.model || model });
124
+ if (r.ok) fired += 1;
125
+ step({ phase: "fire", task_code: code, i: i + 1, times: info.need_times, ok: r.ok, msg: r.msg });
126
+ if (i + 1 < info.need_times) await sleepFn(g.eventMs);
127
+ }
128
+ const base = info.progress?.current ?? 0;
129
+ await waitFor(async () => {
130
+ const t = await latestOf(code);
131
+ if (!t) return false;
132
+ if (t.accept_status === "completed" || t.accept_status === "claimed") return true;
133
+ return Number(t.progress?.current ?? 0) > Number(base);
134
+ }, { timeoutMs: g.verifyTimeoutMs, intervalMs: g.pollMs, sleepFn });
135
+ const latest = (await latestOf(code)) || info;
136
+ const item = {
137
+ task_code: code,
138
+ title: latest.title || info.title || code,
139
+ ok: fired > 0,
140
+ fired,
141
+ times: info.need_times,
142
+ status: latest.accept_status,
143
+ progress: `${latest.progress?.current ?? 0}/${latest.progress?.target ?? "?"}`,
144
+ };
145
+ out.tasks.push(item);
146
+ step({ phase: "task", ...item });
147
+ }
148
+
149
+ const done = (await growthTasks(api)).tasks.filter((t) => t.accept_status === "completed");
150
+ for (const t of done) {
151
+ const cr = await growthClaim(api, t.task_code);
152
+ const credit = Number(cr.data?.credit || 0);
153
+ const energy = Number(cr.data?.energy || 0);
154
+ if (cr.ok) {
155
+ out.credit += credit;
156
+ out.energy += energy;
157
+ const item = out.tasks.find((x) => x.task_code === t.task_code);
158
+ if (item) { item.status = "claimed"; item.credit = credit; item.energy = energy; item.ok = true; }
159
+ }
160
+ step({ phase: "claim", task_code: t.task_code, ok: cr.ok, credit, energy, msg: cr.msg });
161
+ await sleepFn(g.eventMs);
162
+ }
163
+ if (out.tasks.length && out.tasks.every((t) => !t.ok)) out.ok = false;
164
+ return out;
165
+ }
166
+
167
+ // 多账号串行(账号间 1s 节流;单账号异常不挡后续)。
168
+ export async function runGrowthAll({ accounts = [], onAccount, ...opts } = {}) {
169
+ const results = [];
170
+ let creditTotal = 0;
171
+ for (const a of accounts) {
172
+ let row;
173
+ try { row = await runGrowthAccount({ ...opts, ...a }); }
174
+ catch (e) { row = { uid: a.uid, ok: false, tasks: [], credit: 0, energy: 0, error: String(e?.message || e).slice(0, 200) }; }
175
+ results.push(row);
176
+ creditTotal += row.credit || 0;
177
+ try { onAccount?.(row); } catch {}
178
+ await (opts.sleepFn || defaultSleep)(opts.gaps?.accountMs ?? 1000);
179
+ }
180
+ return { ok: results.some((r) => r.ok), results, creditTotal };
181
+ }
@@ -24,4 +24,9 @@ export async function startDaemonMain(VERSION) {
24
24
  void setupWorkbuddyCheckin({ bus, logs }).catch((e) => {
25
25
  try { logs.appendEvent({ ts: Date.now(), type: "workbuddy-checkin-setup-failed", error: String(e?.message || e).slice(0, 200) }); } catch {}
26
26
  });
27
+
28
+ const { setupWorkbuddyGrowth } = await import("./workbuddy-growth.js");
29
+ void setupWorkbuddyGrowth({ bus, logs }).catch((e) => {
30
+ try { logs.appendEvent({ ts: Date.now(), type: "workbuddy-growth-setup-failed", error: String(e?.message || e).slice(0, 200) }); } catch {}
31
+ });
27
32
  }
@@ -20,17 +20,17 @@ export function todayKey(d = new Date()) {
20
20
  }
21
21
 
22
22
  // 到下一次计划点的毫秒数(今天未到点→今天,已过→明天同时)。
23
- export function nextRunDelayMs(now = new Date(), hour = 9) {
23
+ export function nextRunDelayMs(now = new Date(), hour = 9, minute = 0) {
24
24
  const next = new Date(now);
25
- next.setHours(hour, 0, 0, 0);
25
+ next.setHours(hour, minute, 0, 0);
26
26
  if (next.getTime() <= now.getTime()) next.setDate(next.getDate() + 1);
27
27
  return next.getTime() - now.getTime();
28
28
  }
29
29
 
30
30
  // 启动补签:已过今日计划点、且(从没签过 或 上次不是今天)。
31
- export function shouldCatchUp({ lastDate, now = new Date(), hour = 9 } = {}) {
31
+ export function shouldCatchUp({ lastDate, now = new Date(), hour = 9, minute = 0 } = {}) {
32
32
  const point = new Date(now);
33
- point.setHours(hour, 0, 0, 0);
33
+ point.setHours(hour, minute, 0, 0);
34
34
  if (now.getTime() < point.getTime()) return false;
35
35
  return !lastDate || lastDate !== todayKey(now);
36
36
  }
@@ -0,0 +1,133 @@
1
+ import { compatFetch } from "../compat.js";
2
+ import { todayKey, nextRunDelayMs, shouldCatchUp } from "./workbuddy-checkin.js";
3
+ // daemon 内置 WorkBuddy 成长任务 + 猫猫旅行每日自动(A 方案):
4
+ // 多账号串行(任务间 1.2s、账号间 1s 节流)+ 启动补跑 + 每日定时(默认 09:30,与 09:00 签到错峰)。
5
+ // 开关:MSLXDFF_WORKBUDDY_GROWTH=0 关闭(默认开);时间:MSLXDFF_WORKBUDDY_GROWTH_HOUR(默认 9)。
6
+ // 幂等:已 claimed 的任务跳过;结果落 state.workbuddyGrowth 防重复补跑。
7
+
8
+ export const GROWTH_MINUTE = 30;
9
+
10
+ export function isGrowthEnabled(env = process.env) {
11
+ const v = String(env.MSLXDFF_WORKBUDDY_GROWTH ?? "1").trim().toLowerCase();
12
+ return !["0", "false", "off", "no"].includes(v);
13
+ }
14
+
15
+ export function getGrowthHour(env = process.env) {
16
+ const h = Number(env.MSLXDFF_WORKBUDDY_GROWTH_HOUR);
17
+ return Number.isInteger(h) && h >= 0 && h <= 23 ? h : 9;
18
+ }
19
+
20
+ export function nextGrowthDelayMs(now = new Date(), hour = 9, minute = GROWTH_MINUTE) {
21
+ return nextRunDelayMs(now, hour, minute);
22
+ }
23
+
24
+ export function shouldGrowthCatchUp({ lastDate, now = new Date(), hour = 9, minute = GROWTH_MINUTE } = {}) {
25
+ return shouldCatchUp({ lastDate, now, hour, minute });
26
+ }
27
+
28
+ const sleep = (ms) => new Promise((r) => { const t = setTimeout(r, ms); if (typeof t.unref === "function") t.unref(); });
29
+
30
+ export async function setupWorkbuddyGrowth({ bus, logs } = {}) {
31
+ function emit(type, data = {}) {
32
+ const entry = { ts: Date.now(), type, ...data };
33
+ try { bus?.emit(entry); } catch {}
34
+ try { logs?.appendEvent?.(entry); } catch {}
35
+ console.log(`[workbuddy-growth] ${type} ${JSON.stringify(data)}`.slice(0, 500));
36
+ }
37
+ if (!isGrowthEnabled()) {
38
+ console.log("[workbuddy-growth] disabled (set MSLXDFF_WORKBUDDY_GROWTH=1 to enable)");
39
+ emit("workbuddy-growth-disabled");
40
+ return { enabled: false };
41
+ }
42
+ const hour = getGrowthHour();
43
+ console.log(`[workbuddy-growth] enabled: daily ${String(hour).padStart(2, "0")}:${GROWTH_MINUTE} local, multi-account serial`);
44
+ emit("workbuddy-growth-enabled", { hour, minute: GROWTH_MINUTE });
45
+
46
+ const stateMod = await import("../state.js");
47
+ const { runGrowthAll } = await import("../providers/workbuddy/growth.js");
48
+ const { runCatTravel } = await import("../providers/workbuddy/cat-travel.js");
49
+ const { createAuthService, decodeJwtExp } = await import("../providers/workbuddy/auth.js");
50
+
51
+ let running = false;
52
+ async function loadAccounts() {
53
+ const cfg = stateMod.loadProviderConfigs().workbuddy || {};
54
+ const keys = [...(Array.isArray(cfg.keys) ? cfg.keys : [])];
55
+ const authList = [...(Array.isArray(cfg.auths) ? cfg.auths : [])];
56
+ if (!keys.length) return null;
57
+ // 先给临期 token 续期(与签到调度同款:refresh 结果经 store 回写 state 与 auths 文件)
58
+ const authService = createAuthService({ fetchImpl: compatFetch, store: { keys, authList } });
59
+ await Promise.all(authList.map(async (auth, i) => {
60
+ try {
61
+ const exp = decodeJwtExp(keys[i]);
62
+ if (exp && exp - Date.now() / 1000 < 3600) await authService.refreshTokenFor(keys[i], auth);
63
+ } catch {}
64
+ }));
65
+ return authList
66
+ .map((a, i) => ({ uid: a.uid, at: keys[i], domain: a.domain, enterpriseId: a.enterpriseId }))
67
+ .filter((a) => a.uid && a.at);
68
+ }
69
+
70
+ async function runOnce(reason) {
71
+ if (running) return { skipped: "already-running" };
72
+ running = true;
73
+ try {
74
+ const accounts = await loadAccounts();
75
+ if (!accounts?.length) {
76
+ emit("workbuddy-growth-no-accounts", { reason });
77
+ return { ok: false, reason: "no-accounts" };
78
+ }
79
+ const growthRes = await runGrowthAll({
80
+ accounts,
81
+ onAccount: (row) => emit("workbuddy-growth-account", {
82
+ uid: String(row.uid).slice(0, 8), ok: row.ok, credit: row.credit,
83
+ tasks: row.tasks.filter((t) => t.ok && !t.skipped).length, reason,
84
+ }),
85
+ });
86
+ const travel = [];
87
+ for (const a of accounts) {
88
+ try {
89
+ const r = await runCatTravel({ uid: a.uid, at: a.at, domain: a.domain, enterpriseId: a.enterpriseId });
90
+ travel.push({ uid: a.uid, outcome: r.outcome, credits: r.credits, summary: r.summary });
91
+ emit("workbuddy-growth-travel", { uid: String(a.uid).slice(0, 8), outcome: r.outcome, credits: r.credits, reason });
92
+ } catch (e) {
93
+ travel.push({ uid: a.uid, outcome: "error", credits: 0, summary: String(e?.message || e).slice(0, 120) });
94
+ }
95
+ await sleep(1000);
96
+ }
97
+ const date = todayKey();
98
+ const creditTotal = growthRes.creditTotal + travel.reduce((s, r) => s + (r.credits || 0), 0);
99
+ try {
100
+ stateMod.writeStateImmediate(stateMod.defaultStateFile(), {
101
+ workbuddyGrowth: {
102
+ date, at: Date.now(), ok: growthRes.ok, credit: creditTotal, accounts: accounts.length,
103
+ travel: travel.map((t) => ({ uid: t.uid, outcome: t.outcome, credits: t.credits })),
104
+ },
105
+ });
106
+ } catch {}
107
+ emit("workbuddy-growth-done", { date, accounts: accounts.length, credit: creditTotal, ok: growthRes.ok, reason });
108
+ return { ok: true, creditTotal, growthRes, travel };
109
+ } catch (e) {
110
+ emit("workbuddy-growth-failed", { error: String(e?.message || e).slice(0, 200), reason });
111
+ return { ok: false, error: String(e?.message || e).slice(0, 200) };
112
+ } finally {
113
+ running = false;
114
+ }
115
+ }
116
+
117
+ // 启动补跑:昨天没跑且已过今天计划点,60s 后跑(等网络/上游就绪)
118
+ try {
119
+ const lastDate = stateMod.readState(stateMod.defaultStateFile())?.workbuddyGrowth?.date || "";
120
+ if (shouldGrowthCatchUp({ lastDate, hour })) {
121
+ setTimeout(() => { runOnce("catch-up").catch(() => {}); }, 60_000).unref?.();
122
+ console.log(`[workbuddy-growth] catch-up scheduled (last=${lastDate || "never"})`);
123
+ }
124
+ } catch {}
125
+ function arm() {
126
+ const delay = nextGrowthDelayMs(new Date(), hour);
127
+ setTimeout(() => {
128
+ runOnce("daily").catch(() => {}).finally(arm);
129
+ }, delay).unref?.();
130
+ }
131
+ arm();
132
+ return { enabled: true, hour, minute: GROWTH_MINUTE, runOnce };
133
+ }