@twinsearth/dsh-fang 3.1.20 → 3.1.22

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.
Files changed (115) hide show
  1. package/LICENSES/LICENSES/cordis-MIT.txt +39 -0
  2. package/client.js +197 -3
  3. package/defaults/defaults/umbrella-rules.yaml +113 -0
  4. package/package.json +2 -2
  5. package/sdk/sdk/README.md +65 -0
  6. package/sdk/sdk/examples/status-badge/README.md +16 -0
  7. package/sdk/sdk/examples/status-badge/client.js +60 -0
  8. package/sdk/sdk/examples/status-badge/cordis.patch.yml +7 -0
  9. package/sdk/sdk/examples/status-badge/index.js +12 -0
  10. package/sdk/sdk/examples/status-badge/package.json +24 -0
  11. package/sdk/sdk/templates/plugin/README.md +36 -0
  12. package/sdk/sdk/templates/plugin/client.js +35 -0
  13. package/sdk/sdk/templates/plugin/cordis.patch.yml +8 -0
  14. package/sdk/sdk/templates/plugin/icon.svg +5 -0
  15. package/sdk/sdk/templates/plugin/index.js +23 -0
  16. package/sdk/sdk/templates/plugin/locale/en.json +6 -0
  17. package/sdk/sdk/templates/plugin/package.json +36 -0
  18. package/src/kernel/types.mjs +1 -1
  19. package/src/lib/composer-journal.mjs +45 -0
  20. package/src/plugins/orchestrator.mjs +11 -1
  21. package/src/src/compose.mjs +67 -0
  22. package/src/src/contract/client.js +86 -0
  23. package/src/src/contract/constants.js +79 -0
  24. package/src/src/contract/envelope.js +83 -0
  25. package/src/src/contract/index.js +19 -0
  26. package/src/src/contract/negotiate.js +106 -0
  27. package/src/src/contract/server.js +77 -0
  28. package/src/src/contract/transports.js +301 -0
  29. package/src/src/index.mjs +11 -0
  30. package/src/src/kernel/core.mjs +100 -0
  31. package/src/src/kernel/extensions.mjs +61 -0
  32. package/src/src/kernel/fsx.mjs +349 -0
  33. package/src/src/kernel/index.mjs +21 -0
  34. package/src/src/kernel/ledger.mjs +94 -0
  35. package/src/src/kernel/paths.mjs +182 -0
  36. package/src/src/kernel/role.mjs +68 -0
  37. package/src/src/kernel/rounds.mjs +172 -0
  38. package/src/src/kernel/schema.mjs +5 -0
  39. package/src/src/kernel/types.mjs +264 -0
  40. package/src/src/kernel/vendor/cosmokit.mjs +421 -0
  41. package/src/src/kernel/vendor/schemastery.mjs +638 -0
  42. package/src/src/lib/adapter-client.mjs +383 -0
  43. package/src/src/lib/adapter-protocol.mjs +243 -0
  44. package/src/src/lib/ai-secret-store.mjs +202 -0
  45. package/src/src/lib/boot-guard.mjs +182 -0
  46. package/src/src/lib/branch-store.mjs +84 -0
  47. package/src/src/lib/branch.mjs +74 -0
  48. package/src/src/lib/bridge-client.mjs +133 -0
  49. package/src/src/lib/broker-adapter.mjs +67 -0
  50. package/src/src/lib/broker.mjs +45 -0
  51. package/src/src/lib/business-producers.mjs +109 -0
  52. package/src/src/lib/command-cache.mjs +209 -0
  53. package/src/src/lib/compat.mjs +170 -0
  54. package/src/src/lib/composer-journal.mjs +128 -0
  55. package/src/src/lib/container/index.mjs +806 -0
  56. package/src/src/lib/decision-events.mjs +129 -0
  57. package/src/src/lib/decision-ingest-client.mjs +41 -0
  58. package/src/src/lib/decision-outbox.mjs +129 -0
  59. package/src/src/lib/default-essence.mjs +61 -0
  60. package/src/src/lib/desktop-launch.mjs +138 -0
  61. package/src/src/lib/essence.mjs +1211 -0
  62. package/src/src/lib/fork-client.mjs +410 -0
  63. package/src/src/lib/fork-config-lock.mjs +153 -0
  64. package/src/src/lib/fork-seed.mjs +304 -0
  65. package/src/src/lib/fork-supervision-settings.mjs +58 -0
  66. package/src/src/lib/fork-supervisor.mjs +122 -0
  67. package/src/src/lib/fs-guard.mjs +28 -0
  68. package/src/src/lib/http-auth.mjs +162 -0
  69. package/src/src/lib/idle-audit.mjs +178 -0
  70. package/src/src/lib/interaction-poke.mjs +61 -0
  71. package/src/src/lib/mirror-etag.mjs +92 -0
  72. package/src/src/lib/mirror-official-source.mjs +93 -0
  73. package/src/src/lib/mirror.mjs +478 -0
  74. package/src/src/lib/mother-link.mjs +156 -0
  75. package/src/src/lib/mutex.mjs +31 -0
  76. package/src/src/lib/permissions.mjs +115 -0
  77. package/src/src/lib/pnpm-store.mjs +189 -0
  78. package/src/src/lib/preferences.mjs +212 -0
  79. package/src/src/lib/producer-contract.mjs +162 -0
  80. package/src/src/lib/reflow.mjs +41 -0
  81. package/src/src/lib/remote.mjs +408 -0
  82. package/src/src/lib/restart-contract.mjs +650 -0
  83. package/src/src/lib/roots.mjs +30 -0
  84. package/src/src/lib/rule-registry.mjs +1101 -0
  85. package/src/src/lib/runtime-capture.mjs +307 -0
  86. package/src/src/lib/semaphore.mjs +34 -0
  87. package/src/src/lib/session-bundle.mjs +138 -0
  88. package/src/src/lib/session-format.mjs +658 -0
  89. package/src/src/lib/sse-parser.mjs +102 -0
  90. package/src/src/lib/ssrf-guard.mjs +170 -0
  91. package/src/src/lib/status-store.mjs +257 -0
  92. package/src/src/lib/task-handle.mjs +622 -0
  93. package/src/src/lib/ui-actions.mjs +55 -0
  94. package/src/src/lib/umbrella.mjs +1661 -0
  95. package/src/src/lib/upgrade-coordinator.mjs +107 -0
  96. package/src/src/lib/upgrade-status.mjs +43 -0
  97. package/src/src/plugins/adapter.mjs +1468 -0
  98. package/src/src/plugins/approver.mjs +1210 -0
  99. package/src/src/plugins/auditor.mjs +330 -0
  100. package/src/src/plugins/buffer-keeper.mjs +522 -0
  101. package/src/src/plugins/decision-center.mjs +2265 -0
  102. package/src/src/plugins/forker.mjs +1594 -0
  103. package/src/src/plugins/healer.mjs +664 -0
  104. package/src/src/plugins/hot-reloader.mjs +274 -0
  105. package/src/src/plugins/imports.mjs +247 -0
  106. package/src/src/plugins/orchestrator.mjs +3806 -0
  107. package/src/src/plugins/restart-guard.mjs +948 -0
  108. package/src/src/plugins/router.mjs +714 -0
  109. package/src/src/plugins/scorer.mjs +624 -0
  110. package/src/src/plugins/session-bridge.mjs +166 -0
  111. package/src/src/plugins/session-catalog.mjs +771 -0
  112. package/src/src/plugins/session-router.mjs +125 -0
  113. package/src/src/plugins/session-sync.mjs +171 -0
  114. package/src/src/plugins/umbrella.mjs +419 -0
  115. package/tools/recover-queue.mjs +133 -0
