@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.
@@ -0,0 +1,69 @@
1
+ {
2
+ "format": 1,
3
+ "project": "星云笔记 · 增长与 BI 协同图谱 (MTN / SKA 脱敏示范)",
4
+ "nodes": [
5
+ {
6
+ "id": "metric.d7_net_roi",
7
+ "type": "metric",
8
+ "title": "D7 净回本 ROI",
9
+ "aliases": ["D7 ROI", "净回本 ROI", "回本率"],
10
+ "summary": "衡量各投放渠道获客后第 7 日扣除退款与平台分成后的真实净回本效率。",
11
+ "formula": "NetD7Revenue / Spend (NetD7Revenue = GrossD7Revenue - Refund7d - AppStoreCut)",
12
+ "caveats": "小红书 2026-W01~W03 达标基准线为 0.45;报周报前须先核对内购到账延迟脉冲并剔除测试单。",
13
+ "allowedModes": ["direct", "summary", "confirm"],
14
+ "relations": [
15
+ { "rel": "构成指标", "targetId": "term.net_d7_revenue" },
16
+ { "rel": "历史异常注解", "targetId": "event.iap_delay_2026w03" },
17
+ { "rel": "关联商务边界", "targetId": "policy.q1_agency_rebate" }
18
+ ]
19
+ },
20
+ {
21
+ "id": "term.net_d7_revenue",
22
+ "type": "term",
23
+ "title": "NetD7Revenue (D7 净营收)",
24
+ "aliases": ["D7 净营收", "净营收"],
25
+ "summary": "已剔除自然量归因漂移、7 日内退款及渠道手续费后的净收款口径,严禁直接用毛流水替代。",
26
+ "formula": "GrossD7Revenue - RefundAmount7d - ChannelFee",
27
+ "caveats": "iOS 与安卓统一按支付回调确认时刻 T+1 冻结入账。",
28
+ "allowedModes": ["direct", "summary", "confirm"],
29
+ "relations": [
30
+ { "rel": "所属总指标", "targetId": "metric.d7_net_roi" }
31
+ ]
32
+ },
33
+ {
34
+ "id": "metric.paid_cac",
35
+ "type": "metric",
36
+ "title": "付费获客成本 (Paid CAC)",
37
+ "aliases": ["Paid CAC", "获客成本", "单客成本"],
38
+ "summary": "投放花费除以归因期内首购付费用户数,按周滚动核算。",
39
+ "formula": "Spend / NewPaidUsers",
40
+ "caveats": "仅统计公开渠道汇总值,严禁向外部合作方透露单用户订单明细。",
41
+ "allowedModes": ["direct", "summary", "confirm"],
42
+ "relations": []
43
+ },
44
+ {
45
+ "id": "event.iap_delay_2026w03",
46
+ "type": "event",
47
+ "title": "2026-W03 IAP 延迟脉冲",
48
+ "aliases": ["内购延迟", "W03 波动", "苹果延迟入账"],
49
+ "summary": "2026-W03 初次汇总曾出现苹果商店收据校验延迟 6 小时,已在 W03 周末补齐回填。",
50
+ "formula": "",
51
+ "caveats": "若核对周二午间快照发现 iOS ROI 骤降,先检查补齐脚本状态,勿误判为投放崩盘。",
52
+ "allowedModes": ["direct", "summary", "confirm"],
53
+ "relations": [
54
+ { "rel": "影响指标", "targetId": "metric.d7_net_roi" }
55
+ ]
56
+ },
57
+ {
58
+ "id": "policy.q1_agency_rebate",
59
+ "type": "policy",
60
+ "title": "2026 Q1 代理商阶梯返点与保底分成边界",
61
+ "aliases": ["Q1 返点", "阶梯返点", "保底分成", "返点政策"],
62
+ "summary": "2026 Q1 新签代理阶梯返点比例与保底条款尚在法务与财务终审,正式签约前对外延用 2025-Q4 公开框架。",
63
+ "formula": "",
64
+ "caveats": "未经负责人本人拍板确认,任何分身渠道不得对外承诺具体 Q1 返点百分比。",
65
+ "allowedModes": ["confirm"],
66
+ "relations": []
67
+ }
68
+ ]
69
+ }
package/lib/channels.js CHANGED
@@ -17,6 +17,8 @@ import {
17
17
  sanitizeSurfaceText
18
18
  } from '../shared/schema.js';
19
19
  import { createWeixinIlinkClient, validateWeixinBaseUrl } from './weixin-ilink.js';
20
+ import { parseOwnerMobileCommand } from './owner-notifier.js';
21
+ import { isPersonExpired } from './twin-engine.js';
20
22
 
