@twinsearth/dsh-fang 3.0.7 → 3.0.9

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.
@@ -2,7 +2,8 @@
2
2
  // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
3
  // fang-session-bridge — mother-side façade over a running PC host's loopback bridge.
4
4
  // Transport only: it never copies session files and never writes to the PC host.
5
- import { z, roleGate, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
5
+ import { z, roleGate, resolveFangLayout, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
6
+ import { createHttpGuard } from '../lib/http-auth.mjs'
6
7
  import { createBridgeClient, readBridgeDescriptor } from '../lib/bridge-client.mjs'
7
8
 
8
9
  export const name = 'fang-session-bridge'
@@ -16,6 +17,10 @@ export const Config = z.object({
16
17
  timeoutMs: z.number().min(1000).max(120000).default(15000)
17
18
  .description('每次桥接请求的超时(毫秒)'),
18
19
  routes: z.object({ enabled: z.boolean().default(true) }).default({}),
20
+ authToken: z.string().default('')
21
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
22
+ authEnabled: z.boolean().default(true)
23
+ .description('是否要求 /fang/api/bridge/* 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
19
24
  })
20
25
 
21
26
  export function apply(ctx, config) {
@@ -25,6 +30,11 @@ export function apply(ctx, config) {
25
30
  const cfg = { ...Config({}), ...(config ?? {}) }
26
31
  const client = createBridgeClient({ dshHome: cfg.dshHome, timeoutMs: cfg.timeoutMs })
27
32
  const prefix = String(cfg.prefix ?? '/fang').replace(/\/+$/, '') || '/fang'
33
+ const authGuard = createHttpGuard({
34
+ dataDir: resolveFangLayout().dataDir,
35
+ token: cfg.authToken,
36
+ enabled: cfg.authEnabled !== false,
37
+ })
28
38
 
29
39
  const audit = (kind, data) => {
30
40
  try {
@@ -89,19 +99,57 @@ export function apply(ctx, config) {
89
99
  webServer.register({
90
100
  kind: 'exact',
91
101
  path: routePath,
102
+ method,
92
103
  handler: async (req, res) => {
93
104
  try {
94
- if (String(req?.method ?? 'GET').toUpperCase() !== method) return json(res, 405, { ok: false, error: 'method-not-allowed' })
105
+ const decision = authGuard.check(req)
106
+ if (!decision.ok) return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
107
+ if (String(req?.method ?? 'GET').toUpperCase() !== method) {
108
+ try { res.setHeader?.('allow', method) } catch { /* fake res */ }
109
+ return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
110
+ }
95
111
  return await handler(req, res)
96
112
  } catch (e) {
97
- return json(res, 500, { ok: false, error: String(e?.message ?? e) })
113
+ return json(res, 500, { ok: false, error: String(e?.message ?? e), code: 'handler-threw' })
114
+ }
115
+ },
116
+ })
117
+ }
118
+
119
+ // DSH exact routes are keyed by path only: GET+POST share one registration.
120
+ const routeMethods = (routePath, handlers) => {
121
+ webServer.register({
122
+ kind: 'exact',
123
+ path: routePath,
124
+ method: Object.keys(handlers).join(','),
125
+ handler: async (req, res) => {
126
+ try {
127
+ const decision = authGuard.check(req)
128
+ if (!decision.ok) return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
129
+ const allow = Object.keys(handlers)
130
+ const fn = handlers[String(req?.method ?? 'GET').toUpperCase()]
131
+ if (typeof fn !== 'function') {
132
+ try { res.setHeader?.('allow', allow.join(', ')) } catch { /* fake res */ }
133
+ return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
134
+ }
135
+ return await fn(req, res)
136
+ } catch (e) {
137
+ return json(res, 500, { ok: false, error: String(e?.message ?? e), code: 'handler-threw' })
98
138
  }
99
139
  },
100
140
  })
101
141
  }
102
142
 
103
143
  route('GET', `${prefix}/api/bridge/status`, (req, res) => json(res, 200, service.descriptor()))
104
- route('GET', `${prefix}/api/bridge/sessions`, async (req, res) => json(res, 200, await service.listSessions()))
144
+ routeMethods(`${prefix}/api/bridge/sessions`, {
145
+ GET: async (req, res) => json(res, 200, await service.listSessions()),
146
+ POST: async (req, res) => {
147
+ const body = await readBody(req)
148
+ if (body.__parseError) return json(res, 400, { ok: false, error: 'bad-json' })
149
+ const out = await service.create({ cwd: body.cwd, title: body.title })
150
+ json(res, out.ok ? 201 : 400, out)
151
+ },
152
+ })
105
153
  route('GET', `${prefix}/api/bridge/sessions/events`, async (req, res) => {
106
154
  const q = queryOf(req)
107
155
  const out = await service.events(q.get('sessionId') ?? '', { limit: q.get('limit') })
@@ -113,11 +161,6 @@ export function apply(ctx, config) {
113
161
  const out = await service.send(body.sessionId, body.text)
114
162
  json(res, out.ok ? 200 : 400, out)
115
163
  })
116
- route('POST', `${prefix}/api/bridge/sessions`, async (req, res) => {
117
- const body = await readBody(req)
118
- if (body.__parseError) return json(res, 400, { ok: false, error: 'bad-json' })
119
- const out = await service.create({ cwd: body.cwd, title: body.title })
120
- json(res, out.ok ? 201 : 400, out)
121
- })
164
+
122
165
  })
123
166
  }
@@ -29,9 +29,11 @@ import {
29
29
  z,
30
30
  roleGate,
31
31
  resolveDshHome,
32
+ resolveFangLayout,
32
33
  SERVICE,
33
34
  FANG_VERSION,
34
35
  } from '../kernel/index.mjs'
36
+ import { createHttpGuard } from '../lib/http-auth.mjs'
35
37
  import {
36
38
  SESSION_ID_RE,
37
39
  SESSION_LOG_FILE,
@@ -86,6 +88,10 @@ export const Config = z.object({
86
88
  .description('digest 预览的最大字符数(超过 digest 32KiB 上限会 halt 而不是截断)'),
87
89
  allowArchived: z.boolean().default(true)
88
90
  .description('是否允许在请求 includeArchived 时列出已归档会话'),
91
+ authToken: z.string().default('')
92
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
93
+ authEnabled: z.boolean().default(true)
94
+ .description('是否要求 /fang/api/sessions* 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
89
95
  })
90
96
 
91
97
  function clampInt(value, min, max, fallback) {
@@ -125,6 +131,13 @@ export function apply(ctx, config) {
125
131
  const cfg = { ...DEFAULTS, ...configDefaults, ...(config ?? {}) }
126
132
 
127
133
  const dshHome = resolveDshHome()
134
+ // v3.0.8/B1: these three routes read real session content; they must use the
135
+ // same install-level Host/Origin/token gate as /fang/api/status.
136
+ const authGuard = createHttpGuard({
137
+ dataDir: resolveFangLayout({ dataRoot: cfg.dataRoot }).dataDir,
138
+ token: cfg.authToken,
139
+ enabled: cfg.authEnabled !== false,
140
+ })
128
141
  const sessionsRoot = cfg.sessionsRoot ? path.resolve(String(cfg.sessionsRoot)) : path.join(dshHome, 'sessions')
129
142
  const storagesRoot = cfg.storagesRoot ? path.resolve(String(cfg.storagesRoot)) : path.join(dshHome, 'storages')
130
143
  const workspaceIndexFile = path.join(storagesRoot, WORKSPACE_INDEX_FILE)
@@ -671,9 +684,16 @@ export function apply(ctx, config) {
671
684
  webServer.register({
672
685
  kind: 'exact',
673
686
  path: routePath,
687
+ method,
674
688
  handler: async (req, res) => {
689
+ // Auth before method: a token-less POST must be 401, not 405 (fail-closed).
690
+ const decision = authGuard.check(req)
691
+ if (!decision.ok) {
692
+ return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
693
+ }
675
694
  const actual = String(req?.method ?? 'GET').toUpperCase()
676
695
  if (actual !== method) {
696
+ try { res.setHeader?.('allow', method) } catch { /* fake res */ }
677
697
  return json(res, 405, { ok: false, code: 'method-not-allowed', error: 'method-not-allowed', path: routePath })
678
698
  }
679
699
  try {
@@ -6,7 +6,8 @@
6
6
  // cross-machine + realtime -> deny (bridge is loopback-only, sync not realtime)
7
7
  // same machine + host + bridge -> bridge
8
8
  // otherwise -> sync
9
- import { z, roleGate, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
9
+ import { z, roleGate, resolveFangLayout, SERVICE, FANG_VERSION } from '../kernel/index.mjs'
10
+ import { createHttpGuard } from '../lib/http-auth.mjs'
10
11
  import { readBridgeDescriptor } from '../lib/bridge-client.mjs'
11
12
 
12
13
  export const name = 'fang-session-router'
@@ -23,6 +24,10 @@ export const Config = z.object({
23
24
  .description('PC 宿主 DSH_HOME(查找 desktop-bridge.json);留空 = 本机 $DSH_HOME'),
24
25
  prefix: z.string().default('/fang'),
25
26
  routes: z.object({ enabled: z.boolean().default(true) }).default({}),
27
+ authToken: z.string().default('')
28
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
29
+ authEnabled: z.boolean().default(true)
30
+ .description('是否要求 /fang/api/route 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
26
31
  })
27
32
 
28
33
  /** Pure decision function; `deny` means the request cannot be satisfied honestly. */
@@ -43,6 +48,11 @@ export function apply(ctx, config) {
43
48
  if (!gate.active) return
44
49
  const cfg = { ...Config({}), ...(config ?? {}) }
45
50
  const prefix = String(cfg.prefix ?? '/fang').replace(/\/+$/, '') || '/fang'
51
+ const authGuard = createHttpGuard({
52
+ dataDir: resolveFangLayout().dataDir,
53
+ token: cfg.authToken,
54
+ enabled: cfg.authEnabled !== false,
55
+ })
46
56
 
47
57
  const probe = (context = {}) => {
48
58
  const desc = readBridgeDescriptor({ dshHome: cfg.dshHome })
@@ -86,10 +96,19 @@ export function apply(ctx, config) {
86
96
  webServer.register({
87
97
  kind: 'exact',
88
98
  path: `${prefix}/api/route`,
99
+ method: 'GET',
89
100
  handler: async (req, res) => {
101
+ const decision = authGuard.check(req)
102
+ if (!decision.ok) {
103
+ res.statusCode = decision.status
104
+ res.setHeader?.('content-type', 'application/json; charset=utf-8')
105
+ res.end(JSON.stringify({ ok: false, error: decision.code, code: decision.code }))
106
+ return
107
+ }
90
108
  if (String(req?.method ?? 'GET').toUpperCase() !== 'GET') {
91
109
  res.statusCode = 405
92
- res.end(JSON.stringify({ ok: false, error: 'method-not-allowed' }))
110
+ res.setHeader?.('allow', 'GET')
111
+ res.end(JSON.stringify({ ok: false, error: 'method-not-allowed', code: 'method-not-allowed' }))
93
112
  return
94
113
  }
95
114
  const q = new URL(String(req?.url ?? '/'), 'http://fang.local').searchParams
@@ -8,6 +8,7 @@ import {
8
8
  } from '../kernel/index.mjs'
9
9
  import { exportSessions, importSessions } from '../lib/session-bundle.mjs'
10
10
  import { encodeWorkspaceKey } from '../lib/session-format.mjs'
11
+ import { createHttpGuard } from '../lib/http-auth.mjs'
11
12
 
12
13
  export const name = 'fang-session-sync'
13
14
  export const inject = []
@@ -23,6 +24,10 @@ export const Config = z.object({
23
24
  maxBundleBytes: z.number().min(0).max(4 * 1024 * 1024 * 1024).default(512 * 1024 * 1024)
24
25
  .description('单个 bundle 的大小上限(字节);超过则拒绝导出'),
25
26
  routes: z.object({ enabled: z.boolean().default(true) }).default({}),
27
+ authToken: z.string().default('')
28
+ .description('安装级鉴权 token;留空 = env DSH_FANG_AUTH_TOKEN 或 <dataDir>/fang-auth.json(0600,自动生成)'),
29
+ authEnabled: z.boolean().default(true)
30
+ .description('是否要求 /fang/api/sync/* 携带安装级鉴权 token(默认开启;仅测试/本地调试可关)'),
26
31
  })
27
32
 
28
33
  export function apply(ctx, config) {
@@ -34,6 +39,11 @@ export function apply(ctx, config) {
34
39
  const storagesRoot = cfg.storagesRoot ? path.resolve(cfg.storagesRoot) : path.join(resolveDshHome(), 'storages')
35
40
  const bundleRoot = cfg.bundleRoot ? path.resolve(cfg.bundleRoot) : path.join(layout.dataDir, 'sync-bundles')
36
41
  const prefix = String(cfg.prefix ?? '/fang').replace(/\/+$/, '') || '/fang'
42
+ const authGuard = createHttpGuard({
43
+ dataDir: layout.dataDir,
44
+ token: cfg.authToken,
45
+ enabled: cfg.authEnabled !== false,
46
+ })
37
47
 
38
48
  const workspacesOf = (homeDir) => {
39
49
  const file = path.join(homeDir, 'storages', 'workspace.json')
@@ -128,11 +138,17 @@ export function apply(ctx, config) {
128
138
  webServer.register({
129
139
  kind: 'exact',
130
140
  path: routePath,
141
+ method,
131
142
  handler: async (req, res) => {
132
143
  try {
133
- if (String(req?.method ?? 'GET').toUpperCase() !== method) return json(res, 405, { ok: false, error: 'method-not-allowed' })
144
+ const decision = authGuard.check(req)
145
+ if (!decision.ok) return json(res, decision.status, { ok: false, error: decision.code, code: decision.code })
146
+ if (String(req?.method ?? 'GET').toUpperCase() !== method) {
147
+ try { res.setHeader?.('allow', method) } catch { /* fake res */ }
148
+ return json(res, 405, { ok: false, error: 'method-not-allowed', code: 'method-not-allowed' })
149
+ }
134
150
  return await handler(req, res)
135
- } catch (e) { return json(res, 500, { ok: false, error: String(e?.message ?? e) }) }
151
+ } catch (e) { return json(res, 500, { ok: false, error: String(e?.message ?? e), code: 'handler-threw' }) }
136
152
  },
137
153
  })
138
154
  }
@@ -0,0 +1,121 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.8 MCP stdio server: JSON-RPC 2.0, 8 default tools + opId polling.
3
+ import path from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { TOOLS, OpStore, listTools } from './tools.mjs'
6
+
7
+ const META_TOOLS = [
8
+ { name: 'get_op', description: '轮询长任务 opId(不假取消)', inputSchema: { type: 'object', properties: { opId: { type: 'string' } }, required: ['opId'] } },
9
+ { name: 'abandon_op', description: '放弃轮询;不宣称已停止服务端任务', inputSchema: { type: 'object', properties: { opId: { type: 'string' } }, required: ['opId'] } },
10
+ ]
11
+
12
+ export function createHandlers({ callTool, clock = Date.now } = {}) {
13
+ const ops = new OpStore({ clock })
14
+ const defs = [...listTools(), ...META_TOOLS]
15
+ const names = new Set(defs.map((tool) => tool.name))
16
+ const call = async (name, args = {}) => {
17
+ if (name === 'get_op') return ops.get(args.opId)
18
+ if (name === 'abandon_op') return ops.abandon(args.opId)
19
+ if (!names.has(name)) throw new Error('tool-not-found: ' + name)
20
+ const spec = TOOLS.find((tool) => tool.name === name)
21
+ if (spec?.kind === 'op') return ops.start(name, args, () => callTool(name, args))
22
+ return callTool(name, args)
23
+ }
24
+ return { defs, call }
25
+ }
26
+
27
+ export function createServer({ callTool } = {}) {
28
+ const handlers = createHandlers({ callTool })
29
+ return async function handleRequest(request) {
30
+ const { id = null, method, params } = request || {}
31
+ const reply = (result) => ({ jsonrpc: '2.0', id, result })
32
+ const fail = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } })
33
+ try {
34
+ if (method === 'initialize') {
35
+ return reply({
36
+ protocolVersion: '2024-11-05',
37
+ capabilities: { tools: {} },
38
+ serverInfo: { name: 'dsh-fang', version: '3.0.8' },
39
+ })
40
+ }
41
+ if (method === 'ping') return reply({})
42
+ if (method === 'tools/list') {
43
+ return reply({ tools: handlers.defs.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) })
44
+ }
45
+ if (method === 'tools/call') {
46
+ const name = String(params?.name || '')
47
+ const result = await handlers.call(name, params?.arguments || {})
48
+ return reply({ content: [{ type: 'text', text: JSON.stringify(result) }], isError: Boolean(result && result.ok === false) })
49
+ }
50
+ return fail(-32601, 'method not found: ' + method)
51
+ } catch (error) {
52
+ return fail(-32603, String(error?.message ?? error))
53
+ }
54
+ }
55
+ }
56
+
57
+ const SENSITIVE_KEYS = new Set(['token', 'authtoken', 'datadir', 'clipath', 'template', 'password', 'secret', 'cookie'])
58
+
59
+ function sanitize(value) {
60
+ if (Array.isArray(value)) return value.map(sanitize)
61
+ if (!value || typeof value !== 'object') return value
62
+ const out = {}
63
+ for (const [key, child] of Object.entries(value)) {
64
+ if (SENSITIVE_KEYS.has(String(key).toLowerCase())) continue
65
+ out[key] = sanitize(child)
66
+ }
67
+ return out
68
+ }
69
+
70
+ export function createHttpCallTool({ baseUrl, token, fetchImpl = fetch }) {
71
+ const base = String(baseUrl || '').replace(/\/+$/, '')
72
+ const route = {
73
+ status: ['GET', '/fang/api/status'],
74
+ tasks: ['GET', '/fang/api/tasks'],
75
+ task_status: ['GET', '/fang/api/tasks/status'],
76
+ essence_list: ['GET', '/fang/api/essence/list'],
77
+ upgrade_status: ['GET', '/fang/api/upgrade/status'],
78
+ compat: ['GET', '/fang/api/compat'],
79
+ derive: ['POST', '/fang/api/derive'],
80
+ archive: ['POST', '/fang/api/tasks/archive'],
81
+ }
82
+ return async function callTool(name, args = {}) {
83
+ const entry = route[name]
84
+ if (!entry) throw new Error('tool-not-configured: ' + name)
85
+ const [method, routePath] = entry
86
+ let url = base + routePath
87
+ if (name === 'task_status') url += '?taskId=' + encodeURIComponent(String(args.taskId || ''))
88
+ const headers = { accept: 'application/json' }
89
+ if (token) headers['x-fang-auth'] = token
90
+ const init = { method, headers }
91
+ if (method === 'POST') {
92
+ headers['content-type'] = 'application/json'
93
+ init.body = JSON.stringify(args)
94
+ }
95
+ const response = await fetchImpl(url, init)
96
+ const body = await response.json().catch(() => ({}))
97
+ return { ok: response.ok && body.ok !== false, status: response.status, body: sanitize(body) }
98
+ }
99
+ }
100
+
101
+ async function main() {
102
+ const readline = await import('node:readline')
103
+ const baseUrl = process.env.FANG_URL || process.env.FANG_UPSTREAM || 'http://127.0.0.1:61758'
104
+ const token = process.env.FANG_TOKEN || process.env.DSH_FANG_AUTH_TOKEN || ''
105
+ const handle = createServer({ callTool: createHttpCallTool({ baseUrl, token }) })
106
+ const rl = readline.createInterface({ input: process.stdin })
107
+ rl.on('line', async (line) => {
108
+ if (!line.trim()) return
109
+ let request
110
+ try { request = JSON.parse(line) } catch {
111
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }) + '\n')
112
+ return
113
+ }
114
+ const response = await handle(request)
115
+ if (response) process.stdout.write(JSON.stringify(response) + '\n')
116
+ })
117
+ }
118
+
119
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
120
+ main().catch((error) => { console.error(error); process.exit(1) })
121
+ }
@@ -0,0 +1,65 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // v3.0.8 MCP tool registry: 8 default tools, 4 high-risk hidden, opId idempotency, no fake cancel.
3
+ import crypto from 'node:crypto'
4
+
5
+ export const HIGH_RISK_TOOLS = Object.freeze(['promote', 'delete', 'restart', 'mirror_upgrade'])
6
+
7
+ export const TOOLS = Object.freeze([
8
+ { name: 'status', description: '母体/宿主状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
9
+ { name: 'tasks', description: '分身任务列表(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
10
+ { name: 'task_status', description: '单个分身任务状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: { taskId: { type: 'string' } }, required: ['taskId'] } },
11
+ { name: 'derive', description: '派生新分身', kind: 'op', inputSchema: { type: 'object', properties: { title: { type: 'string' } } } },
12
+ { name: 'archive', description: '归档分身(保留 home)', kind: 'op', inputSchema: { type: 'object', properties: { taskId: { type: 'string' } }, required: ['taskId'] } },
13
+ { name: 'essence_list', description: '元主/原身列表(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
14
+ { name: 'upgrade_status', description: '升级状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
15
+ { name: 'compat', description: 'compat 门禁状态(只读)', kind: 'sync', inputSchema: { type: 'object', properties: {} } },
16
+ ...HIGH_RISK_TOOLS.map((name) => ({
17
+ name, description: '高风险工具(默认不暴露)', kind: 'op', highRisk: true,
18
+ inputSchema: { type: 'object', properties: {} },
19
+ })),
20
+ ])
21
+
22
+ export function listTools({ includeHighRisk = false } = {}) {
23
+ return TOOLS.filter((tool) => includeHighRisk || !tool.highRisk)
24
+ }
25
+
26
+ export class OpStore {
27
+ constructor({ clock = Date.now, timeoutMs = 120_000 } = {}) {
28
+ this.clock = clock
29
+ this.timeoutMs = timeoutMs
30
+ this.ops = new Map()
31
+ this.keys = new Map()
32
+ }
33
+
34
+ start(name, args = {}, run) {
35
+ const key = args.idempotencyKey ? `${name}:${args.idempotencyKey}` : ''
36
+ if (key && this.keys.has(key)) return { ok: true, opId: this.keys.get(key), deduped: true }
37
+ const opId = 'op_' + crypto.randomBytes(8).toString('hex')
38
+ this.ops.set(opId, { opId, name, state: 'running', abandoned: false, startedAt: this.clock(), result: null, error: null })
39
+ if (key) this.keys.set(key, opId)
40
+ Promise.resolve().then(run).then((result) => {
41
+ const op = this.ops.get(opId)
42
+ if (!op || op.state !== 'running') return
43
+ op.state = 'completed'; op.result = result ?? null
44
+ }).catch((error) => {
45
+ const op = this.ops.get(opId)
46
+ if (!op || op.state !== 'running') return
47
+ op.state = 'failed'; op.error = String(error?.message ?? error)
48
+ })
49
+ return { ok: true, opId, deduped: false }
50
+ }
51
+
52
+ get(opId) {
53
+ const op = this.ops.get(String(opId))
54
+ if (!op) return { ok: false, error: 'op-not-found' }
55
+ if (op.state === 'running' && this.clock() - op.startedAt > this.timeoutMs) op.state = 'timeout'
56
+ return { ok: true, opId: op.opId, name: op.name, state: op.state, abandoned: op.abandoned, result: op.result, error: op.error }
57
+ }
58
+
59
+ abandon(opId) {
60
+ const op = this.ops.get(String(opId))
61
+ if (!op) return { ok: false, error: 'op-not-found' }
62
+ op.abandoned = true
63
+ return { ok: true, opId: op.opId, state: op.state, abandoned: true }
64
+ }
65
+ }