@@ -0,0 +1,35 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // dsh-Fang / DSH plugin template — optional Client half.
3
+ //
4
+ // Contract: window.__ModuleLoader__.load({ id: <package name>, factory(require) {...} })
5
+ // React comes from the browser module table; do not require other DSH client packages.
6
+ window.__ModuleLoader__.load({
7
+ id: '@your-scope/dsh-plugin-template',
8
+ factory(require) {
9
+ const React = require('react')
10
+ const h = React.createElement
11
+
12
+ function Badge() {
13
+ return h('div', {
14
+ title: 'my-plugin: 输入框下方的一个示例徽标',
15
+ style: {
16
+ display: 'inline-flex', alignItems: 'center', gap: 6,
17
+ padding: '2px 8px', borderRadius: 999, fontSize: 11,
18
+ color: 'var(--dsw-alias-label-secondary, #888)',
19
+ border: '1px solid var(--dsw-alias-border, rgba(127,127,127,.3))',
20
+ },
21
+ }, 'my-plugin')
22
+ }
23
+
24
+ return {
25
+ inject: ['slots'],
26
+ apply(ctx) {
27
+ return ctx.slots.inject('conversation.composer.dock', () => ctx.slots.register({
28
+ name: 'conversation.composer.dock',
29
+ id: 'my-plugin-badge',
30
+ order: 60,
31
+ }, (props) => h(Badge, { ...props, ctx })))
32
+ },
33
+ }
34
+ },
35
+ })
@@ -0,0 +1,8 @@
1
+ # SPDX-License-Identifier: MIT
2
+ # Bundle patch for the plugin template: one loader row inserted at install time.
3
+ # Rename the id / package name when you copy this template.
4
+ - insert:
5
+ - id: my-plugin
6
+ name: '@your-scope/dsh-plugin-template'
7
+ config:
8
+ greeting: 'hello from my plugin'
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="my-plugin">
2
+ <rect x="4" y="4" width="56" height="56" rx="12" fill="#0f172a"/>
3
+ <circle cx="32" cy="30" r="12" fill="none" stroke="#22c55e" stroke-width="4"/>
4
+ <path d="M20 48h24" stroke="#94a3b8" stroke-width="4" stroke-linecap="round"/>
5
+ </svg>
@@ -0,0 +1,23 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // dsh-Fang / DSH plugin template — Host half.
3
+ //
4
+ // A Cordis plugin module: export name / inject / (optional Config) / apply.
5
+ // Copy this file, change the names, and install the directory as a bundle:
6
+ // plugin_manager install_bundle(target="E:\\path\\to\\my-plugin")
7
+ //
8
+ // The optional `Config` two lines below needs a schema library. If you want a configurable
9
+ // plugin, copy `schemastery.mjs` + `cosmokit.mjs` (MIT, upstream cordis) into a `vendor/`
10
+ // folder next to this file and `export const Config = z.object({...})`, exactly like the
11
+ // dsh-Fang core does; otherwise a plugin with no Config is perfectly valid.
12
+ export const name = 'my-plugin'
13
+ export const inject = []
14
+
15
+ const DEFAULTS = { greeting: 'hello from my plugin' }
16
+
17
+ export function apply(ctx, config) {
18
+ const cfg = { ...DEFAULTS, ...(config ?? {}) }
19
+ ctx.effect(() => ctx.provide('myPlugin', {
20
+ greeting: () => cfg.greeting,
21
+ status: () => ({ ok: true, at: new Date().toISOString() }),
22
+ }))
23
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "my-plugin (template)",
4
+ "description": "Minimal MIT plugin template for DSH / dsh-Fang: host half plus an optional composer-dock badge."
5
+ }
6
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@your-scope/dsh-plugin-template",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "Minimal dsh-Fang / DSH plugin template (MIT): host half + optional client half.",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": {
10
+ "browser": "./client.js",
11
+ "default": "./client.js"
12
+ },
13
+ "./locale/*.json": "./locale/*.json",
14
+ "./icon": "./icon.svg"
15
+ },
16
+ "files": [
17
+ "index.js",
18
+ "client.js",
19
+ "cordis.patch.yml",
20
+ "locale/*.json",
21
+ "icon.svg"
22
+ ],
23
+ "license": "MIT",
24
+ "dsh": {
25
+ "bundle": {
26
+ "patch": "./cordis.patch.yml"
27
+ },
28
+ "client": {
29
+ "platform": "web",
30
+ "immediately": true,
31
+ "inject": [
32
+ "@deepseek-ai/dsh-client-connection"
33
+ ]
34
+ }
35
+ }
36
+ }
@@ -129,7 +129,7 @@ export const AUDIT = {
129
129
  RUNTIME_ERROR: 'runtime-error',
130
130
  }