21
23
  export { validateWeixinBaseUrl };
22
24
 
@@ -60,6 +62,7 @@ export function createChannelManager({
60
62
  createWebSocket = url => new globalThis.WebSocket(url),
61
63
  weixinBaseUrl = 'https://ilinkai.weixin.qq.com',
62
64
  allowLoopbackForTest = false,
65
+ ackDelayMs = 3500,
63
66
  logger = console
64
67
  }) {
65
68
  const sockets = new Map();
@@ -915,6 +918,28 @@ export function createChannelManager({
915
918
  */
916
919
  async function handleExternalEvent(channelId, event = {}) {
917
920
  if (event.isOwner) {
921
+ const isDm = Boolean(event.isOwnerDm) || event.chatType === 'dm';
922
+ const cmd = isDm && event.text ? parseOwnerMobileCommand(event.text) : null;
923
+ if (cmd && typeof engine.resolveRemoteOwnerCommand === 'function') {
924
+ const ownerEvtId = String(event.eventId || event.messageId || '').trim();
925
+ const ownerDedupKey = ownerEvtId ? `${channelId}:${ownerEvtId}` : '';
926
+ if (ownerDedupKey && (seenEventIds.has(ownerDedupKey) || store.hasProcessedEvent?.(ownerDedupKey))) {
927
+ return { action: 'ignored', reason: 'duplicate_event' };
928
+ }
929
+ if (ownerDedupKey) {
930
+ seenEventIds.add(ownerDedupKey);
931
+ if (seenEventIds.size > 500) seenEventIds.delete(seenEventIds.values().next().value);
932
+ await store.recordProcessedEvent?.(ownerDedupKey);
933
+ }
934
+ const replyMsg = await engine.resolveRemoteOwnerCommand(cmd);
935
+ if (channelId === 'ch-feishu' && officialConnectors?.sendFeishuMessage) {
936
+ await officialConnectors.sendFeishuMessage({
937
+ replyContext: event.replyContext || { openId: event.senderId, chatId: event.chatId },
938
+ text: replyMsg
939
+ }).catch(err => logger?.warn?.('[agent-twin] owner dm confirm failed:', err?.message));
940
+ }
941
+ return { action: 'owner_command_handled', command: cmd.kind, reply: replyMsg };
942
+ }
918
943
  engine.recordOwnerPresence(channelId, event.chatId || event.senderId);
919
944
  return { action: 'owner_presence_recorded' };
920
945
  }
@@ -1010,15 +1035,48 @@ export function createChannelManager({
1010
1035
  return { action: 'ignored', reason: 'not_whitelisted' };
1011
1036
  }
1012
1037
 
1013
- const res = await engine.handleInboundMessage({
1014
- personId: person.id,
1015
- question: text,
1016
- channelId,
1017
- threadKey: chatId,
1018
- isGroup,
1019
- mentionsBot: Boolean(event.mentionsBot),
1020
- replyContext: event.replyContext || {}
1021
- });
1038
+ const latestState = store.getState();
1039
+ const shouldArmAck = ackDelayMs > 0
1040
+ && channelId !== 'ch-web'
1041
+ && latestState.ackSlowTurns !== false
1042
+ && latestState.dutyMode !== 'off'
1043
+ && Boolean(person.enabled)
1044
+ && !isPersonExpired(person)
1045
+ && (!isGroup || Boolean(event.mentionsBot))
1046
+ && !(chatId && engine.isOwnerPresentRecently?.(channelId, chatId));
1047
+
1048
+ let ackSent = false;
1049
+ let ackTimer = null;
1050
+ if (shouldArmAck) {
1051
+ ackTimer = setTimeout(() => {
1052
+ ackSent = true;
1053
+ void sendOutbound(
1054
+ person,
1055
+ '收到,正在只读核对授权资料与数据,稍候几秒…',
1056
+ event.replyContext
1057
+ ).catch(err => logger?.warn?.('[agent-twin] slow-turn ack send failed:', err?.message));
1058
+ }, ackDelayMs);
1059
+ ackTimer.unref?.();
1060
+ }
1061
+
1062
+ let res;
1063
+ try {
1064
+ res = await engine.handleInboundMessage({
1065
+ personId: person.id,
1066
+ question: text,
1067
+ channelId,
1068
+ threadKey: chatId,
1069
+ isGroup,
1070
+ mentionsBot: Boolean(event.mentionsBot),
1071
+ replyContext: event.replyContext || {}
1072
+ });
1073
+ } finally {
1074
+ if (ackTimer) clearTimeout(ackTimer);
1075
+ }
1076
+
1077
+ if (ackSent) {
1078
+ res.ackSent = true;
1079
+ }
1022
1080
 
1023
1081
  if (['replied', 'paused', 'rate_limited'].includes(res.action) && res.reply) {
1024
1082
  res.outbound = await sendOutbound(person, res.reply, event.replyContext);
@@ -123,7 +123,7 @@ function formatToolStepDetail(toolName, input) {
123
123
  /**
124
124
  * Parse NDJSON lines from `dsh --profile headless --json`.
125
125
  */
126
- export function collectHeadlessEvents() {
126
+ export function collectHeadlessEvents(onStep = null) {
127
127
  const steps = new Map();
128
128
  let sessionId = '';
129
129
  let finalText = '';
@@ -159,12 +159,25 @@ export function collectHeadlessEvents() {
159
159
  case 'tool_start': {
160
160
  const toolName = String(event.tool || event.name || event.step || '').trim();
161
161
  const callId = String(event.callId || `${toolName}-${steps.size + 1}`);
162
+ const isNew = !steps.has(callId);
162
163
  const title = TOOL_LABELS.get(toolName) || '核对项目资料';
163
164
  const detail = formatToolStepDetail(toolName, event.input);
164
- steps.set(callId, {
165
+ const stepObj = {
165
166
  title,
166
- detail: detail || `${toolName || 'tool'} 只读执行`
167
+ detail: detail || `${toolName || 'tool'} 只读执行`,
168
+ toolName
169
+ };
170
+ steps.set(callId, {
171
+ title: stepObj.title,
172
+ detail: stepObj.detail
167
173
  });
174
+ if (isNew && typeof onStep === 'function') {
175
+ try {
176
+ onStep(stepObj);
177
+ } catch {
178
+ // ignore progress listener errors
179
+ }
180
+ }
168
181
  break;
169
182
  }
170
183
  case 'final':
@@ -342,13 +355,21 @@ export function createFullBloodTwinRunner({
342
355
  preparedHome = true;
343
356
  }
344
357
 
345
- async function invokeDshTurn({ sessionId = '', sandboxCwd, prompt, signal }) {
358
+ async function invokeDshTurn({ sessionId = '', sandboxCwd, prompt, signal, onProgress = null }) {
346
359
  const cred = credStatus();
347
360
  if (!cred.ready || !isExecutable(resolvedCliPath)) {
348
361
  throw new Error('Full-Blooded DSH runner credentials or CLI unavailable');
349
362
  }
350
363
  await ensureRunnerHome(cred);
351
364
 
365
+ if (typeof onProgress === 'function') {
366
+ try {
367
+ onProgress({ phase: 'sandbox', title: '启动只读隔离沙箱', detail: '核对白名单与规矩红线' });
368
+ } catch {
369
+ // ignore progress listener errors
370
+ }
371
+ }
372
+
352
373
  const runOnce = async sid => {
353
374
  const args = [
354
375
  '--profile',
@@ -367,7 +388,11 @@ export function createFullBloodTwinRunner({
367
388
  timer.unref?.();
368
389
  const combinedSignal = signal ? AbortSignal.any([signal, ac.signal]) : ac.signal;
369
390
 
370
- const collector = collectHeadlessEvents();
391
+ const collector = collectHeadlessEvents(step => {
392
+ if (typeof onProgress === 'function') {
393
+ onProgress({ phase: 'tool', ...step });
394
+ }
395
+ });
371
396
  let stderr = '';
372
397
  let child;
373
398
  try {
@@ -444,6 +469,7 @@ export function createFullBloodTwinRunner({
444
469
  question,
445
470
  externalKnowledge = [],
446
471
  includeFullPolicy = true,
472
+ onProgress = null,
447
473
  signal
448
474
  } = opts;
449
475
  if (typeof runnerOverride?.runCallerTurn === 'function') {
@@ -457,6 +483,7 @@ export function createFullBloodTwinRunner({
457
483
  question,
458
484
  externalKnowledge,
459
485
  includeFullPolicy,
486
+ onProgress,
460
487
  signal
461
488
  });
462
489
  }
@@ -499,7 +526,7 @@ export function createFullBloodTwinRunner({
499
526
  ].join('\n');
500
527
 
501
528
  const prompt = `${harnessBlock}${extLines}\n\n来访者提问:\n${question}`;
502
- const raw = await invokeDshTurn({ sessionId, sandboxCwd, prompt, signal });
529
+ const raw = await invokeDshTurn({ sessionId, sandboxCwd, prompt, signal, onProgress });
503
530
  const parsed = parseTwinDecision(raw.text);
504
531
  return {
505
532
  ...parsed,