@oxmumu3/dsh-agent-twin 0.6.0 → 0.6.2

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/lib/host.js CHANGED
@@ -10,6 +10,8 @@ import { createChannelManager } from './channels.js';
10
10
  import { registerTwinRoutes } from './routes.js';
11
11
  import { createFullBloodTwinRunner } from './fullblood-runner.js';
12
12
  import { createOfficialConnectorsBridge } from './official-connectors.js';
13
+ import { createMtnKnowledgeProvider } from './mtn-provider.js';
14
+ import { createOwnerNotifier } from './owner-notifier.js';
13
15
 
14
16
  function readConfigPort(config) {
15
17
  const raw = config?.guestPort;
@@ -52,6 +54,20 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
52
54
  const fullBloodRunner = overrides.fullBloodRunner === false
53
55
  ? null
54
56
  : (overrides.fullBloodRunner || createFullBloodTwinRunner({ ctx, paths, logger }));
57
+ const mtnProvider = overrides.mtnProvider === false
58
+ ? null
59
+ : (overrides.mtnProvider || createMtnKnowledgeProvider({ store, logger }));
60
+ if (mtnProvider) {
61
+ registerKnowledgeProvider(mtnProvider);
62
+ }
63
+ const ownerNotifier = overrides.ownerNotifier === false
64
+ ? null
65
+ : (overrides.ownerNotifier || createOwnerNotifier({
66
+ store,
67
+ officialConnectors,
68
+ execFileImpl: overrides.execFileImpl,
69
+ logger
70
+ }));
55
71
 
56
72
  let channelManager = null;
57
73
  let guestServer = null;
@@ -95,6 +111,7 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
95
111
  logger,
96
112
  llmResponder: overrides.llmResponder,
97
113
  fullBloodRunner,
114
+ ownerNotifier,
98
115
  knowledgeProviders: () => [...knowledgeProviders],
99
116
  onDispatchOutbound: async (person, text, replyContext) => {
100
117
  if (!channelManager) return { delivered: false };
@@ -106,15 +123,25 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
106
123
  guestServer = createGuestServer({
107
124
  host: overrides.guestHost || '127.0.0.1',
108
125
  port: overrides.guestPort ?? readConfigPort(config),
126
+ publicBurstLimit: overrides.publicBurstLimit,
109
127
  getState: () => store.getState(),
110
128
  readCallerThread: callerId => store.readCallerThread(callerId),
129
+ readVisitorThread: visitorId => store.readVisitorThread(visitorId),
111
130
  allSecretValues: () => store.allSecretValues(),
112
- onGuestAsk: async (person, question) => {
131
+ onGuestAsk: async (person, question, opts = {}) => {
113
132
  return engine.handleInboundMessage({
114
133
  personId: person.id,
115
134
  question,
116
135
  channelId: 'ch-web',
117
- threadKey: person.id
136
+ threadKey: person.id,
137
+ onProgress: opts.onProgress
138
+ });
139
+ },
140
+ onPublicAsk: async (visitorId, question, opts = {}) => {
141
+ return engine.handlePublicVisitorMessage({
142
+ visitorId,
143
+ question,
144
+ onProgress: opts.onProgress
118
145
  });
119
146
  },
120
147
  logger
@@ -130,6 +157,8 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
130
157
  channelManager,
131
158
  officialConnectors,
132
159
  fullBloodRunner,
160
+ mtnProvider,
161
+ ownerNotifier,
133
162
  registerKnowledgeProvider,
134
163
  dispose
135
164
  };
@@ -145,6 +174,7 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
145
174
  createWebSocket: overrides.createWebSocket,
146
175
  weixinBaseUrl: overrides.weixinBaseUrl,
147
176
  allowLoopbackForTest: overrides.allowLoopbackForTest,
177
+ ackDelayMs: overrides.ackDelayMs,
148
178
  logger
149
179
  });
150
180
  await channelManager.start();
@@ -159,6 +189,8 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
159
189
  channelManager,
160
190
  officialConnectors,
161
191
  fullBloodRunner,
192
+ mtnProvider,
193
+ ownerNotifier,
162
194
  registerKnowledgeProvider,
163
195
  dispose
164
196
  };
@@ -171,7 +203,8 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
171
203
  store,
172
204
  engine,
173
205
  channelManager,
174
- guestServer
206
+ guestServer,
207
+ mtnProvider
175
208
  });