131
131
 
132
- export const FANG_VERSION = '3.1.20'
132
+ export const FANG_VERSION = '3.1.22'
133
133
 
134
134
  /**
135
135
  * @typedef {object} ForkInfo
@@ -7,6 +7,10 @@ import path from 'node:path'
7
7
  const MAX_DRAFT = 100_000
8
8
  const MAX_QUEUE = 100
9
9
  const MAX_ITEM = 4_000
10
+ // v3.1.21:队列「必丢」根因之一是所有会话挤在同一个 key(后者覆盖前者)。
11
+ // 新增 append-only 历史文件:任何一次含队列的保存都会追加一条快照,
12
+ // 即使主 journal 被覆盖,历史里仍能找回来。
13
+ const MAX_HISTORY = 500
10
14
 
11
15
  function cleanText(value, limit) {
12
16
  return String(value ?? '').replace(/\0/g, '').slice(0, limit)
@@ -15,6 +19,7 @@ function cleanText(value, limit) {
15
19
  export class ComposerJournal {
16
20
  constructor(dataDir) {
17
21
  this.file = path.join(dataDir, 'composer-journal.json')
22
+ this.historyFile = path.join(dataDir, 'composer-journal-history.jsonl')
18
23
  }
19
24
 
20
25
  load() {
@@ -58,6 +63,7 @@ export class ComposerJournal {
58
63
  draft: cleanText(input.draft, MAX_DRAFT),
59
64
  queue,
60
65
  path: cleanText(input.path, 500),
66
+ sessionKey: cleanText(input.sessionKey, 200),
61
67
  updatedAt: new Date().toISOString(),
62
68
  }
63
69
  const all = this.load()
@@ -69,9 +75,48 @@ export class ComposerJournal {
69
75
  for (const stale of keys.slice(0, keys.length - 100)) delete all[stale]
70
76
  }
71
77
  this.saveFile(all)
78
+ this.appendHistory({ ...entry, sessionKey: cleanText(input.sessionKey, 200) || entry.key })
72
79
  return entry
73
80
  }
74
81
 
82
+ /** 追加一条历史快照(只在有队列内容时写,避免草稿噪音)。 */
83
+ appendHistory(entry) {
84
+ try {
85
+ const queue = Array.isArray(entry?.queue) ? entry.queue : []
86
+ if (queue.length === 0) return
87
+ fs.mkdirSync(path.dirname(this.historyFile), { recursive: true })
88
+ fs.appendFileSync(this.historyFile, JSON.stringify({
89
+ key: entry.key,
90
+ queue,
91
+ draft: entry.draft || "",
92
+ path: entry.path || "",
93
+ sessionKey: entry.sessionKey || "",
94
+ updatedAt: entry.updatedAt,
95
+ }) + "\n", { encoding: "utf8", mode: 0o600 })
96
+ // 裁剪:超过上限时重写最后 MAX_HISTORY 行
97
+ const raw = fs.readFileSync(this.historyFile, "utf8").trim().split("\n").filter(Boolean)
98
+ if (raw.length > MAX_HISTORY) {
99
+ fs.writeFileSync(this.historyFile, raw.slice(-MAX_HISTORY).join("\n") + "\n", { encoding: "utf8", mode: 0o600 })
100
+ }
101
+ } catch { /* 历史写入失败不影响主 journal */ }
102
+ }
103
+
104
+ /** 读取历史快照(newest first),可按 sessionKey 过滤。 */
105
+ history({ limit = 50, sessionKey = "" } = {}) {
106
+ try {
107
+ const raw = fs.readFileSync(this.historyFile, "utf8").trim().split("\n").filter(Boolean)
108
+ const items = []
109
+ for (const line of raw) {
110
+ try {
111
+ const entry = JSON.parse(line)
112
+ if (sessionKey && String(entry?.sessionKey || "") !== String(sessionKey)) continue
113
+ items.push(entry)
114
+ } catch { /* 跳过坏行 */ }
115
+ }
116
+ return items.slice(-Math.max(1, Number(limit) || 50)).reverse()
117
+ } catch { return [] }
118
+ }
119
+
75
120
  remove(key) {
76
121
  const all = this.load()
77
122
  const id = String(key)
@@ -3581,13 +3581,23 @@ export function apply(ctx, config) {
3581
3581
  const key = String(body?.key ?? '')
3582
3582
  if (!key) return json(res, 400, { ok: false, error: 'journal-key-required' })
3583
3583
  try {
3584
- return json(res, 200, { ok: true, entry: composerJournal.save(key, body) })
3584
+ return json(res, 200, { ok: true, entry: composerJournal.save(key, { ...body, sessionKey: body?.sessionKey || body?.sessionId || '' }) })
3585
3585
  } catch (error) {
3586
3586
  return json(res, 400, { ok: false, error: String(error?.message ?? error) })
3587
3587
  }
3588
3588
  },
3589
3589
  })
