@twinsearth/dsh-fang 3.1.15 → 3.1.17

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/client.js CHANGED
@@ -479,6 +479,19 @@ window.__ModuleLoader__.load({
479
479
  let timer = 0
480
480
  let observer = null
481
481
  let observed = null
482
+ let fallbackEl = null
483
+ let reported = false
484
+
485
+ // v3.1.17:客户端自报「已加载」,仅时间戳(供 /fang/adapter/identity 的 clientLoaded)。
486
+ const reportLoaded = () => {
487
+ if (reported) return
488
+ reported = true
489
+ try {
490
+ void fetch('/fang/adapter/client-report', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
491
+ .catch(() => { /* 老宿主没有该路由:忽略 */ })
492
+ } catch { /* ignore */ }
493
+ }
494
+
482
495
  const findBrandName = () => {
483
496
  const candidates = document.querySelectorAll('[class*="brandName"]')
484
497
  for (const node of candidates) {
@@ -502,50 +515,107 @@ window.__ModuleLoader__.load({
502
515
  if (el.title !== title) el.title = title
503
516
  if (el.getAttribute('aria-label') !== title) el.setAttribute('aria-label', title)
504
517
  }
505
- const place = () => {
506
- if (!document || !document.body) return false
507
- let el = document.getElementById(WEB_ROLE_BADGE_ID)
508
- if (el && el.isConnected && el.parentElement) { paint(el); return true }
509
- const brandName = findBrandName()
510
- if (!brandName || !brandName.parentElement) return false
511
- el = document.createElement('span')
518
+
519
+ const createBadge = () => {
520
+ const el = document.createElement('span')
512
521
  el.id = WEB_ROLE_BADGE_ID
513
522
  el.className = 'fang-web-role'
514
523
  el.setAttribute('role', 'status')
515
524
  el.setAttribute('aria-live', 'polite')
525
+ return el
526
+ }
527
+
528
+ /** 首选:宿主侧栏品牌词标右侧。 */
529
+ const placeInBrand = () => {
530
+ if (!document || !document.body) return false
531
+ const existing = document.getElementById(WEB_ROLE_BADGE_ID)
532
+ if (existing && existing.isConnected && existing.parentElement && existing !== fallbackEl) { paint(existing); return true }
533
+ const brandName = findBrandName()
534
+ if (!brandName || !brandName.parentElement) return false
535
+ if (fallbackEl) { try { fallbackEl.remove() } catch { /* ignore */ } fallbackEl = null }
536
+ const el = createBadge()
516
537
  brandName.parentElement.insertBefore(el, brandName.nextSibling)
517
538
  paint(el)
518
- // 宿主重渲染只可能发生在品牌行内部:盯住它的父节点,摘掉就补回。
519
- if (observer) { try { observer.disconnect() } catch { /* ignore */ } }
520
- observer = new MutationObserver(() => { try { place() } catch { /* ignore */ } })
521
- try { observer.observe(brandName.parentElement, { childList: true, subtree: true }) } catch { /* ignore */ }
522
- observed = brandName.parentElement
539
+ observe(brandName.parentElement)
523
540
  return true
524
541
  }
542
+
543
+ /**
544
+ * 兜底(v3.1.17):品牌槽不存在或被宿主整段移除时,挂到 body 右上角固定角标。
545
+ * 只在 3 次重试仍失败后启用,避免与正常挂载抢位置。
546
+ */
547
+ const placeFallback = () => {
548
+ if (!document || !document.body) return false
549
+ if (fallbackEl && fallbackEl.isConnected) { paint(fallbackEl); return true }
550
+ const el = createBadge()
551
+ el.classList.add('fang-web-role--fallback')
552
+ el.style.position = 'fixed'
553
+ el.style.top = '8px'
554
+ el.style.right = '12px'
555
+ el.style.zIndex = '2147483000'
556
+ el.style.padding = '2px 8px'
557
+ el.style.borderRadius = '10px'
558
+ el.style.fontSize = '11px'
559
+ el.style.fontWeight = '600'
560
+ el.style.pointerEvents = 'none'
561
+ el.style.background = 'rgba(0,0,0,.55)'
562
+ document.body.append(el)
563
+ fallbackEl = el
564
+ paint(el)
565
+ observe(document.body)
566
+ return true
567
+ }
568
+
569
+ const observe = (node) => {
570
+ if (!node) return
571
+ if (observed === node && observer) return
572
+ if (observer) { try { observer.disconnect() } catch { /* ignore */ } }
573
+ observer = new MutationObserver(() => {
574
+ try { if (!placeInBrand()) placeFallback() } catch { /* ignore */ }
575
+ })
576
+ try { observer.observe(node, { childList: true, subtree: true }) } catch { /* ignore */ }
577
+ observed = node
578
+ }
579
+
525
580
  const install = () => {
526
- if (place()) { if (timer) { clearInterval(timer); timer = 0 } return true }
581
+ const ok = placeInBrand()
582
+ if (ok) { if (timer) { clearInterval(timer); timer = 0 } return true }
527
583
  return false
528
584
  }
529
- install()
530
- // 侧栏可能晚于插件激活渲染;最多等 20s,不无限占定时器。
531
- if (!document.getElementById(WEB_ROLE_BADGE_ID)) {
585
+
586
+ reportLoaded()
587
+
588
+ // 3 次重试(250ms 间隔)后才兜底;宿主侧栏渲染通常在第一帧后就绪。
589
+ if (!install()) {
532
590
  let tries = 0
533
591
  timer = setInterval(() => {
534
592
  tries += 1
535
- if (install() || tries >= 80) { clearInterval(timer); timer = 0 }
593
+ const done = install()
594
+ if (!done && tries >= 3) {
595
+ clearInterval(timer)
596
+ timer = 0
597
+ placeFallback()
598
+ } else if (done) {
599
+ clearInterval(timer)
600
+ timer = 0
601
+ }
536
602
  }, 250)
537
603
  }
604
+
538
605
  void (async () => {
539
606
  const detected = await detectWebRole()
540
607
  if (!detected) return
541
608
  role = detected
542
- install()
609
+ if (!install()) placeFallback()
543
610
  })()
611
+
544
612
  return () => {
545
613
  if (timer) { clearInterval(timer); timer = 0 }
546
614
  if (observer) { try { observer.disconnect() } catch { /* ignore */ } observer = null }
547
615
  void observed
548
616
  try { document.getElementById(WEB_ROLE_BADGE_ID)?.remove() } catch { /* ignore */ }
617
+ try { fallbackEl?.remove() } catch { /* ignore */ }
618
+ fallbackEl = null
549
619
  }
550
620
  }
551
621
 
@@ -29,6 +29,23 @@ legacy 直接调用 3.1.x 旧服务键(fangForker / fangDecisionCenter 等)
29
29
  业务错误(如 `ticket-invalid`)**不降级**,避免重复副作用;传输/协议/未知方法才降级。
30
30
  每次尝试记录在 `client.attempts()`,状态可观测。
31
31
 
32
+ ## 2.5 零配置(v3.1.16 / 房主 3.2.5)
33
+
34
+ 瓮城原身运行态的 spawn 环境新增 `DSH_FANG_MOTHER=<母体 dataDir>`;房主 Router 检测到该变量后
35
+ 自动使用 `<母体 dataDir>/contract-outbox` 作为 `dispatch.contractFileDir`,无需手工配置:
36
+
37
+ ```text
38
+ 原身 Host(essence Router)
39
+ env: DSH_FANG_ROLE=fork / DSH_FANG_ESSENCE=1 / DSH_FANG_MOTHER=<母体 dataDir>
40
+ ↓ dispatch.contract=true(自动 file 桥)
41
+ <母体 dataDir>/contract-outbox/requests → responses
42
+ ↓
43
+ 母体 Host(Fang contract service)→ 真实 fork
44
+ ```
45
+
46
+ HTTP 桥需要两个凭据:契约 Bearer token + 安装级 `x-fang-auth`;房主通过
47
+ `dispatch.motherToken` 与 `dispatch.motherAuthToken` 提供(SDK 侧为可选 `headers`)。
48
+
32
49
  ## 3. 两侧实现位置
33
50
 
34
51
  | 侧 | 文件 | 内容 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/dsh-fang",
3
- "version": "3.1.15",
3
+ "version": "3.1.17",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "dsh-Fang (瓮城) — mother/fork plugin development environment for DeepSeek Harness: one readonly mother, a disposable child dsh-Web per task.",
@@ -28,6 +28,7 @@ export function createContractClient(options = {}) {
28
28
  if (config.httpBaseUrl) transports.push(createHttpTransport({
29
29
  baseUrl: config.httpBaseUrl,
30
30
  token: config.httpToken,
31
+ headers: config.httpHeaders,
31
32
  fetchImpl,
32
33
  timeoutMs: config.timeoutMs,
33
34
  pathPrefix: config.pathPrefix,
@@ -53,7 +53,7 @@ export function createLocalTransport({ ctx, serviceName = 'fangContract' } = {})
53
53
  }
54
54
  }
55
55
 
56
- export function createHttpTransport({ baseUrl = '', token = '', fetchImpl = fetch, timeoutMs = 15_000, pathPrefix = '/fang/api/contract' } = {}) {
56
+ export function createHttpTransport({ baseUrl = '', token = '', headers: extraHeaders = {}, fetchImpl = fetch, timeoutMs = 15_000, pathPrefix = '/fang/api/contract' } = {}) {
57
57
  const base = baseOf(baseUrl)
58
58
  const prefix = `/${String(pathPrefix).replace(/^\/+|\/+$/g, '')}`
59
59
  const available = () => Boolean(base)
@@ -64,7 +64,7 @@ export function createHttpTransport({ baseUrl = '', token = '', fetchImpl = fetc
64
64
  try {
65
65
  const response = await fetchImpl(`${base}${prefix}${endpoint}`, {
66
66
  method: 'POST',
67
- headers: { 'content-type': 'application/json', accept: 'application/json', ...authHeaders(token) },
67
+ headers: { 'content-type': 'application/json', accept: 'application/json', ...authHeaders(token), ...(extraHeaders && typeof extraHeaders === 'object' ? extraHeaders : {}) },
68
68
  body: JSON.stringify(role),
69
69
  signal: controller.signal,
70
70
  })
@@ -129,7 +129,7 @@ export const AUDIT = {
129
129
  RUNTIME_ERROR: 'runtime-error',
130
130
  }
131
131
 
132
- export const FANG_VERSION = '3.1.15'
132
+ export const FANG_VERSION = '3.1.17'
133
133
 
134
134
  /**
135
135
  * @typedef {object} ForkInfo
@@ -193,6 +193,7 @@ export const ADAPTER_OP = {
193
193
  export const ADAPTER_ROUTE = {
194
194
  HELLO: '/adapter/hello',
195
195
  IDENTITY: '/adapter/identity',
196
+ CLIENT_REPORT: '/adapter/client-report',
196
197
  STATUS: '/adapter/status',
197
198
  APPROVALS: '/adapter/approvals',
198
199
  AUDIT: '/adapter/audit',
@@ -695,13 +695,29 @@ export function apply(ctx, config) {
695
695
 
696
696
  // v3.1.14:Web 端拿不到 adapter Bearer token,身份探测走公开只读路由;
697
697
  // 只暴露 role/kind/version,不含 taskId/sessionId/token。
698
+ let clientReported = false
699
+ let clientReportedAt = 0
700
+
698
701
  const identity = () => ({
699
702
  ok: true,
700
703
  role,
701
704
  kind: identityKind({ role, taskId, essence: typeof process !== 'undefined' && process.env?.DSH_FANG_ESSENCE === '1' }),
702
705
  version: FANG_VERSION,
703
706
  protocol: ADAPTER_PROTOCOL_VERSION,
707
+ // v3.1.17:一眼判断「服务端有身份、客户端没加载」——不含 taskId/token 等敏感字段。
708
+ surface: 'web-adapter',
709
+ clientLoaded: clientReported,
710
+ clientReportedAt: clientReportedAt || null,
704
711
  })
712
+ /**
713
+ * 客户端自报:Web 端加载了 fang client 后会 POST 到这里;
714
+ * 只记录时间,不记录任何身份/token(用于运维排查徽标不显示)。
715
+ */
716
+ const reportClient = () => {
717
+ clientReported = true
718
+ clientReportedAt = Date.now()
719
+ return { ok: true, clientReported: true, at: clientReportedAt }
720
+ }
705
721
 
706
722
  const approvals = () => {
707
723
  const items = approvalItemsWithOrphans()
@@ -1108,6 +1124,8 @@ export function apply(ctx, config) {
1108
1124
  routes: [],
1109
1125
 
1110
1126
  hello,
1127
+ identity,
1128
+ reportClient,
1111
1129
  status,
1112
1130
  approvals,
1113
1131
  audit,
@@ -1235,6 +1253,14 @@ export function apply(ctx, config) {
1235
1253
  handler: (req, res) => json(res, 200, identity()),
1236
1254
  })
1237
1255
  try { service.routes.push(`${prefix}${ADAPTER_ROUTE.IDENTITY}`) } catch { /* fake ws */ }
1256
+ // v3.1.17:客户端自报加载状态(只记录时间戳,不含身份/token)。
1257
+ webServer.register({
1258
+ kind: 'exact',
1259
+ path: `${prefix}${ADAPTER_ROUTE.CLIENT_REPORT}`,
1260
+ method: 'POST',
1261
+ handler: (req, res) => json(res, 200, reportClient()),
1262
+ })
1263
+ try { service.routes.push(`${prefix}${ADAPTER_ROUTE.CLIENT_REPORT}`) } catch { /* fake ws */ }
1238
1264
  const route = (method, routePath, handler) => {
1239
1265
  webServer.register({
1240
1266
  kind: 'exact',
@@ -2319,7 +2319,9 @@ export function apply(ctx, config) {
2319
2319
  homeDir,
2320
2320
  profile: 'essence-runtime',
2321
2321
  cliPath: cliPath(),
2322
- env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId, DSH_FANG_ESSENCE: '1' },
2322
+ // v3.1.16:原身运行态同样需要母体 dataDir,房主 Router 才能零配置推导
2323
+ // 契约 file 桥(contract-outbox);普通分身在 846/1461/1534 行已有同名注入。
2324
+ env: { DSH_FANG_ROLE: 'fork', DSH_FANG_TASK_ID: forkId, DSH_FANG_ESSENCE: '1', DSH_FANG_MOTHER: layout.dataDir },
2323
2325
  })
2324
2326
  if (!started.ok) throw new Error(`runtime-spawn-failed: ${started.error ?? 'unknown'} (forkId=${forkId}, homeDir=${homeDir}, profile=essence-runtime)`)
2325
2327
  return {
@@ -365,6 +365,10 @@ export function apply(ctx, config) {
365
365
  }
366
366
  }
367
367
  const workspaceFilter = typeof opts.workspaceId === 'string' && opts.workspaceId.trim() ? opts.workspaceId.trim() : null
368
+ // v3.1.17:房主 Router 的 Ticket→会话映射键(sessionKey/ticketId)原样带回,
369
+ // 便于 3_Sessions 把「工单」与「母体会话目录」对齐;不参与过滤,只做标注。
370
+ const sessionKey = typeof opts.sessionKey === 'string' && opts.sessionKey.trim() ? opts.sessionKey.trim() : null
371
+ const ticketId = typeof opts.ticketId === 'string' && opts.ticketId.trim() ? opts.ticketId.trim() : null
368
372
 
369
373
  let items = scanned.sessions
370
374
  if (!includeArchivedEffective) items = items.filter((session) => !session.archived)
@@ -385,7 +389,14 @@ export function apply(ctx, config) {
385
389
  })
386
390
  return {
387
391
  ok: true,
388
- sessions: page.map((session) => ({ ...sessionView(session), ...titleFields(titleOf(session), session.workspaceTitle) })),
392
+ sessions: page.map((session) => ({
393
+ ...sessionView(session),
394
+ ...titleFields(titleOf(session), session.workspaceTitle),
395
+ ...(sessionKey ? { sessionKey } : {}),
396
+ ...(ticketId ? { ticketId } : {}),
397
+ })),
398
+ ...(sessionKey ? { sessionKey } : {}),
399
+ ...(ticketId ? { ticketId } : {}),
389
400
  total,
390
401
  returned: page.length,
391
402
  limit: requestedLimit,