176
209
  }
177
210
 
@@ -183,6 +216,8 @@ export async function mountTwinHost(ctx, config = {}, overrides = {}) {
183
216
  channelManager,
184
217
  officialConnectors,
185
218
  fullBloodRunner,
219
+ mtnProvider,
220
+ ownerNotifier,
186
221
  registerKnowledgeProvider,
187
222
  dispose
188
223
  };
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Built-in MTN / SKA Semantic Knowledge Graph Provider (`lib/mtn-provider.js`):
3
+ * - Discovers `mtn/*.json`, `ska/*.json`, `*.mtn.json` inside mounted read-only projects
4
+ * and owner-curated nodes at `$DSH_HOME/agent-twin/mtn-graph.json`.
5
+ * - Enforces caller capability authorization and `allowedModes` filtering before expanding
6
+ * 1-hop semantic relations (`公式` / `口径注意` / `受保护关联边界提示`) into caller turns.
7
+ */
8
+ import { createHash, randomUUID } from 'node:crypto';
9
+ import { chmod, lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
10
+ import { dirname, join, resolve } from 'node:path';
11
+ import { IGNORED_DIR_NAMES, PERSON_MODES, sanitizeSurfaceText } from '../shared/schema.js';
12
+
13
+ const MAX_GRAPH_BYTES = 256 * 1024;
14
+ const MAX_SCAN_DEPTH = 3;
15
+
16
+ function tokenize(text) {
17
+ const s = String(text || '').toLowerCase();
18
+ const tokens = new Set(s.match(/[a-z0-9_.-]{2,}/g) || []);
19
+ const cjk = s.match(/[\u4e00-\u9fff]{2,}/g) || [];
20
+ for (const run of cjk) {
21
+ tokens.add(run);
22
+ for (let i = 0; i <= run.length - 2; i++) {
23
+ tokens.add(run.slice(i, i + 2));
24
+ }
25
+ }
26
+ return [...tokens];
27
+ }
28
+
29
+ function normalizeNode(raw, defaultProjectId = '') {
30
+ if (!raw || typeof raw !== 'object') return null;
31
+ const title = sanitizeSurfaceText(String(raw.title || raw.name || '').trim());
32
+ const summary = sanitizeSurfaceText(String(raw.summary || raw.definition || raw.description || '').trim());
33
+ if (!title && !summary) return null;
34
+
35
+ const id = String(raw.id || '').trim() || `mtn-${createHash('sha1').update(`${defaultProjectId}:${title}`).digest('hex').slice(0, 8)}`;
36
+ const allowedModesRaw = Array.isArray(raw.allowedModes) ? raw.allowedModes : [];
37
+ const allowedModes = allowedModesRaw.filter(m => PERSON_MODES.includes(m));
38
+ const relations = Array.isArray(raw.relations)
39
+ ? raw.relations
40
+ .filter(r => r && typeof r === 'object' && (r.targetId || r.target))
41
+ .map(r => ({
42
+ rel: sanitizeSurfaceText(String(r.rel || r.type || '关联').trim()) || '关联',
43
+ targetId: String(r.targetId || r.target).trim()
44
+ }))
45
+ : [];
46
+
47
+ return {
48
+ id,
49
+ projectId: typeof raw.projectId === 'string' && raw.projectId.trim() ? raw.projectId.trim() : defaultProjectId,
50
+ type: ['metric', 'term', 'policy', 'entity', 'event'].includes(raw.type) ? raw.type : 'term',
51
+ title: title || id,
52
+ aliases: Array.isArray(raw.aliases)
53
+ ? raw.aliases.map(a => sanitizeSurfaceText(String(a || '').trim())).filter(Boolean).slice(0, 16)
54
+ : [],
55
+ summary,
56
+ formula: sanitizeSurfaceText(String(raw.formula || '').trim()),
57
+ caveats: sanitizeSurfaceText(String(raw.caveats || '').trim()),
58
+ allowedModes: allowedModes.length > 0 ? allowedModes : ['direct', 'summary', 'confirm'],
59
+ capIds: Array.isArray(raw.capIds) ? raw.capIds.map(x => String(x || '').trim()).filter(Boolean) : [],
60
+ relations
61
+ };
62
+ }
63
+
64
+ function isModeAllowed(node, mode) {
65
+ if (!mode) return true;
66
+ if (!Array.isArray(node.allowedModes) || node.allowedModes.length === 0) return true;
67
+ return node.allowedModes.includes(mode);
68
+ }
69
+
70
+ async function safeAtomicWrite(filePath, payload) {
71
+ await mkdir(dirname(filePath), { recursive: true, mode: 0o700 });
72
+ const tmpPath = `${filePath}.tmp.${process.pid}.${randomUUID().slice(0, 8)}`;
73
+ try {
74
+ await writeFile(tmpPath, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
75
+ await chmod(tmpPath, 0o600);
76
+ await rename(tmpPath, filePath);
77
+ } catch (err) {
78
+ await unlink(tmpPath).catch(() => {});
79
+ throw err;
80
+ }
81
+ }
82
+
83
+ export function createMtnKnowledgeProvider({ store, logger = console }) {
84
+ const customGraphPath = join(store.paths.rootDir, 'mtn-graph.json');
85
+ const fileCache = new Map();
86
+
87
+ async function readGraphFileNodes(filePath, defaultProjectId = '') {
88
+ try {
89
+ const st = await lstat(filePath);
90
+ if (st.isSymbolicLink() || !st.isFile() || st.size > MAX_GRAPH_BYTES) return [];
91
+ const cacheKey = `${filePath}:${Math.round(st.mtimeMs)}:${st.size}:${defaultProjectId}`;
92
+ if (fileCache.has(cacheKey)) return fileCache.get(cacheKey);
93
+ const raw = await readFile(filePath, 'utf8');
94
+ const parsed = JSON.parse(raw);
95
+ const list = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.nodes) ? parsed.nodes : []);
96
+ const normalized = list.map(n => normalizeNode(n, defaultProjectId)).filter(Boolean);
97
+ if (fileCache.size > 64) fileCache.clear();
98
+ fileCache.set(cacheKey, normalized);
99
+ return normalized;
100
+ } catch {
101
+ return [];
102
+ }
103
+ }
104
+
105
+ async function findProjectGraphFiles(rootPath) {
106
+ const absRoot = resolve(String(rootPath || ''));
107
+ try {
108
+ const st = await lstat(absRoot);
109
+ if (st.isSymbolicLink() || !st.isDirectory()) return [];
110
+ } catch {
111
+ return [];
112
+ }
113
+
114
+ const found = [];
115
+ async function walk(dir, relPrefix, depth) {
116
+ if (depth > MAX_SCAN_DEPTH || found.length >= 20) return;
117
+ let entries;
118
+ try {
119
+ entries = await readdir(dir, { withFileTypes: true });
120
+ } catch {
121
+ return;
122
+ }
123
+ for (const ent of entries) {
124
+ if (found.length >= 20) break;
125
+ if (ent.name === '.' || ent.name === '..' || ent.name.startsWith('.')) continue;
126
+ const full = join(dir, ent.name);
127
+ let st;
128
+ try {
129
+ st = await lstat(full);
130
+ } catch {
131
+ continue;
132
+ }
133
+ if (st.isSymbolicLink()) continue;
134
+ const rel = relPrefix ? `${relPrefix}/${ent.name}` : ent.name;
135
+ if (ent.isDirectory()) {
136
+ if (!IGNORED_DIR_NAMES.has(ent.name)) {
137
+ await walk(full, rel, depth + 1);
138
+ }
139
+ continue;
140
+ }
141
+ if (!st.isFile()) continue;
142
+ const lower = rel.toLowerCase();
143
+ if (
144
+ lower.endsWith('.mtn.json') ||
145
+ ((lower.startsWith('mtn/') || lower.startsWith('ska/')) && lower.endsWith('.json'))
146
+ ) {
147
+ found.push(full);
148
+ }
149
+ }
150
+ }
151
+ await walk(absRoot, '', 0);
152
+ return found;
153
+ }
154
+
155
+ async function loadAllNodes() {
156
+ const state = store.getState();
157
+ const out = [];
158
+ const customNodes = await readGraphFileNodes(customGraphPath, '');
159
+ out.push(...customNodes);
160
+
161
+ for (const mp of state.mountedProjects || []) {
162
+ if (!mp?.rootPath) continue;
163
+ const files = await findProjectGraphFiles(mp.rootPath);
164
+ for (const file of files) {
165
+ const nodes = await readGraphFileNodes(file, mp.id);
166
+ out.push(...nodes);
167
+ }
168
+ }
169
+
170
+ // Deduplicate by id (custom graph takes precedence when ids collide)
171
+ const byId = new Map();
172
+ for (const n of out) {
173
+ if (!byId.has(n.id)) byId.set(n.id, n);
174
+ }
175
+ return [...byId.values()];
176
+ }
177
+
178
+ async function listNodes() {
179
+ return loadAllNodes();
180
+ }
181
+
182
+ async function upsertNodes(inputNodes = []) {
183
+ const incoming = (Array.isArray(inputNodes) ? inputNodes : [inputNodes])
184
+ .map(n => normalizeNode(n, n?.projectId || ''))
185
+ .filter(Boolean);
186
+ if (incoming.length === 0) {
187
+ throw new Error('缺少有效的 MTN 知识节点内容');
188
+ }
189
+ const existing = await readGraphFileNodes(customGraphPath, '');
190
+ const merged = new Map(existing.map(n => [n.id, n]));
191
+ for (const n of incoming) {
192
+ merged.set(n.id, n);
193
+ }
194
+ const nextNodes = [...merged.values()];
195
+ await safeAtomicWrite(customGraphPath, { format: 1, updatedAt: new Date().toISOString(), nodes: nextNodes });
196
+ fileCache.clear();
197
+ return { count: incoming.length, totalCustomNodes: nextNodes.length, nodes: nextNodes };
198
+ }
199
+
200
+ async function query(question, { person = null, activeCaps = null } = {}) {
201
+ const q = String(question || '').trim();
202
+ if (!q) return [];
203
+ const qLower = q.toLowerCase();
204
+ const qTokens = tokenize(q);
205
+ if (qTokens.length === 0) return [];
206
+
207
+ const state = store.getState();
208
+ const activeSet = Array.isArray(activeCaps) ? new Set(activeCaps) : null;
209
+ const enabledCaps = (state.capabilities || []).filter(c => c?.enabled && (!activeSet || activeSet.has(c.id)));
210
+ const authorizedProjectIds = new Set(enabledCaps.map(c => c.projectId));
211
+
212
+ const allNodes = await loadAllNodes();
213
+ if (allNodes.length === 0) return [];
214
+
215
+ const authorizedNodes = allNodes.filter(node => {
216
+ if (node.projectId && !authorizedProjectIds.has(node.projectId)) return false;
217
+ if (!node.projectId && person?.isPublicVisitor) return false;
218
+ if (!node.projectId && activeSet && activeSet.size === 0) return false;
219
+ if (node.capIds.length > 0 && activeSet && !node.capIds.some(cid => activeSet.has(cid))) return false;
220
+ return true;
221
+ });
222
+
223
+ const nodeById = new Map(authorizedNodes.map(n => [n.id, n]));
224
+ const mode = person?.mode || '';
225
+ const scored = [];
226
+
227
+ for (const node of authorizedNodes) {
228
+ if (!isModeAllowed(node, mode)) continue;
229
+
230
+ let score = 0;
231
+ const titleLower = node.title.toLowerCase();
232
+ if (titleLower && qLower.includes(titleLower)) score += 8;
233
+ for (const alias of node.aliases) {
234
+ if (alias && qLower.includes(alias.toLowerCase())) score += 8;
235
+ }
236
+
237
+ const headingHay = `${titleLower} ${node.aliases.join(' ').toLowerCase()}`;
238
+ const bodyHay = `${node.summary} ${node.formula} ${node.caveats}`.toLowerCase();
239
+ for (const tok of qTokens) {
240
+ if (headingHay.includes(tok)) score += 4;
241
+ else if (bodyHay.includes(tok)) score += 1;
242
+ }
243
+
244
+ if (score >= 4 || (score >= 2 && qTokens.length <= 2)) {
245
+ scored.push({ score, node });
246
+ }
247
+ }
248
+
249
+ scored.sort((a, b) => b.score - a.score);
250
+
251
+ return scored.slice(0, 4).map(({ score, node }) => {
252
+ const parts = [node.summary];
253
+ if (node.formula) parts.push(`计算公式:${node.formula}`);
254
+ if (node.caveats) parts.push(`口径注意:${node.caveats}`);
255
+
256
+ for (const rel of node.relations || []) {
257
+ const target = nodeById.get(rel.targetId);
258
+ if (!target) continue;
259
+ if (isModeAllowed(target, mode)) {
260
+ const extra = [target.summary, target.formula ? `公式:${target.formula}` : ''].filter(Boolean).join(';');
261
+ parts.push(`[关联${rel.rel}: ${target.title} — ${extra}]`);
262
+ } else {
263
+ parts.push(`[边界提示: 关联项「${target.title}」受当前授权档位保护,若被追问细节须触发 REDLINE 转负责人拍板]`);
264
+ }
265
+ }
266
+
267
+ return {
268
+ nodeId: node.id,
269
+ type: node.type,
270
+ score,
271
+ source: 'MTN 语义图谱',
272
+ title: node.title,
273
+ summary: sanitizeSurfaceText(parts.filter(Boolean).join(' | '))
274
+ };
275
+ });
276
+ }
277
+
278
+ return {
279
+ name: 'MTN 语义图谱',
280
+ query,
281
+ listNodes,
282
+ upsertNodes
283
+ };
284
+ }
@@ -350,7 +350,11 @@ export function createOfficialConnectorsBridge({
350
350
  const event = extractFeishuIncoming(parsed);
351
351
  if (!event || !event.text) return;
352
352
  if (ownerOpenId && event.senderId === ownerOpenId) {
353
- onOwnerActivity?.(event.chatId);
353
+ if (event.chatType === 'group') {
354
+ onOwnerActivity?.(event.chatId);
355
+ } else {
356
+ onMessage?.({ ...event, isOwner: true, isOwnerDm: true });
357
+ }
354
358
  return;
355
359
  }
356
360
  onMessage?.(event);
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Mobile Owner Push & Remote Phone Approval Loop (`lib/owner-notifier.js`):
3
+ * - Sends concise `#CODE` pending approval briefs to the owner's Feishu DM (via 0.2.3 official
4
+ * `lark-cli`) and optionally via local `dsh-wechat` when `ownerNotify.wechat === true`.
5
+ * - Parses crisp owner DM reply commands (`批准 #CODE`, `改 #CODE:...`, `记规矩 #CODE:...`,
6
+ * `忽略 #CODE`, `待办`) so owners can approve & dispatch from their phone in seconds.
7
+ */
8
+ import { execFile } from 'node:child_process';
9
+ import { promisify } from 'node:util';
10
+ import { redactSecrets, sanitizeSurfaceText } from '../shared/schema.js';
11
+
12
+ const execFileAsync = promisify(execFile);
13
+
14
+ export function makeApprovalShortCode(id) {
15
+ const clean = String(id || '').replace(/[^A-Za-z0-9]/g, '').toUpperCase();
16
+ if (clean.length >= 4) return clean.slice(-4);
17
+ return clean.padStart(4, '0');
18
+ }
19
+
20
+ /**
21
+ * Parse an explicit 1-on-1 owner DM approval command. Returns `null` for ordinary chat.
22
+ */
23
+ export function parseOwnerMobileCommand(rawText) {
24
+ const text = String(rawText || '').trim();
25
+ if (!text) return null;
26
+
27
+ if (/^(?:待办|待拍板|审批列表)$/i.test(text)) {
28
+ return { kind: 'list', code: '', text: '' };
29
+ }
30
+
31
+ const approveMatch = text.match(/^(?:批准|同意|通过|准奏)(?:\s*#?([A-Za-z0-9_-]{3,20}))?$/i);
32
+ if (approveMatch) {
33
+ return { kind: 'approve', code: (approveMatch[1] || '').toUpperCase(), text: '' };
34
+ }
35
+
36
+ const ruleMatch = text.match(/^(?:记规矩|定规矩)(?:\s*#?([A-Za-z0-9_-]{3,20}))?\s*[::]\s*([\s\S]+)$/i);
37
+ if (ruleMatch) {
38
+ return { kind: 'rule', code: (ruleMatch[1] || '').toUpperCase(), text: ruleMatch[2].trim() };
39
+ }
40
+
41
+ const editMatch = text.match(/^(?:改|修改|回复)(?:\s*#?([A-Za-z0-9_-]{3,20}))?\s*[::]\s*([\s\S]+)$/i);
42
+ if (editMatch) {
43
+ return { kind: 'edit', code: (editMatch[1] || '').toUpperCase(), text: editMatch[2].trim() };
44
+ }
45
+
46
+ const dismissMatch = text.match(/^(?:忽略|驳回|不回)(?:\s*#?([A-Za-z0-9_-]{3,20}))?$/i);
47
+ if (dismissMatch) {
48
+ return { kind: 'dismiss', code: (dismissMatch[1] || '').toUpperCase(), text: '' };
49
+ }
50
+
51
+ return null;
52
+ }
53
+
54
+ export function createOwnerNotifier({
55
+ store,
56
+ officialConnectors = null,
57
+ execFileImpl = execFileAsync,
58
+ dshWechatBin = 'dsh-wechat',
59
+ logger = console
60
+ }) {
61
+ async function notifyPendingApproval(approval) {
62
+ if (!approval || typeof approval !== 'object') return { skipped: true };
63
+ const state = store.getState();
64
+ const cfg = state.ownerNotify || { feishu: true, wechat: false };
65
+ const code = approval.shortCode || makeApprovalShortCode(approval.id);
66
+ const secrets = store.allSecretValues();
67
+
68
+ const who = redactSecrets(sanitizeSurfaceText(approval.personName || '外部来访者'), secrets);
69
+ const chan = redactSecrets(sanitizeSurfaceText(approval.channel || '外部通道'), secrets);
70
+ const tag = redactSecrets(sanitizeSurfaceText(approval.tag || '待拍板'), secrets);
71
+ const q = redactSecrets(sanitizeSurfaceText(approval.question || ''), secrets).slice(0, 120);
72
+ const draft = redactSecrets(sanitizeSurfaceText(approval.draft || ''), secrets).slice(0, 260);
73
+
74
+ const title = `AI 分身待拍板 #${code}(${tag})`;
75
+ const body = [
76
+ `来访对象:${who}(${chan})`,
77
+ `对方提问:${q}`,
78
+ `拟回草稿:${draft}`,
79
+ '',
80
+ `手机直接回复本条私信即可处理:`,
81
+ `• 批准 #${code}`,
82
+ `• 改 #${code}:你的最终回复内容`,
83
+ `• 记规矩 #${code}:最终回复并沉淀长期规矩`,
84
+ `• 忽略 #${code}`
85
+ ].join('\n');
86
+
87
+ let feishuDelivered = false;
88
+ let wechatDelivered = false;
89
+
90
+ if (cfg.feishu !== false && officialConnectors && typeof officialConnectors.probeFeishu === 'function') {
91
+ try {
92
+ const probe = await officialConnectors.probeFeishu();
93
+ const ownerOpenId = cfg.feishuOpenId || probe?.openId;
94
+ if (probe?.connected && ownerOpenId && typeof officialConnectors.sendFeishuMessage === 'function') {
95
+ const sent = await officialConnectors.sendFeishuMessage({
96
+ replyContext: { openId: ownerOpenId },
97
+ text: `**${title}**\n\n${body}`
98
+ });
99
+ feishuDelivered = Boolean(sent?.delivered);
100
+ }
101
+ } catch (err) {
102
+ logger?.warn?.('[agent-twin] owner feishu push failed:', err?.message);
103
+ }
104
+ }
105
+
106
+ if (cfg.wechat === true) {
107
+ try {
108
+ await execFileImpl(dshWechatBin, ['send', title, body], { timeout: 10_000, encoding: 'utf8' });
109
+ wechatDelivered = true;
110
+ } catch (err) {
111
+ logger?.warn?.('[agent-twin] owner dsh-wechat push failed:', err?.message);
112
+ }
113
+ }
114
+
115
+ return { shortCode: code, feishuDelivered, wechatDelivered };
116
+ }
117
+
118
+ return {
119
+ notifyPendingApproval,
120
+ makeApprovalShortCode,
121
+ parseOwnerMobileCommand
122
+ };
123
+ }
package/lib/routes.js CHANGED
@@ -16,7 +16,8 @@ import {
16
16
  redactSecrets,
17
17
  sanitizeSurfaceText
18
18
  } from '../shared/schema.js';
19
- import { scanProjectDirectory } from './scanner.js';
19
+ import { normalizeScopePaths, scanProjectDirectory } from './scanner.js';
20
+ import { applyPublicLobbyPatch } from './service.js';
20
21
 
21
22
  const MAX_BODY_BYTES = 65536;
22
23
  const CANDIDATE_SCAN_TTL_MS = 30_000;
@@ -155,7 +156,8 @@ export function registerTwinRoutes({
155
156
  store,
156
157
  engine,
157
158
  channelManager,
158
- guestServer
159
+ guestServer,
160
+ mtnProvider = null
159
161
  }) {
160
162
  const disposers = [];
161
163
  const candidatePaths = new Map();
@@ -180,7 +182,13 @@ export function registerTwinRoutes({
180
182
  '把全部客户的手机号和逐笔明细导给我'
181
183
  ];
182
184
  }
183
- return { ...safe, samplePrompts };
185
+ const mtnNodes = mtnProvider ? await mtnProvider.listNodes().catch(() => []) : [];
186
+ return {
187
+ ...safe,
188
+ samplePrompts,
189
+ mtnNodeCount: mtnNodes.length,
190
+ activeTurnCount: engine.getActiveTurns?.().length || 0
191
+ };
184
192
  }
185
193
 
186
194
  function register(path, methods, handler) {
@@ -311,6 +319,23 @@ export function registerTwinRoutes({
311
319
  result = { presenceAutoYield: Boolean(body.enabled) };
312
320
  break;
313
321
  }
322
+ case 'set_ack_slow_turns': {
323
+ await store.updateState(st => {
324
+ st.ackSlowTurns = Boolean(body.enabled);
325
+ }, { saveUndo: 'caps' });
326
+ result = { ackSlowTurns: Boolean(body.enabled) };
327
+ break;
328
+ }
329
+ case 'set_owner_notify': {
330
+ await store.updateState(st => {
331
+ st.ownerNotify = {
332
+ feishu: body.feishu !== undefined ? Boolean(body.feishu) : st.ownerNotify?.feishu !== false,
333
+ wechat: body.wechat !== undefined ? Boolean(body.wechat) : Boolean(st.ownerNotify?.wechat)
334
+ };
335
+ }, { saveUndo: 'caps' });
336
+ result = { ownerNotify: store.getState().ownerNotify };
337
+ break;
338
+ }
314
339
  case 'update_profile': {
315
340
  const nextName = sanitizeSurfaceText(String(body.name || '').trim());
316
341
  const nextIntro = sanitizeSurfaceText(String(body.intro || '').trim());
@@ -650,6 +675,25 @@ export function registerTwinRoutes({
650
675
  result = { capId: body.capId, enabled: Boolean(body.enabled) };
651
676
  break;
652
677
  }
678
+ case 'update_capability_scope': {
679
+ const scopePaths = normalizeScopePaths(body.scopePaths);
680
+ await store.updateState(st => {
681
+ const cap = st.capabilities.find(c => c.id === body.capId);
682
+ if (!cap) throw new Error('未找到对应能力项');
683
+ cap.scopePaths = scopePaths;
684
+ }, { saveUndo: 'caps' });
685
+ result = { capId: body.capId, scopePaths };
686
+ break;
687
+ }
688
+ case 'list_mtn_nodes': {
689
+ result = { nodes: mtnProvider ? await mtnProvider.listNodes() : [] };
690
+ break;
691
+ }
692
+ case 'upsert_mtn_nodes': {
693
+ if (!mtnProvider) throw new Error('当前运行时未启用 MTN 知识图谱提供器');
694
+ result = await mtnProvider.upsertNodes(body.nodes || body.node);
695
+ break;
696
+ }
653
697
  case 'unmount_project': {
654
698
  await store.updateState(st => {
655
699
  const idx = st.mountedProjects.findIndex(m => m.id === body.projectId);
@@ -699,6 +743,12 @@ export function registerTwinRoutes({
699
743
  result = { deleted: body.ruleId };
700
744
  break;
701
745
  }
746
+ case 'configure_public_lobby': {
747
+ result = {
748
+ publicLobby: await applyPublicLobbyPatch(store, body.publicLobby || body)
749
+ };
750
+ break;
751
+ }
702
752
  default:
703
753
  return jsonResponse({ ok: false, error: `未知操作:${action}` }, 400);
704
754
  }