3590
3590
 
3591
+ // v3.1.21:append-only 历史快照(主 journal 被覆盖时的兜底恢复源)。
3592
+ routeMethods(`${prefix}/api/composer/journal/history`, {
3593
+ GET: (req, res) => {
3594
+ const query = new URL(String(req.url ?? '/'), 'http://x').searchParams
3595
+ const limit = Math.max(1, Math.min(200, Number(query.get('limit') || 20)))
3596
+ const sessionKey = String(query.get('sessionKey') || '')
3597
+ return json(res, 200, { ok: true, items: composerJournal.history({ limit, sessionKey }) })
3598
+ },
3599
+ })
3600
+
3591
3601
  // Restore saved queue rows into the official Session inbox WITHOUT waking the
3592
3602
  // agent. The queue journal is a recovery surface; it must not send messages.
3593
3603
  route('POST', `${prefix}/api/composer/queue`, async (req, res) => {
@@ -0,0 +1,67 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang compose mode — mounts the orchestrator and every sub-plugin as nested
4
+ // fibers of one loader row. This is the fallback composition used when the split-row
5
+ // patch (`./cordis.patch.yml`) cannot resolve subpath entries; it is behaviourally
6
+ // identical because every sub-plugin is the same module the split rows would load.
7
+ import { z } from './kernel/index.mjs'
8
+ import * as auditor from './plugins/auditor.mjs'
9
+ import * as forker from './plugins/forker.mjs'
10
+ import * as bufferKeeper from './plugins/buffer-keeper.mjs'
11
+ import * as scorer from './plugins/scorer.mjs'
12
+ import * as umbrella from './plugins/umbrella.mjs'
13
+ import * as healer from './plugins/healer.mjs'
14
+ import * as router from './plugins/router.mjs'
15
+ import * as approver from './plugins/approver.mjs'
16
+ import * as hotReloader from './plugins/hot-reloader.mjs'
17
+ import * as restartGuard from './plugins/restart-guard.mjs'
18
+ import * as adapter from './plugins/adapter.mjs'
19
+ import * as orchestrator from './plugins/orchestrator.mjs'
20
+ import * as sessionBridge from './plugins/session-bridge.mjs'
21
+ import * as sessionSync from './plugins/session-sync.mjs'
22
+ import * as sessionRouter from './plugins/session-router.mjs'
23
+ import * as decisionCenter from './plugins/decision-center.mjs'
24
+
25
+ export const name = 'fang-compose'
26
+ export const inject = []
27
+
28
+ export const Config = z.object({
29
+ auditor: z.object({}).default({}).description('审计子插件配置'),
30
+ forker: z.object({}).default({}).description('派生器配置'),
31
+ bufferKeeper: z.object({}).default({}).description('缓冲管理器配置'),
32
+ scorer: z.object({}).default({}).description('评分配置'),
33
+ umbrella: z.object({}).default({}).description('保护伞(动作灯色 + 决策)配置'),
34
+ healer: z.object({}).default({}).description('修复子插件配置'),
35
+ router: z.object({}).default({}).description('路由决策配置'),
36
+ approver: z.object({}).default({}).description('审批子插件配置'),
37
+ hotReloader: z.object({}).default({}).description('热更新引擎配置'),
38
+ restartGuard: z.object({}).default({}).description('红线守卫配置'),
39
+ adapter: z.object({}).default({}).description('分身侧 Adapter 配置'),
40
+ orchestrator: z.object({}).default({}).description('编排器配置'),
41
+ sessionBridge: z.object({}).default({}).description('桥接(实时驱动 PC 会话)配置'),
42
+ sessionSync: z.object({}).default({}).description('同步(勾选会话搬运)配置'),
43
+ sessionRouter: z.object({}).default({}).description('混合路由配置'),
44
+ decisionCenter: z.object({}).default({}).description('决策中心配置'),
45
+ }).description('dsh-Fang 单行装载模式配置')
46
+
47
+ export function apply(ctx, config) {
48
+ const cfg = config ?? {}
49
+ ctx.plugin(auditor, cfg.auditor ?? {})
50
+ ctx.plugin(forker, cfg.forker ?? {})
51
+ ctx.plugin(bufferKeeper, cfg.bufferKeeper ?? {})
52
+ ctx.plugin(scorer, cfg.scorer ?? {})
53
+ ctx.plugin(umbrella, cfg.umbrella ?? {})
54
+ ctx.plugin(healer, cfg.healer ?? {})
55
+ ctx.plugin(router, cfg.router ?? {})
56
+ ctx.plugin(approver, cfg.approver ?? {})
57
+ ctx.plugin(hotReloader, cfg.hotReloader ?? {})
58
+ ctx.plugin(restartGuard, cfg.restartGuard ?? {})
59
+ ctx.plugin(adapter, cfg.adapter ?? {})
60
+ ctx.plugin(orchestrator, cfg.orchestrator ?? {})
61
+ ctx.plugin(sessionBridge, cfg.sessionBridge ?? {})
62
+ ctx.plugin(sessionSync, cfg.sessionSync ?? {})
63
+ ctx.plugin(sessionRouter, cfg.sessionRouter ?? {})
64
+ ctx.plugin(decisionCenter, cfg.decisionCenter ?? {})
65
+ }
66
+
67
+ export const _modules = { auditor, forker, bufferKeeper, scorer, umbrella, healer, router, approver, hotReloader, restartGuard, adapter, orchestrator, sessionBridge, sessionSync, sessionRouter, decisionCenter }
@@ -0,0 +1,86 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang/dsh-Master contributors — see LICENSE.
3
+
4
+ import { DEFAULT_TRANSPORT_ORDER, METHODS } from './constants.js'
5
+ import {
6
+ createFileTransport,
7
+ createHttpTransport,
8
+ createLegacyTransport,
9
+ createLocalTransport,
10
+ createTransportRouter,
11
+ } from './transports.js'
12
+
13
+ /**
14
+ * 客户端门面:一次配置,按 local → http → file → legacy 自动降级。
15
+ *
16
+ * @param {{
17
+ * ctx?: object,
18
+ * config?: {httpBaseUrl?:string, httpToken?:string, fileDir?:string, order?:string[], timeoutMs?:number},
19
+ * fetchImpl?: typeof fetch,
20
+ * logger?: object,
21
+ * instanceId?: string,
22
+ * }} options
23
+ */
24
+ export function createContractClient(options = {}) {
25
+ const { ctx = null, config = {}, fetchImpl = fetch, logger = null, instanceId = 'contract-client' } = options
26
+ const transports = []
27
+ if (ctx) transports.push(createLocalTransport({ ctx }))
28
+ if (config.httpBaseUrl) transports.push(createHttpTransport({
29
+ baseUrl: config.httpBaseUrl,
30
+ token: config.httpToken,
31
+ headers: config.httpHeaders,
32
+ fetchImpl,
33
+ timeoutMs: config.timeoutMs,
34
+ pathPrefix: config.pathPrefix,
35
+ }))
36
+ if (config.fileDir) transports.push(createFileTransport({
37
+ dir: config.fileDir,
38
+ pollMs: config.filePollMs,
39
+ timeoutMs: config.fileTimeoutMs,
40
+ }))
41
+ if (ctx) transports.push(createLegacyTransport({ ctx }))
42
+
43
+ const order = Array.isArray(config.order) && config.order.length > 0 ? config.order : DEFAULT_TRANSPORT_ORDER
44
+ const router = createTransportRouter({
45
+ transports,
46
+ order,
47
+ localHello: null,
48
+ logger,
49
+ })
50
+ let lastHello = null
51
+ let helloPromise = null
52
+
53
+ const client = {
54
+ instanceId,
55
+ transports: () => router.transports(),
56
+ describe: () => ({
57
+ instanceId,
58
+ routes: router.describe(),
59
+ hello: lastHello,
60
+ }),
61
+ attempts: () => router.attempts(),
62
+ async hello(force = false) {
63
+ if (!force && lastHello) return lastHello
64
+ if (!force && helloPromise) return helloPromise
65
+ helloPromise = (async () => {
66
+ const result = await router.hello()
67
+ lastHello = result
68
+ return result
69
+ })().finally(() => { helloPromise = null })
70
+ return helloPromise
71
+ },
72
+ async invoke(method, params, invokeOptions = {}) {
73
+ const result = await router.invoke(method, params, { timeoutMs: config.timeoutMs, ...invokeOptions })
74
+ return result
75
+ },
76
+ async health() { return await client.invoke(METHODS.HEALTH, null) },
77
+ async spawnFork(params, invokeOptions = {}) { return await client.invoke(METHODS.FORK_SPAWN, params, invokeOptions) },
78
+ async stopFork(params, invokeOptions = {}) { return await client.invoke(METHODS.FORK_STOP, params, invokeOptions) },
79
+ async listForks(params = {}, invokeOptions = {}) { return await client.invoke(METHODS.FORK_LIST, params, invokeOptions) },
80
+ async createDecision(params, invokeOptions = {}) { return await client.invoke(METHODS.DECISION_CREATE, params, invokeOptions) },
81
+ async resolveDecision(params, invokeOptions = {}) { return await client.invoke(METHODS.DECISION_RESOLVE, params, invokeOptions) },
82
+ async listSessions(params = {}, invokeOptions = {}) { return await client.invoke(METHODS.SESSION_LIST, params, invokeOptions) },
83
+ async orchestratorStatus(params = {}, invokeOptions = {}) { return await client.invoke(METHODS.ORCHESTRATOR_STATUS, params, invokeOptions) },
84
+ }
85
+ return client
86
+ }
@@ -0,0 +1,79 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang/dsh-Master contributors — see LICENSE.
3
+
4
+ /**
5
+ * 契约常量与兼容规则(contract SDK 1.x)。
6
+ *
7
+ * 稳定承诺:
8
+ * * MAJOR 相同的版本保证“旧字段可读、旧方法可调、未知字段忽略”;
9
+ * * 新增能力只通过 METHODS/CAPABILITIES 扩展,不改变既有方法语义;
10
+ * * 删除/改义必须升 MAJOR,并保留至少一个 MINOR 周期的双写(method@1 与 method@2)。
11
+ */
12
+
13
+ export const CONTRACT_PACKAGE = '@twinsearth/dsh-fang-contract'
14
+ export const CONTRACT_VERSION = '1.0.0'
15
+ export const PROTOCOL = 'fang-master'
16
+ export const PROTOCOL_VERSION = 1
17
+ export const MIN_COMPATIBLE_MAJOR = 1
18
+
19
+ /** 稳定方法名(新方法只能追加)。 */
20
+ export const METHODS = Object.freeze({
21
+ HELLO: 'contract.hello',
22
+ HEALTH: 'contract.health',
23
+ FORK_SPAWN: 'fang.fork.spawn',
24
+ FORK_STOP: 'fang.fork.stop',
25
+ FORK_LIST: 'fang.fork.list',
26
+ DECISION_CREATE: 'fang.decision.create',
27
+ DECISION_RESOLVE: 'fang.decision.resolve',
28
+ SESSION_LIST: 'fang.session.list',
29
+ ORCHESTRATOR_STATUS: 'fang.orchestrator.status',
30
+ })
31
+
32
+ /** 方法 → 契约版本(用于协商后的方法裁剪)。 */
33
+ export const METHOD_VERSION = Object.freeze({
34
+ [METHODS.HELLO]: '1.0',
35
+ [METHODS.HEALTH]: '1.0',
36
+ [METHODS.FORK_SPAWN]: '1.0',
37
+ [METHODS.FORK_STOP]: '1.0',
38
+ [METHODS.FORK_LIST]: '1.0',
39
+ [METHODS.DECISION_CREATE]: '1.0',
40
+ [METHODS.DECISION_RESOLVE]: '1.0',
41
+ [METHODS.SESSION_LIST]: '1.0',
42
+ [METHODS.ORCHESTRATOR_STATUS]: '1.0',
43
+ })
44
+
45
+ export const CAPABILITIES = Object.freeze([
46
+ 'sync', 'async', 'idempotent', 'stream-events', 'file-outbox',
47
+ ])
48
+
49
+ export const ROLES = Object.freeze(['mother', 'essence', 'fork'])
50
+
51
+ export const ERROR_CODES = Object.freeze({
52
+ INVALID_ENVELOPE: 'invalid-envelope',
53
+ UNSUPPORTED_METHOD: 'unsupported-method',
54
+ UNSUPPORTED_VERSION: 'unsupported-version',
55
+ INCOMPATIBLE: 'contract-incompatible',
56
+ TRANSPORT_UNAVAILABLE: 'transport-unavailable',
57
+ TRANSPORT_TIMEOUT: 'transport-timeout',
58
+ TRANSPORT_HTTP_ERROR: 'transport-http-error',
59
+ REMOTE_ERROR: 'remote-error',
60
+ ALL_TRANSPORTS_FAILED: 'all-transports-failed',
61
+ HANDLER_THREW: 'handler-threw',
62
+ })
63
+
64
+ /**
65
+ * 兜底顺序(从快到慢):
66
+ * local —— 同一 Host 的 DSH 服务(零网络、首选)
67
+ * http —— 母体/原身 HTTP 契约端点
68
+ * file —— 同一文件系统的 outbox/inbox(HTTP 不可用/被防火墙拦)
69
+ * legacy —— 直接调用 3.1.x 的旧 DSH 服务键(接口包被替换/新端点不存在时)
70
+ */
71
+ export const DEFAULT_TRANSPORT_ORDER = Object.freeze(['local', 'http', 'file', 'legacy'])
72
+
73
+ /** 3.1.x 及更早的旧服务键(只读兼容;不新增语义)。 */
74
+ export const LEGACY_SERVICE_KEYS = Object.freeze({
75
+ forker: 'fangForker',
76
+ decisionCenter: 'fangDecisionCenter',
77
+ sessionCatalog: 'fangSessionCatalog',
78
+ orchestrator: 'fang',
79
+ })
@@ -0,0 +1,83 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang/dsh-Master contributors — see LICENSE.
3
+
4
+ import crypto from 'node:crypto'
5
+
6
+ import { ERROR_CODES, PROTOCOL, PROTOCOL_VERSION } from './constants.js'
7
+
8
+ export function newId(prefix = 'msg') {
9
+ return `${prefix}_${crypto.randomUUID()}`
10
+ }
11
+
12
+ /** 创建请求信封;未知字段由接收方忽略(兼容规则)。 */
13
+ export function createEnvelope({ method, params = null, id, source = '', instanceId = '', timeoutMs = 30_000, meta = {} } = {}) {
14
+ if (!method || typeof method !== 'string') throw new Error('method is required')
15
+ return {
16
+ protocol: PROTOCOL,
17
+ protocolVersion: PROTOCOL_VERSION,
18
+ id: String(id ?? newId('req')),
19
+ method: String(method),
20
+ params: params ?? null,
21
+ meta: {
22
+ at: Date.now(),
23
+ deadline: Date.now() + Math.max(1, Number(timeoutMs) || 30_000),
24
+ source: String(source ?? ''),
25
+ instanceId: String(instanceId ?? ''),
26
+ ...(meta && typeof meta === 'object' ? meta : {}),
27
+ },
28
+ }
29
+ }
30
+
31
+ /** 校验请求/响应信封;返回 {ok, errors, envelope}。 */
32
+ export function validateEnvelope(value, { response = false } = {}) {
33
+ const errors = []
34
+ const raw = value && typeof value === 'object' ? value : {}
35
+ if (raw.protocol !== PROTOCOL) errors.push(`protocol-invalid:${String(raw.protocol)}`)
36
+ if (raw.protocolVersion !== PROTOCOL_VERSION) errors.push(`protocol-version-invalid:${String(raw.protocolVersion)}`)
37
+ if (!raw.id) errors.push('id-required')
38
+ if (response) {
39
+ if (typeof raw.ok !== 'boolean') errors.push('ok-required')
40
+ if (raw.ok === false && !raw.error?.code) errors.push('error-code-required')
41
+ } else if (!raw.method) {
42
+ errors.push('method-required')
43
+ }
44
+ return { ok: errors.length === 0, errors, envelope: raw }
45
+ }
46
+
47
+ export function createResponse({ id, result, error, meta = {} } = {}) {
48
+ const base = {
49
+ protocol: PROTOCOL,
50
+ protocolVersion: PROTOCOL_VERSION,
51
+ id: String(id ?? newId('res')),
52
+ ok: !error,
53
+ meta: { at: Date.now(), ...(meta && typeof meta === 'object' ? meta : {}) },
54
+ }
55
+ if (error) return { ...base, error: normalizeError(error) }
56
+ return { ...base, result: result ?? null }
57
+ }
58
+
59
+ export function normalizeError(error, fallbackCode = ERROR_CODES.REMOTE_ERROR) {
60
+ if (!error) return { code: fallbackCode, message: String(fallbackCode), retryable: false }
61
+ if (typeof error === 'string') return { code: fallbackCode, message: error, retryable: false }
62
+ return {
63
+ code: String(error.code ?? fallbackCode),
64
+ message: String(error.message ?? error.error ?? fallbackCode),
65
+ retryable: error.retryable === true,
66
+ ...(error.detail === undefined ? {} : { detail: error.detail }),
67
+ }
68
+ }
69
+
70
+ export class ContractTransportError extends Error {
71
+ constructor(code, message, { transport = '', detail = null, retryable = false } = {}) {
72
+ super(String(message ?? code))
73
+ this.name = 'ContractTransportError'
74
+ this.code = String(code)
75
+ this.transport = String(transport)
76
+ this.detail = detail
77
+ this.retryable = retryable === true
78
+ }
79
+ }
80
+
81
+ export function isCompatibleResponse(value) {
82
+ return validateEnvelope(value, { response: true }).ok
83
+ }
@@ -0,0 +1,19 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang/dsh-Master contributors — see LICENSE.
3
+
4
+ /**
5
+ * @twinsearth/dsh-fang-contract
6
+ *
7
+ * 瓮城(dsh-Fang)↔ 房主(dsh-Master)的独立版本化互联 SDK。
8
+ * 设计目标:
9
+ * 1. 双方独立升级:语义化版本 + hello 协商 + 未知字段忽略 + 方法版本裁剪;
10
+ * 2. 互联互通保底:local → http → file → legacy 四级传输自动降级;
11
+ * 3. 接口包可独立替换:更新本包即升级接口架构,旧方法在 MAJOR 内保持可调用。
12
+ */
13
+
14
+ export * from './constants.js'
15
+ export * from './envelope.js'
16
+ export * from './negotiate.js'
17
+ export * from './server.js'
18
+ export * from './transports.js'
19
+ export * from './client.js'