初始版本 0.1.0:四道菜团队中台 DSH 插件
模型通道:接管官方 API Key 通道指向弹匣网关(GLM-5.3 / GLM-5.3-Flash) 登录:浏览器取一次性接入码 → 换成员专属 key → 写入 DSH 凭据 工具面:MCP 暴露查汇总/查任务/查项目/建任务/完成/改期/whoami 面板:侧边栏入口,个人看板 + 角色可见范围 + 行内操作 离职吊销:成员停用即吊销名下全部 TDB key 发布配置:scope 包名、私有 registry 锁定、prepack 自动构建、prepublishOnly 检查
This commit is contained in:
commit
ff8017bbbb
26 files changed
+2924
No files matched your search
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
.local-credentials.json
|
||||
*.log
|
||||
.DS_Store
|
||||
dist/*.map
|
||||
@@ -0,0 +1,14 @@
|
||||
# CHANGELOG
|
||||
|
||||
版本规则:修 bug 用 patch,加功能用 minor,改权限/协议用 major。
|
||||
每次发布必须在这里留一条,写清改了什么、要不要重新登录、要不要重启。
|
||||
|
||||
## 0.1.0 — 2026-11-07
|
||||
|
||||
首个可用版本。
|
||||
|
||||
- 模型通道:接管官方 API Key 通道指向弹匣网关,提供 GLM-5.3 / GLM-5.3-Flash
|
||||
- 登录:浏览器取一次性接入码,换取成员专属 key,写入 DSH 凭据
|
||||
- 工具面(MCP):查汇总 / 查任务 / 查项目 / 建任务 / 完成 / 改期 / whoami
|
||||
- 面板:侧边栏入口,个人看板 + 角色可见范围 + 行内完成/改期 + 快速建任务
|
||||
- 离职吊销:成员停用即吊销名下全部 TDB key(弹匣侧实现)
|
||||
@@ -0,0 +1,5 @@
|
||||
Copyright (c) 2026 四道菜(sidaocai). All rights reserved.
|
||||
|
||||
本软件为四道菜内部工具,闭源。未经书面许可,不得复制、分发、修改或用于其他组织。
|
||||
This software is proprietary and confidential. Unauthorized copying, distribution,
|
||||
modification, or use outside the organization is strictly prohibited.
|
||||
@@ -0,0 +1,42 @@
|
||||
# dsh-markmag
|
||||
|
||||
DeepSeek Harness 插件 —— 四道菜团队中台(骨架版)。
|
||||
|
||||
## 它做什么
|
||||
|
||||
装上之后,DSH 的模型选择器里多出两个模型:
|
||||
|
||||
- **四道菜 · GLM-5.3**
|
||||
- **四道菜 · GLM-5.3-Flash**
|
||||
|
||||
它们走的是公司网关(弹匣背后的 TDB 记忆代理),用你个人的团队钥匙(凭据 `MARKMAG_TEAM_KEY`)。
|
||||
个人 DeepSeek 账号那条通道完全不动,两条线并存。
|
||||
|
||||
## 装
|
||||
|
||||
```bash
|
||||
node ~/Documents/Essay_AI/Essay_system/dsh-markmag/scripts/install.mjs
|
||||
```
|
||||
|
||||
然后重启桌面版 DSH。
|
||||
|
||||
## 撤
|
||||
|
||||
```bash
|
||||
cp ~/.dsh/profiles/desktop/package.json.bak-20261107-plugin ~/.dsh/profiles/desktop/package.json
|
||||
rm -rf ~/.dsh/profiles/desktop/node_modules/dsh-markmag
|
||||
```
|
||||
|
||||
## 现在还没有的
|
||||
|
||||
- 登录拿钥匙(现在钥匙要手工放进凭据 `MARKMAG_TEAM_KEY`)
|
||||
- 离职自动失效
|
||||
- 团队记忆自动盖章(现在由 dsh-team-memory 插件负责)
|
||||
|
||||
这三件是下一阶段的事。
|
||||
|
||||
## 为什么是覆盖官方通道
|
||||
|
||||
DSH 的模型通道 id 是固定的(`deepseek-official`),第三方插件没法凭空造一个新供应商名。
|
||||
所以骨架版的做法是:把官方 API Key 通道指向公司网关,并用模型名里的「四道菜 ·」前缀做辨识。
|
||||
真要一个独立的「四道菜」供应商条目,需要自己实现 adapter,那是升级版的事。
|
||||
@@ -0,0 +1,29 @@
|
||||
# dsh-markmag bundle patch —— 四道菜团队中台
|
||||
#
|
||||
# 两件事:
|
||||
# 1. 把本插件的宿主半片插进插件树(没有这段,src/host.js 一行都不会跑)
|
||||
# 2. 把「DeepSeek API Key」通道指向公司网关,并列出网关放开的模型
|
||||
#
|
||||
# 不动「DeepSeek 账号」通道(entry id: llm-deepseek-account),个人账号照常可用 ——
|
||||
# 两条通道并存:公司通道走公司额度 + 团队记忆,个人通道完全私有。
|
||||
|
||||
- insert:
|
||||
- id: markmag
|
||||
name: '@sidaocai/dsh-markmag'
|
||||
|
||||
# 网关端点:弹匣背后的 TDB 记忆代理,Anthropic Messages 协议兼容入口。
|
||||
# 模型清单:网关当前只开放智谱 GLM 系,deepseek/kimi/qwen 等均未开通(实测 1211 模型不存在)。
|
||||
- id: llm-deepseek
|
||||
name: '@deepseek-ai/dsh-llm-deepseek-api-key'
|
||||
config:
|
||||
baseURL: https://brain.sidaocai.cn/tdb-api/claude-code/default
|
||||
apiKeyEnv: MARKMAG_TEAM_KEY
|
||||
models:
|
||||
- id: glm-5.3
|
||||
name: '四道菜 · GLM-5.3'
|
||||
contextWindow: 128000
|
||||
maxTokens: 8192
|
||||
- id: glm-5.3-flash
|
||||
name: '四道菜 · GLM-5.3-Flash'
|
||||
contextWindow: 128000
|
||||
maxTokens: 8192
|
||||
@@ -0,0 +1,253 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""DSH 接入码(2026-11-07):浏览器登录态生成一次性码,桌面端拿码换成员 key。
|
||||
|
||||
为什么不直接把 key 显示出来让人复制:
|
||||
key 是长期凭证,进了剪贴板/聊天记录就一直在。一次性码 5 分钟过期、用后即废,
|
||||
泄露了也换不到东西 —— 把「长期凭证」换成「一次性凭证」的标准做法。
|
||||
|
||||
流程:
|
||||
1. 浏览器打开 /markmag/api/dsh/link(已登录)→ 页面显示 8 位码
|
||||
2. 桌面端 POST /api/dsh/link-exchange {code} → 换回该成员的 TDB 模型 key
|
||||
3. 桌面端把 key 存进自己的凭据库,之后不再需要这步
|
||||
|
||||
安全取舍:
|
||||
link-exchange 是唯一不需要登录态的 POST(DSH 正是因为没有登录态才来换),
|
||||
所以它自己得够硬:8 位码(31^8≈8500 亿)、5 分钟过期、用后即删、失败限流。
|
||||
码表只存进程内存,服务重启即清空,不落盘。
|
||||
"""
|
||||
import secrets
|
||||
import time
|
||||
|
||||
TTL_SECONDS = 300
|
||||
CODE_LEN = 8
|
||||
# 去掉 I/O/0/1,避免手抄看错
|
||||
_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
# 暴力猜码防护:一分钟内最多失败这么多次
|
||||
MAX_FAILS_PER_MIN = 10
|
||||
|
||||
_codes = {}
|
||||
_fails = []
|
||||
|
||||
|
||||
def _gc():
|
||||
"""清掉过期的码,避免字典无限长。"""
|
||||
now = time.time()
|
||||
for k in [k for k, v in _codes.items() if v.get("exp", 0) < now]:
|
||||
_codes.pop(k, None)
|
||||
|
||||
|
||||
def _rate_ok():
|
||||
"""最近一分钟失败次数是否还在额度内。"""
|
||||
now = time.time()
|
||||
_fails[:] = [t for t in _fails if now - t < 60]
|
||||
return len(_fails) < MAX_FAILS_PER_MIN
|
||||
|
||||
|
||||
def issue(sess):
|
||||
"""登录态 → 一次性码。"""
|
||||
uid = (sess or {}).get("uid") or ""
|
||||
name = (sess or {}).get("name") or ""
|
||||
if not uid:
|
||||
return {"ok": False, "err": "未登录"}
|
||||
_gc()
|
||||
code = "".join(secrets.choice(_ALPHABET) for _ in range(CODE_LEN))
|
||||
_codes[code] = {"uid": uid, "name": name, "exp": time.time() + TTL_SECONDS}
|
||||
return {"ok": True, "code": code, "expires_in": TTL_SECONDS}
|
||||
|
||||
|
||||
def redeem(raw_code):
|
||||
"""一次性码 → 成员 key。码用后即删,无论成败。"""
|
||||
if not _rate_ok():
|
||||
return {"ok": False, "err": "尝试过于频繁,等一分钟再试"}
|
||||
_gc()
|
||||
code = (raw_code or "").strip().upper()
|
||||
if not code:
|
||||
return {"ok": False, "err": "缺少接入码"}
|
||||
row = _codes.pop(code, None)
|
||||
if not row:
|
||||
_fails.append(time.time())
|
||||
return {"ok": False, "err": "接入码无效或已使用"}
|
||||
if row.get("exp", 0) < time.time():
|
||||
return {"ok": False, "err": "接入码已过期"}
|
||||
import sources.tdb_provision as TP
|
||||
r = TP.get_member_key({"uid": row["uid"], "name": row["name"]})
|
||||
if not r.get("ok"):
|
||||
return {"ok": False, "err": r.get("err") or "换 key 失败"}
|
||||
# 只回必要字段;不回显 uid,桌面端也不需要
|
||||
return {
|
||||
"ok": True,
|
||||
"user_key": r.get("user_key"),
|
||||
"model": r.get("model"),
|
||||
"name": row.get("name"),
|
||||
"tool_token": issue_tool_token(row["uid"]),
|
||||
}
|
||||
|
||||
|
||||
_PAGE = """<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>接入 DSH · 弹匣</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
body { margin:0; min-height:100vh; display:flex; align-items:center; justify-content:center;
|
||||
font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;
|
||||
background:#0f1115; color:#e8eaed; }
|
||||
.card { width:min(92vw,440px); padding:40px 32px; border-radius:18px; background:#171a21;
|
||||
border:1px solid #262b36; text-align:center; }
|
||||
h1 { margin:0 0 6px; font-size:19px; font-weight:600; letter-spacing:.02em; }
|
||||
.sub { margin:0 0 28px; font-size:13px; color:#8b93a3; line-height:1.6; }
|
||||
.code { font-family:ui-monospace,SFMono-Regular,Menlo,monospace; font-size:34px; font-weight:600;
|
||||
letter-spacing:.14em; padding:20px 0; border-radius:12px; background:#0f1115;
|
||||
border:1px solid #2d3442; color:#7dd3a0; user-select:all; }
|
||||
.tip { margin:24px 0 0; font-size:12.5px; color:#8b93a3; line-height:1.8; }
|
||||
.tip b { color:#c7cdd8; font-weight:600; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>接入 DeepSeek Harness</h1>
|
||||
<p class="sub">把这个码填进 DSH 的弹匣登录框</p>
|
||||
<div class="code">__CODE__</div>
|
||||
<p class="tip">
|
||||
<b>__MINUTES__ 分钟内有效</b>,用过一次就作废。<br>
|
||||
只在这一台电脑上用,别发给别人。
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
def page_html(code, expires_in):
|
||||
"""给浏览器看的页面:大字显示接入码。"""
|
||||
minutes = max(1, int(expires_in) // 60)
|
||||
return _PAGE.replace("__CODE__", code).replace("__MINUTES__", str(minutes))
|
||||
|
||||
|
||||
# ── 工具凭证(无状态 HMAC,不给 cookie 权限)────────────────
|
||||
# 为什么不用会话 cookie:cookie 等于完整登录态,拿到就能调所有 API。
|
||||
# 工具凭证只能走下面白名单里那 4 个工具,权限被掐死在源头。
|
||||
TOOL_TTL_DAYS = 90
|
||||
ALLOWED_TOOLS = ("get_summary", "query_tasks", "query_projects", "create_task", "whoami", "toggle_task", "update_task")
|
||||
|
||||
|
||||
def _auth_secret():
|
||||
import auth
|
||||
if auth.SECRET is None:
|
||||
auth.init_auth()
|
||||
return auth.SECRET
|
||||
|
||||
|
||||
def _sign(payload):
|
||||
import hashlib
|
||||
import hmac
|
||||
return hmac.new(_auth_secret(), payload.encode(), hashlib.sha256).hexdigest()[:32]
|
||||
|
||||
|
||||
def issue_tool_token(uid):
|
||||
"""成员 uid → 工具凭证(90 天)。"""
|
||||
exp = int(time.time()) + TOOL_TTL_DAYS * 86400
|
||||
payload = "dsh|%s|%d" % (uid, exp)
|
||||
return "%s|%s" % (payload, _sign(payload))
|
||||
|
||||
|
||||
def verify_tool_token(tok):
|
||||
"""工具凭证 → uid;无效/过期返回 None。
|
||||
|
||||
格式是四段:dsh | uid | exp | 签名(签名覆盖前三段)。
|
||||
"""
|
||||
try:
|
||||
parts = (tok or "").strip().split("|")
|
||||
if len(parts) != 4 or parts[0] != "dsh":
|
||||
return None
|
||||
_, uid, exp, sig = parts
|
||||
if int(exp) < time.time():
|
||||
return None
|
||||
import hmac
|
||||
if not hmac.compare_digest(_sign("%s|%s|%s" % (parts[0], uid, exp)), sig):
|
||||
return None
|
||||
return uid
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def session_of(uid):
|
||||
"""uid → 会话态(与网页会话同构:实时查 members,停用即失效)。"""
|
||||
import sources.members_store as M
|
||||
m = M.find(uid)
|
||||
if not m:
|
||||
return None
|
||||
if not m.get("active", 1):
|
||||
return None
|
||||
return {
|
||||
"uid": uid,
|
||||
"name": m.get("name") or "",
|
||||
"role": m.get("role", "member"),
|
||||
"depts": (m.get("depts") or "").split(",") if m.get("depts") else [],
|
||||
}
|
||||
|
||||
|
||||
def _visible_task(tid, sess):
|
||||
"""取一条任务并校验调用者可见性(与网页版 api/tasks/update 同一口径)。"""
|
||||
import sources.tasks_store as T
|
||||
from main import _vis_ok
|
||||
try:
|
||||
tid = int(tid)
|
||||
except (TypeError, ValueError):
|
||||
return None, "任务 id 非法"
|
||||
row = T.get_task(tid)
|
||||
if not row:
|
||||
return None, "任务不存在"
|
||||
if not _vis_ok(row, sess):
|
||||
return None, "非本部门任务,没有权限"
|
||||
return row, None
|
||||
|
||||
|
||||
def dispatch(tok, tool, args):
|
||||
"""工具凭证 + 工具名 → 执行(复用 agent 的四件工具,含部门可见性)。"""
|
||||
uid = verify_tool_token(tok)
|
||||
if not uid:
|
||||
return {"ok": False, "err": "凭证无效或已过期,请重新登录"}
|
||||
sess = session_of(uid)
|
||||
if not sess:
|
||||
return {"ok": False, "err": "账号已停用或无权限"}
|
||||
name = (tool or "").strip()
|
||||
if name not in ALLOWED_TOOLS:
|
||||
return {"ok": False, "err": "不支持的工具:%s" % name}
|
||||
if name == "toggle_task":
|
||||
# 状态流转只走 tasks_store.cycle —— 活动日志、依赖预警都在那边,不在这里重写
|
||||
row, err = _visible_task(args.get("id"), sess)
|
||||
if err:
|
||||
return {"ok": False, "err": err}
|
||||
import sources.tasks_store as T
|
||||
want = (args.get("to") or "").strip()
|
||||
target = want if want else ("todo" if row.get("status") == "done" else "done")
|
||||
new_status = T.cycle(row["id"], target, actor=sess.get("name") or "dsh")
|
||||
if not new_status:
|
||||
return {"ok": False, "err": "状态流转失败(目标状态不合法)"}
|
||||
return {"ok": True, "result": {"id": row["id"], "status": new_status}}
|
||||
|
||||
if name == "update_task":
|
||||
# 字段白名单与 diff 记录在 tasks_store.update 里,这里只做可见性把关
|
||||
row, err = _visible_task(args.get("id"), sess)
|
||||
if err:
|
||||
return {"ok": False, "err": err}
|
||||
import sources.tasks_store as T
|
||||
patch = dict(args.get("patch") or {})
|
||||
done = T.update(row["id"], patch, actor=sess.get("name") or "dsh")
|
||||
if not done:
|
||||
return {"ok": False, "err": "更新失败(字段非法或依赖成环)"}
|
||||
return {"ok": True, "result": {"id": row["id"]}}
|
||||
|
||||
if name == "whoami":
|
||||
# 只回身份与可见范围,不回任何凭证
|
||||
return {"ok": True, "result": {"name": sess.get("name"), "role": sess.get("role"), "depts": sess.get("depts")}}
|
||||
try:
|
||||
import agent
|
||||
safe = dict(args or {})
|
||||
safe["_by"] = sess.get("name") or "dsh"
|
||||
return {"ok": True, "result": agent._run_tool(name, safe, sess)}
|
||||
except Exception as e:
|
||||
return {"ok": False, "err": "执行失败:%s" % str(e)[:120]}
|
||||
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""成员停用 → 吊销他名下全部 TDB key(2026-11-07)。
|
||||
|
||||
为什么是吊销 key,不是停用账号:
|
||||
TDB 没有「在职/离职」这回事。它的鉴权只认两样东西 —— key 的状态和过期时间,
|
||||
而且每个请求都实时验(MemoryProxy 不缓存验证结果)。所以对 TDB 来说,
|
||||
「这个人还在不在」等价于「他手里的 key 还能不能用」。
|
||||
|
||||
为什么不直接调 user-key/revoke:
|
||||
内核的 revoke 会拒绝撤销「最后一个有效 key」(否则用户手里一把能用的都不剩)。
|
||||
而离职场景恰恰是要把他所有 key 都废掉,所以统一改 expires_at 到过去 ——
|
||||
鉴权每次都查这个字段,效果等同吊销,且不会撞上那条保护。
|
||||
|
||||
恢复:
|
||||
成员重新启用后,下次取 key 时 tdb_provision 会发现本地缓存已清,自动重开一把新的。
|
||||
失效是即时的,恢复也是自动的。
|
||||
|
||||
审计:
|
||||
key 记录本身不删(只改过期时间),谁什么时候被停用、废了几把,都留得住。
|
||||
"""
|
||||
import time
|
||||
|
||||
PAST = "2020-01-01T00:00:00.000Z"
|
||||
|
||||
|
||||
def revoke_member_keys(uid):
|
||||
"""吊销某成员全部有效 key。返回 {ok, revoked, user_id} 或 {ok:False, err}。"""
|
||||
if not uid:
|
||||
return {"ok": False, "err": "缺少成员 uid"}
|
||||
try:
|
||||
import sources.tdb_provision as TP
|
||||
except Exception as e:
|
||||
return {"ok": False, "err": "模块不可用:%s" % str(e)[:80]}
|
||||
|
||||
if not TP._conf():
|
||||
return {"ok": False, "err": "团队 AI 未配置(tdb_admin.json 缺失)"}
|
||||
|
||||
conn = None
|
||||
try:
|
||||
conn = TP._local_cache()
|
||||
cached = TP._cache_get(conn, uid) or {}
|
||||
user_id = cached.get("user_id") or ""
|
||||
|
||||
# 缓存里没有这个人 → 按成员姓名去 TDB 找
|
||||
if not user_id:
|
||||
import sources.members_store as M
|
||||
name = (M.find(uid) or {}).get("name") or ""
|
||||
if not name:
|
||||
return {"ok": True, "revoked": 0, "note": "成员不存在"}
|
||||
listing = TP._core("POST", "/v3/meta/user/list", {"page": 1, "page_size": 200})
|
||||
for u in listing.get("items") or []:
|
||||
if u.get("username") == name:
|
||||
user_id = u.get("user_id") or ""
|
||||
break
|
||||
if not user_id:
|
||||
return {"ok": True, "revoked": 0, "note": "该成员还没有 TDB 账号,无需吊销"}
|
||||
|
||||
keys = TP._core("POST", "/v3/meta/user-key/list", {"user_id": user_id})
|
||||
items = keys.get("items") or []
|
||||
revoked = 0
|
||||
failed = []
|
||||
for k in items:
|
||||
if (k or {}).get("status") != "active":
|
||||
continue
|
||||
kid = k.get("key_id")
|
||||
if not kid:
|
||||
continue
|
||||
try:
|
||||
TP._core("POST", "/v3/meta/user-key/update", {"key_id": kid, "expires_at": PAST})
|
||||
revoked += 1
|
||||
except Exception as e:
|
||||
failed.append("%s: %s" % (kid, str(e)[:60]))
|
||||
|
||||
# 清本地缓存:不清的话,取 key 接口 24 小时内还会把旧 key 递出去
|
||||
if conn:
|
||||
try:
|
||||
conn.execute("DELETE FROM accounts WHERE uid=?", (uid,))
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
out = {"ok": True, "revoked": revoked, "user_id": user_id, "at": time.strftime("%Y-%m-%d %H:%M")}
|
||||
if failed:
|
||||
out["failed"] = failed[:5]
|
||||
return out
|
||||
except Exception as e:
|
||||
return {"ok": False, "err": str(e)[:140]}
|
||||
finally:
|
||||
if conn:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def revoke_status(uid):
|
||||
"""只读:看某成员名下 key 的现状(给管理页用,不动数据)。"""
|
||||
try:
|
||||
import sources.tdb_provision as TP
|
||||
conn = TP._local_cache()
|
||||
cached = TP._cache_get(conn, uid) or {}
|
||||
user_id = cached.get("user_id") or ""
|
||||
if conn:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
if not user_id:
|
||||
return {"ok": True, "user_id": "", "keys": []}
|
||||
listing = TP._core("POST", "/v3/meta/user-key/list", {"user_id": user_id})
|
||||
rows = []
|
||||
for k in listing.get("items") or []:
|
||||
rows.append({
|
||||
"key_id": k.get("key_id"),
|
||||
"prefix": k.get("key_prefix"),
|
||||
"status": k.get("status"),
|
||||
"expires_at": k.get("expires_at"),
|
||||
"last_used_at": k.get("last_used_at"),
|
||||
})
|
||||
return {"ok": True, "user_id": user_id, "keys": rows}
|
||||
except Exception as e:
|
||||
return {"ok": False, "err": str(e)[:120]}
|
||||
Vendored
+434
@@ -0,0 +1,434 @@
|
||||
/**
|
||||
* 弹匣工作台 —— DSH 客户端半片(侧边栏面板)。
|
||||
*
|
||||
* 定位:DSH 里「我现在该干什么」+ 就地处理 + 一键跳回弹匣看全貌。
|
||||
* 数据与写操作全部走 /__markmag/*(宿主转调弹匣 API,鉴权用工具凭证)。
|
||||
*
|
||||
* 写操作的规矩:面板只把按钮接到弹匣已有的能力上(tasks_store.cycle / update / create),
|
||||
* 状态机、字段白名单、部门可见性、活动日志、依赖预警全在弹匣侧判定,这里一行规则都不重写。
|
||||
*
|
||||
* 默认个人看板;第二栏的可见范围由弹匣后端 _vis_ok 决定,面板只按角色给名字。
|
||||
* 产物由 scripts/build-client.mjs 从 panel.css + panel.template.js 合成。
|
||||
*/
|
||||
window.__ModuleLoader__.load({
|
||||
id: "dsh-markmag",
|
||||
factory: function (require) {
|
||||
const module = { exports: {} }
|
||||
const exports = module.exports
|
||||
|
||||
const reactMod = require("react")
|
||||
const React = reactMod && reactMod.default ? reactMod.default : reactMod
|
||||
const h = React.createElement
|
||||
const useState = React.useState
|
||||
const useEffect = React.useEffect
|
||||
const useCallback = React.useCallback
|
||||
const useMemo = React.useMemo
|
||||
|
||||
const KEY = "markmag"
|
||||
const BASE = "https://brain.sidaocai.cn/markmag/"
|
||||
const CSS = ".mm-wrap{\n --ink:var(--dsw-alias-label-primary,#111);\n --ink2:var(--dsw-alias-label-secondary,#555);\n --ink3:var(--dsw-alias-label-tertiary,#888);\n --ink4:var(--dsw-alias-label-caption,#aaa);\n --line:var(--dsw-alias-border-l2,rgba(0,0,0,.1));\n --line2:var(--dsw-alias-border-l4,rgba(0,0,0,.16));\n --card:var(--dsw-alias-bg-layer-2,#fff);\n --bg:var(--dsw-alias-bg-base,#f7f7f8);\n --hover:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04));\n --primary:var(--dsw-alias-button-primary-fill,#2E6BFF);\n --primary-hover:var(--dsw-alias-button-primary-hover,#4D82FF);\n --on-primary:var(--dsw-alias-label-primary-inverted,#fff);\n --ok:var(--dsw-alias-state-success-primary,#10B981);\n --warn:var(--dsw-alias-state-warn-primary,#D9A406);\n --err:var(--dsw-alias-state-error-primary,#E5484D);\n --info:var(--dsw-alias-state-business-primary,#2E6BFF);\n --idle:var(--dsw-alias-state-idle-primary,#9aa2ad);\n --r-sm:var(--dsw-radius-sm,8px);\n --r-md:var(--dsw-radius-md,12px);\n --r-xl:var(--dsw-radius-xl,20px);\n height:100%;overflow:auto;background:var(--bg);color:var(--ink);\n font-family:-apple-system,BlinkMacSystemFont,\"PingFang SC\",\"Microsoft YaHei\",sans-serif;\n font-size:13px;line-height:1.5;-webkit-font-smoothing:antialiased;\n}\n.mm-inner{max-width:1000px;margin:0 auto;padding:20px 22px 48px}\n.mm-head{display:flex;align-items:center;gap:11px;margin-bottom:14px}\n.mm-logo{width:32px;height:32px;border-radius:var(--r-md);flex:none;display:grid;place-items:center;\n background:var(--primary);color:var(--on-primary)}\n.mm-title{font-size:15.5px;font-weight:650;letter-spacing:.01em}\n.mm-sub{font-size:11.5px;color:var(--ink4);margin-top:2px}\n.mm-actions{margin-left:auto;display:flex;align-items:center;gap:8px;flex:none}\n.mm-btn{border:1px solid var(--line);background:transparent;color:var(--ink2);\n border-radius:var(--r-sm);padding:5px 11px;font-size:12px;cursor:pointer;transition:.15s;\n white-space:nowrap;font-family:inherit}\n.mm-btn:hover{background:var(--hover);color:var(--ink);border-color:var(--line2)}\n.mm-btn:disabled{cursor:default;opacity:.6}\n.mm-btn-primary{background:var(--primary);border-color:transparent;color:var(--on-primary);font-weight:560}\n.mm-btn-primary:hover{background:var(--primary-hover);color:var(--on-primary)}\n.mm-nav{display:flex;gap:4px;border-bottom:1px solid var(--line);margin-bottom:16px}\n.mm-nav-i{border:none;background:transparent;color:var(--ink3);font-size:13px;font-family:inherit;\n padding:8px 12px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px;transition:.15s;\n display:flex;align-items:center;gap:6px}\n.mm-nav-i:hover{color:var(--ink)}\n.mm-nav-on{color:var(--primary);border-bottom-color:var(--primary);font-weight:560}\n.mm-nav-c{font-size:10.5px;background:var(--hover);border-radius:999px;padding:0 6px;color:var(--ink3);\n font-variant-numeric:tabular-nums}\n.mm-nav-on .mm-nav-c{background:color-mix(in srgb,var(--primary) 16%,transparent);color:var(--primary)}\n.mm-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:20px}\n.mm-stat{background:var(--card);border:1px solid var(--line);border-radius:var(--r-xl);padding:15px 17px}\n.mm-stat-n{font-size:26px;font-weight:660;letter-spacing:-.02em;line-height:1.1;font-variant-numeric:tabular-nums}\n.mm-stat-l{font-size:11.5px;color:var(--ink3);margin-top:4px}\n.mm-card{background:var(--card);border:1px solid var(--line);border-radius:var(--r-xl);overflow:hidden}\n.mm-row{display:flex;align-items:center;gap:11px;padding:10px 15px;border-top:1px solid var(--line);transition:background .12s}\n.mm-row:first-child{border-top:none}\n.mm-row:hover{background:var(--hover)}\n.mm-dot{width:7px;height:7px;border-radius:50%;flex:none}\n.mm-dot-ok{background:var(--ok)}\n.mm-dot-warn{background:var(--warn)}\n.mm-dot-err{background:var(--err)}\n.mm-dot-idle{background:var(--idle)}\n.mm-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ink)}\n.mm-meta{font-size:11.5px;color:var(--ink3);flex:none;white-space:nowrap}\n.mm-date{font-family:ui-monospace,\"SF Mono\",Menlo,monospace;font-size:11.5px;color:var(--ink4);\n flex:none;font-variant-numeric:tabular-nums}\n.mm-date-late{color:var(--err)}\n.mm-badge{font-size:11px;font-weight:560;padding:2px 8px;border-radius:var(--r-sm);flex:none;white-space:nowrap}\n.mm-b-todo{background:var(--hover);color:var(--ink2)}\n.mm-b-doing{background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}\n.mm-b-blocked{background:color-mix(in srgb,var(--err) 14%,transparent);color:var(--err)}\n.mm-b-done{background:color-mix(in srgb,var(--ok) 14%,transparent);color:var(--ok)}\n.mm-empty{padding:24px 16px;text-align:center;color:var(--ink4);font-size:12.5px}\n.mm-err{background:color-mix(in srgb,var(--err) 10%,transparent);border:1px solid var(--err);\n color:var(--err);border-radius:var(--r-md);padding:10px 13px;font-size:12.5px;margin-bottom:16px}\n.mm-Line truncated
|
||||
|
||||
const HEALTH_CLASS = { green: "mm-dot-ok", yellow: "mm-dot-warn", amber: "mm-dot-warn", red: "mm-dot-err" }
|
||||
const HEALTH_TXT = { green: "健康", yellow: "注意", amber: "注意", red: "异常" }
|
||||
const STATUS = {
|
||||
todo: ["待办", "mm-b-todo"],
|
||||
doing: ["进行中", "mm-b-doing"],
|
||||
blocked: ["受阻", "mm-b-blocked"],
|
||||
done: ["已完成", "mm-b-done"],
|
||||
}
|
||||
const FILTERS = [["", "全部"], ["todo", "待办"], ["doing", "进行中"], ["blocked", "受阻"]]
|
||||
|
||||
function pad2(n) { return String(n).padStart(2, "0") }
|
||||
function todayStr() {
|
||||
const d = new Date()
|
||||
return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate())
|
||||
}
|
||||
function openInMarkmag(hash) { window.open(BASE + (hash || ""), "_blank", "noopener") }
|
||||
|
||||
async function postJson(url, body) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body || {}),
|
||||
})
|
||||
return await res.json()
|
||||
} catch (e) {
|
||||
return { ok: false, err: "请求失败:" + (e.message || e) }
|
||||
}
|
||||
}
|
||||
|
||||
function Icon(props) {
|
||||
const size = (props && props.size) || 20
|
||||
return h("svg", {
|
||||
width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
|
||||
strokeWidth: 1.9, strokeLinecap: "round", strokeLinejoin: "round",
|
||||
},
|
||||
h("rect", { x: 3, y: 4.5, width: 18, height: 15, rx: 2.5 }),
|
||||
h("path", { d: "M7.5 9.5h9" }),
|
||||
h("path", { d: "M7.5 13.5h5.5" })
|
||||
)
|
||||
}
|
||||
|
||||
function Logo() {
|
||||
return h("div", { className: "mm-logo" },
|
||||
h("svg", {
|
||||
width: 17, height: 17, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
|
||||
strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round",
|
||||
},
|
||||
h("rect", { x: 3.5, y: 5, width: 17, height: 14, rx: 2.5 }),
|
||||
h("path", { d: "M8 10h8" }),
|
||||
h("path", { d: "M8 14h4.5" })
|
||||
))
|
||||
}
|
||||
|
||||
function Badge(props) {
|
||||
const st = STATUS[props.status] || [props.status || "", "mm-b-todo"]
|
||||
return h("span", { className: "mm-badge " + st[1] }, st[0])
|
||||
}
|
||||
|
||||
function Skeleton() {
|
||||
return [0, 1, 2].map(function (i) {
|
||||
return h("div", { key: i, className: "mm-row" },
|
||||
h("div", { className: "mm-sk", style: { width: (150 + i * 60) + "px" } }))
|
||||
})
|
||||
}
|
||||
|
||||
function Panel() {
|
||||
const sMe = useState(null), me = sMe[0], setMe = sMe[1]
|
||||
const sTasks = useState([]), tasks = sTasks[0], setTasks = sTasks[1]
|
||||
const sProjects = useState([]), projects = sProjects[0], setProjects = sProjects[1]
|
||||
const sErr = useState(""), err = sErr[0], setErr = sErr[1]
|
||||
const sNote = useState(""), note = sNote[0], setNote = sNote[1]
|
||||
const sLoading = useState(true), loading = sLoading[0], setLoading = sLoading[1]
|
||||
const sAt = useState(""), at = sAt[0], setAt = sAt[1]
|
||||
const sTab = useState("mine"), tab = sTab[0], setTab = sTab[1]
|
||||
const sFilter = useState(""), filter = sFilter[0], setFilter = sFilter[1]
|
||||
const sUrgent = useState(false), urgent = sUrgent[0], setUrgent = sUrgent[1]
|
||||
const sBusy = useState(0), busy = sBusy[0], setBusy = sBusy[1]
|
||||
const sEditing = useState(0), editing = sEditing[0], setEditing = sEditing[1]
|
||||
const sNew = useState(false), showNew = sNew[0], setShowNew = sNew[1]
|
||||
const sForm = useState({ title: "", due: "", project: "" }), form = sForm[0], setForm = sForm[1]
|
||||
|
||||
const load = useCallback(function () {
|
||||
setLoading(true)
|
||||
setErr("")
|
||||
Promise.all([
|
||||
fetch("/__markmag/me", { credentials: "same-origin" }).then(function (r) { return r.json() }),
|
||||
fetch("/__markmag/tasks", { credentials: "same-origin" }).then(function (r) { return r.json() }),
|
||||
fetch("/__markmag/projects", { credentials: "same-origin" }).then(function (r) { return r.json() }),
|
||||
]).then(function (res) {
|
||||
const m = res[0], t = res[1], p = res[2]
|
||||
if (m && m.ok && m.result) setMe(m.result)
|
||||
else if (m && !m.ok) throw new Error(m.err || "读取身份失败")
|
||||
setTasks(t && t.ok && t.result && t.result.tasks ? t.result.tasks : [])
|
||||
setProjects(p && p.ok && p.result && p.result.projects ? p.result.projects : [])
|
||||
setAt(new Date().toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" }))
|
||||
}).catch(function (e) {
|
||||
setErr(e.message || String(e))
|
||||
}).then(function () {
|
||||
setLoading(false)
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(function () { load() }, [load])
|
||||
|
||||
// ── 写操作:都落到弹匣同一套 store,成功后重新拉一遍 ──
|
||||
async function doToggle(t) {
|
||||
setBusy(t.id); setErr(""); setNote("")
|
||||
const r = await postJson("/__markmag/task/toggle", { id: t.id })
|
||||
setBusy(0)
|
||||
if (r && r.ok) {
|
||||
const st = r.result && r.result.status
|
||||
setNote((st === "done" ? "已完成:" : "状态:" + (STATUS[st] ? STATUS[st][0] : st) + " ") + t.title)
|
||||
load()
|
||||
} else setErr((r && r.err) || "操作失败")
|
||||
}
|
||||
|
||||
async function doSetDue(t, due) {
|
||||
setEditing(0); setErr(""); setNote("")
|
||||
if (!due || due === t.due) return
|
||||
setBusy(t.id)
|
||||
const r = await postJson("/__markmag/task/update", { id: t.id, patch: { due: due } })
|
||||
setBusy(0)
|
||||
if (r && r.ok) { setNote("截止日已改为 " + due + ":" + t.title); load() }
|
||||
else setErr((r && r.err) || "改期失败")
|
||||
}
|
||||
|
||||
async function doCreate() {
|
||||
const title = (form.title || "").trim()
|
||||
if (!title) { setErr("先写个任务标题"); return }
|
||||
setBusy(-1); setErr(""); setNote("")
|
||||
const payload = { title: title }
|
||||
if (form.due) payload.due = form.due
|
||||
if (form.project) payload.project = form.project
|
||||
const r = await postJson("/__markmag/task/create", payload)
|
||||
setBusy(0)
|
||||
if (r && r.ok) {
|
||||
setNote("已建任务:" + title)
|
||||
setForm({ title: "", due: "", project: "" })
|
||||
setShowNew(false)
|
||||
load()
|
||||
} else setErr((r && r.err) || "建任务失败")
|
||||
}
|
||||
|
||||
const today = todayStr()
|
||||
const myName = (me && me.name) || ""
|
||||
const myRole = (me && me.role) || "member"
|
||||
const scopeLabel = myRole === "admin" ? "全团队" : (myRole === "dept_admin" ? "本部门" : "部门可见")
|
||||
|
||||
const mine = useMemo(function () {
|
||||
return tasks.filter(function (t) { return t.owner === myName || t.created_by === myName })
|
||||
}, [tasks, myName])
|
||||
|
||||
const openTasks = useMemo(function () {
|
||||
return tasks.filter(function (t) { return t.status !== "done" })
|
||||
}, [tasks])
|
||||
|
||||
const focus = useMemo(function () {
|
||||
return openTasks.filter(function (t) { return t.due && t.due <= today })
|
||||
.sort(function (a, b) { return a.due < b.due ? -1 : 1 })
|
||||
}, [openTasks, today])
|
||||
|
||||
const overdueCount = useMemo(function () {
|
||||
return openTasks.filter(function (t) { return t.due && t.due < today }).length
|
||||
}, [openTasks, today])
|
||||
|
||||
const base = tab === "mine" ? mine.filter(function (t) { return t.status !== "done" }) : openTasks
|
||||
const shown = useMemo(function () {
|
||||
let list = base
|
||||
if (urgent) list = list.filter(function (t) { return t.due && t.due < today })
|
||||
if (filter) list = list.filter(function (t) { return t.status === filter })
|
||||
return list.slice().sort(function (a, b) {
|
||||
if (!a.due && !b.due) return 0
|
||||
if (!a.due) return 1
|
||||
if (!b.due) return -1
|
||||
return a.due < b.due ? -1 : 1
|
||||
})
|
||||
}, [base, urgent, filter, today])
|
||||
|
||||
/** 一行任务:徽章 + 标题 + 负责人 + 日期(可改)+ hover 操作(完成/改期/去弹匣) */
|
||||
function TaskLine(t) {
|
||||
const late = t.due && t.due < today
|
||||
const isEditing = editing === t.id
|
||||
const ops = h("div", { className: "mm-row-ops" },
|
||||
h("button", {
|
||||
className: "mm-op mm-op-done",
|
||||
disabled: busy === t.id,
|
||||
onClick: function (e) { e.stopPropagation(); doToggle(t) },
|
||||
}, t.status === "done" ? "重开" : "完成"),
|
||||
h("button", {
|
||||
className: "mm-op",
|
||||
onClick: function (e) { e.stopPropagation(); setEditing(isEditing ? 0 : t.id) },
|
||||
}, "改期"),
|
||||
h("button", {
|
||||
className: "mm-op",
|
||||
onClick: function (e) { e.stopPropagation(); openInMarkmag("#today") },
|
||||
}, "弹匣"))
|
||||
const dateEl = isEditing
|
||||
? h("input", {
|
||||
className: "mm-date-in",
|
||||
type: "date",
|
||||
defaultValue: t.due || today,
|
||||
autoFocus: true,
|
||||
onClick: function (e) { e.stopPropagation() },
|
||||
onChange: function (e) { doSetDue(t, e.target.value) },
|
||||
onBlur: function () { setEditing(0) },
|
||||
})
|
||||
: h("span", {
|
||||
className: "mm-date mm-date-edit" + (late ? " mm-date-late" : ""),
|
||||
style: { width: 70, textAlign: "right" },
|
||||
onClick: function (e) { e.stopPropagation(); setEditing(t.id) },
|
||||
}, t.due || "设日期")
|
||||
return h("div", {
|
||||
key: t.id,
|
||||
className: "mm-row mm-row-click",
|
||||
onClick: function () { openInMarkmag("#today") },
|
||||
},
|
||||
h(Badge, { status: t.status }),
|
||||
h("span", { className: "mm-name" }, t.title),
|
||||
h("span", { className: "mm-meta", style: { flex: "none" } }, t.owner || ""),
|
||||
dateEl,
|
||||
ops)
|
||||
}
|
||||
|
||||
const focusEl = focus.length
|
||||
? h("div", { className: "mm-focus" },
|
||||
h("div", { className: "mm-focus-h" },
|
||||
h("span", { className: "mm-focus-t" },
|
||||
overdueCount ? "要处理:" + overdueCount + " 项已逾期" : "今天到期"),
|
||||
h("span", { className: "mm-focus-c" }, "可直接完成或改期")),
|
||||
focus.slice(0, 6).map(function (t) { return TaskLine(t) }))
|
||||
: null
|
||||
|
||||
const statsEl = h("div", { className: "mm-stats" },
|
||||
h("div", { className: "mm-stat", style: { cursor: "pointer" },
|
||||
onClick: function () { setTab("scope"); setUrgent(false); setFilter("") } },
|
||||
h("div", { className: "mm-stat-n" }, String(mine.filter(function (t) { return t.status !== "done" }).length)),
|
||||
h("div", { className: "mm-stat-l" }, "我的未完成")),
|
||||
h("div", { className: "mm-stat", style: { cursor: "pointer" },
|
||||
onClick: function () { setTab("scope"); setUrgent(true); setFilter("") } },
|
||||
h("div", { className: "mm-stat-n", style: overdueCount ? { color: "var(--err)" } : null }, String(overdueCount)),
|
||||
h("div", { className: "mm-stat-l" }, "已逾期")),
|
||||
h("div", { className: "mm-stat", style: { cursor: "pointer" },
|
||||
onClick: function () { openInMarkmag("#proj") } },
|
||||
h("div", { className: "mm-stat-n" }, String(projects.length)),
|
||||
h("div", { className: "mm-stat-l" }, "项目")))
|
||||
|
||||
const tabsEl = h("div", { className: "mm-actions-2" },
|
||||
[["mine", "我的"], ["scope", scopeLabel]].map(function (item) {
|
||||
const k = item[0], label = item[1]
|
||||
return h("button", {
|
||||
key: k,
|
||||
className: "mm-tab" + (tab === k ? " mm-tab-on" : ""),
|
||||
onClick: function () { setTab(k); setUrgent(false) },
|
||||
}, label)
|
||||
}),
|
||||
h("span", { style: { flex: 1 } }),
|
||||
urgent ? h("button", { className: "mm-tab mm-tab-on", onClick: function () { setUrgent(false) } }, "只看逾期 ×") : null)
|
||||
|
||||
const filtersEl = h("div", { className: "mm-actions-2" },
|
||||
FILTERS.map(function (f) {
|
||||
const v = f[0], label = f[1]
|
||||
return h("button", {
|
||||
key: "f" + v,
|
||||
className: "mm-tab" + (filter === v ? " mm-tab-on" : ""),
|
||||
onClick: function () { setFilter(v) },
|
||||
}, label)
|
||||
}))
|
||||
|
||||
const taskRows = shown.length
|
||||
? shown.map(function (t) { return TaskLine(t) })
|
||||
: (loading
|
||||
? h(Skeleton)
|
||||
: h("div", { className: "mm-empty-hint" },
|
||||
tab === "mine" ? "你手上没有到期任务" : "这个范围里没有任务"))
|
||||
|
||||
const projectOptions = projects.map(function (p) {
|
||||
return h("option", { key: p.id, value: p.id }, p.name)
|
||||
})
|
||||
|
||||
const newEl = h("div", { className: "mm-new" },
|
||||
showNew
|
||||
? h("div", { className: "mm-card" },
|
||||
h("div", { className: "mm-new-row" },
|
||||
h("input", {
|
||||
className: "mm-in mm-in-t",
|
||||
placeholder: "任务标题",
|
||||
value: form.title,
|
||||
autoFocus: true,
|
||||
onChange: function (e) { setForm(Object.assign({}, form, { title: e.target.value })) },
|
||||
onKeyDown: function (e) { if (e.key === "Enter") doCreate() },
|
||||
}),
|
||||
h("input", {
|
||||
className: "mm-in mm-in-d",
|
||||
type: "date",
|
||||
value: form.due,
|
||||
onChange: function (e) { setForm(Object.assign({}, form, { due: e.target.value })) },
|
||||
}),
|
||||
h("select", {
|
||||
className: "mm-in mm-in-s",
|
||||
value: form.project,
|
||||
onChange: function (e) { setForm(Object.assign({}, form, { project: e.target.value })) },
|
||||
}, h("option", { value: "" }, "不挂项目"), projectOptions),
|
||||
h("button", {
|
||||
className: "mm-btn mm-btn-primary",
|
||||
disabled: busy === -1,
|
||||
onClick: doCreate,
|
||||
}, busy === -1 ? "提交中…" : "建任务"),
|
||||
h("button", { className: "mm-btn", onClick: function () { setShowNew(false) } }, "取消")))
|
||||
: h("button", {
|
||||
className: "mm-btn",
|
||||
style: { width: "100%" },
|
||||
onClick: function () { setShowNew(true); setNote("") },
|
||||
}, "+ 快速建任务"))
|
||||
|
||||
const projectCards = projects.length
|
||||
? projects.map(function (p, i) {
|
||||
const key = String(p.health || "").toLowerCase()
|
||||
const pct = typeof p.progress === "number" ? Math.max(0, Math.min(100, p.progress)) : null
|
||||
return h("div", {
|
||||
key: p.id || i,
|
||||
className: "mm-pcard",
|
||||
onClick: function () { openInMarkmag(p.id ? "#d/" + p.id : "#proj") },
|
||||
},
|
||||
h("div", { className: "mm-pcard-n" }, p.name),
|
||||
h("div", { className: "mm-pcard-m" },
|
||||
h("span", { className: "mm-dot " + (HEALTH_CLASS[key] || "mm-dot-idle") }),
|
||||
h("span", null, HEALTH_TXT[key] || "—"),
|
||||
p.stage ? h("span", null, "· " + p.stage) : null,
|
||||
p.owner ? h("span", null, "· " + p.owner) : null),
|
||||
pct === null ? null : h("div", { className: "mm-bar" },
|
||||
h("div", { className: "mm-bar-i", style: { width: pct + "%" } })))
|
||||
})
|
||||
: h("div", { className: "mm-pcard" },
|
||||
h("div", { className: "mm-pcard-n" }, loading ? "读取中…" : "还没有项目"))
|
||||
|
||||
const identity = me
|
||||
? myName + (myRole === "admin" ? " · 团队负责人" : myRole === "dept_admin" ? " · 部门负责人" : "")
|
||||
: ""
|
||||
|
||||
return h("div", { className: "mm-wrap" },
|
||||
h("style", { dangerouslySetInnerHTML: { __html: CSS } }),
|
||||
h("div", { className: "mm-inner" },
|
||||
h("div", { className: "mm-head" },
|
||||
h(Logo),
|
||||
h("div", null,
|
||||
h("div", { className: "mm-title" }, "弹匣工作台"),
|
||||
h("div", { className: "mm-sub" }, identity || (at ? "数据更新于 " + at : "四道菜 · 团队作战台"))),
|
||||
h("div", { className: "mm-actions" },
|
||||
h("button", { className: "mm-btn", onClick: load, disabled: loading },
|
||||
loading ? "读取中…" : "刷新"),
|
||||
h("button", {
|
||||
className: "mm-btn mm-btn-primary",
|
||||
onClick: function () { openInMarkmag("#today") },
|
||||
}, "弹匣全貌"))),
|
||||
|
||||
err ? h("div", { className: "mm-err" }, err) : null,
|
||||
note ? h("div", { className: "mm-ok" }, note) : null,
|
||||
focusEl,
|
||||
statsEl,
|
||||
|
||||
h("div", { className: "mm-sec" },
|
||||
h("div", { className: "mm-sec-h" },
|
||||
h("span", { className: "mm-sec-t" }, "任务"),
|
||||
h("span", { className: "mm-sec-c" }, String(shown.length))),
|
||||
tabsEl,
|
||||
filtersEl,
|
||||
h("div", { className: "mm-card" }, taskRows),
|
||||
newEl),
|
||||
|
||||
h("div", { className: "mm-sec" },
|
||||
h("div", { className: "mm-sec-h" },
|
||||
h("span", { className: "mm-sec-t" }, "项目"),
|
||||
h("span", { className: "mm-sec-c" }, String(projects.length))),
|
||||
h("div", { className: "mm-grid" }, projectCards)),
|
||||
|
||||
h("div", { className: "mm-foot" }, "悬停任务行可完成 / 改期 · 写操作与弹匣同一套规则")))
|
||||
}
|
||||
|
||||
function apply(ctx) {
|
||||
ctx.slots.inject("main", function () {
|
||||
return ctx.slots.register({ name: "main", key: KEY }, Panel)
|
||||
})
|
||||
ctx.effect(function () {
|
||||
let dispose = null
|
||||
function mount() {
|
||||
if (dispose) dispose()
|
||||
dispose = ctx.slots.inject("sidebar.panellist", function () {
|
||||
return ctx.slots.register(
|
||||
{ name: "sidebar.panellist", id: KEY, order: 6, label: function () { return "弹匣工作台" } },
|
||||
Icon
|
||||
)
|
||||
})
|
||||
}
|
||||
mount()
|
||||
return function () { if (dispose) dispose() }
|
||||
}, "dsh-markmag: sidebar entry")
|
||||
}
|
||||
|
||||
module.exports = { inject: ["slots"], apply: apply }
|
||||
return module.exports
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
# 弹匣面板 · UI/UX 规划
|
||||
|
||||
> 2026-11-07。前四版 UI 被打回,原因是先做了样式没定结构。这份文件是先定"怎么用",再谈"长什么样"。
|
||||
> 代码位置:`src/panel/panel.css` + `src/panel/panel.template.js` → `scripts/build-client.mjs` → `dist/client.js`
|
||||
|
||||
## 一、它是什么
|
||||
|
||||
**DSH 里的「我现在该干什么」+ 一键跳回弹匣。** 只读、只跳转,不编辑。
|
||||
|
||||
不是弹匣的替代品,也不是弹匣功能的全集。判断标准只有一条:**这一屏看完,知道下一步点哪儿。**
|
||||
|
||||
## 二、三层结构(解决"一页塞满")
|
||||
|
||||
| 层 | 内容 | 目的 |
|
||||
|---|---|---|
|
||||
| L1 首页 | 焦点区 + 三个数字 + 项目矩阵 | 5 秒看出今天要处理什么 |
|
||||
| L2 面板内 | 任务全量(按状态筛)/ 项目列表 | 要翻的时候有地方翻 |
|
||||
| L3 跳弹匣 | `#today` / `#proj` / `#d/<项目id>` | 真正干活回弹匣 |
|
||||
|
||||
## 三、首页布局(从上到下)
|
||||
|
||||
1. **焦点区**(最重要,占首屏)
|
||||
- 逾期任务(红)+ 今天到期
|
||||
- 每条一行,可点 → 打开弹匣
|
||||
- 没有就显示"今天没有逾期,专心干活",不留空框
|
||||
|
||||
2. **数字区**(三格,全部可点)
|
||||
| 数字 | 点它 |
|
||||
|---|---|
|
||||
| 项目 N | 切到项目视图 |
|
||||
| 未完成 N | 切到任务视图(全部) |
|
||||
| 逾期 N | 切到任务视图(只看逾期) |
|
||||
|
||||
3. **项目矩阵**(2 列卡片,不截断名称)
|
||||
- 每张卡:项目名(完整)+ 健康度色条 + 阶段 + 负责人
|
||||
- 点卡 → 弹匣 `#d/<项目id>` 项目详情
|
||||
|
||||
## 四、明确不做
|
||||
|
||||
- ❌ 日历 / 甘特 / 复杂表格(都不如弹匣本体,且要两套维护)
|
||||
- ❌ 面板内编辑(改任务回弹匣,避免规则两处实现)
|
||||
- ❌ 无行动价值的数字
|
||||
|
||||
## 五、视觉规范
|
||||
|
||||
- **颜色全走 DSH 变量**(`--dsw-alias-*`),深浅色自动跟随
|
||||
- 项目 = 卡片矩阵(2 列);任务 = 紧凑行(要能快速扫)
|
||||
- 数字大(26px/660),标签小(11.5px/三级文字色)
|
||||
- 可点元素都有 hover 反馈(背景 + 边框)
|
||||
- 卡片圆角 20px(`--dsw-radius-xl`),内边距 16-18px
|
||||
|
||||
## 六、待你确认
|
||||
|
||||
1. **默认看谁的活**:我的任务 / 全团队(建议默认我的,右上角可切)
|
||||
2. **项目卡要不要进度条**:弹匣项目有进度字段就显示,没有就只显示阶段
|
||||
3. **任务点击跳转**:弹匣现在只能跳到 `#today` 看板(不能定位到某一条),可接受吗
|
||||
|
||||
## 七、验收标准
|
||||
|
||||
- 打开面板 5 秒内能回答"今天我必须做什么"
|
||||
- 任一数字/卡片/任务行,点下去都能到弹匣的对应位置
|
||||
- 项目名完整显示,不出现省略号
|
||||
- 深浅色切换不用改代码
|
||||
|
||||
## 八、默认视图与角色(2026-11-07 鑫哥定)
|
||||
|
||||
**默认永远是个人的。** 但不同角色看到的东西不一样,因为**可见性规则本来就在弹匣后端**:
|
||||
|
||||
弹匣的 `_vis_ok` 规则 = 部门内可见 OR 我是负责人/创建者。所以面板拿到的数据,天然就是「这个人该看的」,
|
||||
面板不需要自己判权限——它只做分栏。
|
||||
|
||||
| 角色 | 默认「我的」 | 第二栏(名字随角色变) |
|
||||
|---|---|---|
|
||||
| 成员 member | 我负责 + 我创建的任务 | 「部门可见」——同部门的相关任务 |
|
||||
| 部门负责人 dept_admin | 同上 | 「本部门」——本部门全部任务 |
|
||||
| 团队负责人 admin | 同上 | 「全团队」——全团队任务 |
|
||||
|
||||
配套:面板需要知道「我是谁、什么角色」,所以弹匣加一个只读的 `whoami`(走同一张工具凭证)。
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
# 插件发布与更新方案
|
||||
|
||||
> 2026-11-07。目标:不再靠「发文件包」—— 发布一条命令、更新一条命令。
|
||||
|
||||
## 一、现状
|
||||
|
||||
| 项 | 现状 |
|
||||
|---|---|
|
||||
| 代码 | 本地目录 `~/Documents/Essay_AI/Essay_system/dsh-markmag`,**没有进 Git** |
|
||||
| 安装 | 手工跑 `scripts/install.mjs`,把文件复制进 profile 的 node_modules |
|
||||
| profile 依赖 | `"dsh-markmag": "file:/Users/essay/.../dsh-markmag"` |
|
||||
| profile 包管理 | **pnpm 11.1.3**(`pnpm-lock.yaml` + `pnpm-workspace.yaml`,nodeLinker: hoisted) |
|
||||
| 版本 | 0.1.0,无 tag、无 changelog |
|
||||
|
||||
真正的问题不是「发文件包」,而是**没有版本、没有仓库、没有升级路径**。多人之后,谁装的是哪个版本完全不可知。
|
||||
|
||||
## 二、已验证的条件
|
||||
|
||||
| 条件 | 结果 |
|
||||
|---|---|
|
||||
| Gitea 版本 | **28.1.0**(`brain.sidaocai.cn/git`) |
|
||||
| Gitea npm registry | **已开通** —— `/api/packages/sidaocai/npm/dsh-markmag` 返回 `401 reqPackageAccess`(鉴权响应,不是 404) |
|
||||
| pnpm | 11.1.3,profile 由它管 |
|
||||
|
||||
**结论:不需要新建任何服务**,Gitea 自带 npm 私有仓库。
|
||||
|
||||
## 三、目标架构
|
||||
|
||||
```
|
||||
代码 → Gitea 仓库 sidaocai/dsh-markmag(私有)
|
||||
│ npm publish
|
||||
▼
|
||||
包 → Gitea npm registry @sidaocai/dsh-markmag
|
||||
│ pnpm install / update
|
||||
▼
|
||||
每人 → ~/.dsh/profiles/desktop/node_modules/dsh-markmag
|
||||
```
|
||||
|
||||
## 四、三条命令(三种角色)
|
||||
|
||||
### 我发布(每次改完代码)
|
||||
|
||||
```bash
|
||||
cd ~/Documents/Essay_AI/Essay_system/dsh-markmag
|
||||
node scripts/build-client.mjs # 生成 dist/client.js
|
||||
npm version patch # 0.1.0 → 0.1.1;加功能用 minor
|
||||
git push origin main --follow-tags
|
||||
npm publish # 推到 Gitea registry
|
||||
```
|
||||
|
||||
### 同事首次安装(一次性)
|
||||
|
||||
```bash
|
||||
node scripts/setup-account.mjs # 已包含装插件 + 取钥匙
|
||||
```
|
||||
|
||||
### 更新(已装过的人)
|
||||
|
||||
```bash
|
||||
node scripts/update.mjs # 拉最新版 + 重建 client + 装进 profile
|
||||
```
|
||||
|
||||
重启 DSH 生效。
|
||||
|
||||
## 五、一次性配置
|
||||
|
||||
1. **建 Gitea 仓库** `sidaocai/dsh-markmag`,私有。
|
||||
2. **发布用 .npmrc**(放 `~/.npmrc`,token 不进仓库):
|
||||
|
||||
```
|
||||
@sidaocai:registry=https://brain.sidaocai.cn/git/api/packages/sidaocai/npm/
|
||||
//brain.sidaocai.cn/git/api/packages/sidaocai/npm/:_authToken=<GITEA_TOKEN>
|
||||
```
|
||||
|
||||
3. **profile 的 .npmrc**(`~/.dsh/profiles/desktop/.npmrc`)同样指向 Gitea registry。
|
||||
|
||||
## 六、版本与变更记录
|
||||
|
||||
- `CHANGELOG.md` 每次发布记:版本号 + 改了什么 + 是否需要重新登录/重启
|
||||
- 面板顶部显示自身版本号
|
||||
- 修 bug 用 patch,加功能用 minor,改权限或协议用 major
|
||||
|
||||
## 七、更新提示(避免「不知道有新版本」)
|
||||
|
||||
**推荐 B 方案:弹匣后端登记最新版**
|
||||
|
||||
| 方案 | 做法 | 代价 |
|
||||
|---|---|---|
|
||||
| A | 面板直接查 Gitea 的包元数据 | 要给每个人发 Gitea 读权限 token |
|
||||
| **B** | 弹匣加配置项 `plugin_latest`,面板比对后提示 | 改版本只需更新一处配置 |
|
||||
|
||||
## 八、分两阶段
|
||||
|
||||
### 阶段一(现在,单人):先补最小闭环
|
||||
- 代码进 Gitea 私有仓库
|
||||
- 加 `CHANGELOG.md` + 版本号
|
||||
- 写 `scripts/update.mjs`(本地重新构建 + 装)
|
||||
- **不上 registry** —— 单人场景没必要
|
||||
|
||||
### 阶段二(团队铺开前):切 registry
|
||||
- 配好 npm 私有仓库
|
||||
- profile 依赖从 `file:` 改成 `^0.1.0`
|
||||
- 同事 `pnpm install` 自动拉
|
||||
- 加更新提示
|
||||
|
||||
## 九、待验证(阶段二前必须实测)
|
||||
|
||||
1. **桌面版 profile 能否被 pnpm 正常维护** —— Electron 启动时会不会覆盖 node_modules(这是最大未知数)
|
||||
2. Gitea npm registry 的读权限怎么给团队成员(组织成员 / token)
|
||||
3. 包体积(client.js 31KB + src,可接受)
|
||||
|
||||
## 十、不做什么
|
||||
|
||||
- 不急着上 CI/CD(10 人团队,本地 publish 一条命令够用)
|
||||
- 不做插件自更新(自动拉远程代码执行风险高;要更新就明确跑一条命令)
|
||||
- 不引入 Verdaccio 等独立 registry(Gitea 已有)
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "@sidaocai/dsh-markmag",
|
||||
"version": "0.1.0",
|
||||
"description": "DeepSeek Harness 插件 · 四道菜团队中台:公司模型通道 + 弹匣工具面 + 团队记忆",
|
||||
"type": "module",
|
||||
"main": "src/host.js",
|
||||
"exports": {
|
||||
".": "./src/host.js",
|
||||
"./client": "./dist/client.js",
|
||||
"./cordis.patch.yml": "./cordis.patch.yml",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
},
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-runtime"
|
||||
]
|
||||
}
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20",
|
||||
"dsh": ">=0.2.1-rc.5 <0.3.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"registry": "https://brain.sidaocai.cn/git/api/packages/sidaocai/npm/"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://brain.sidaocai.cn/git/sidaocai/dsh-markmag.git"
|
||||
},
|
||||
"homepage": "https://brain.sidaocai.cn/git/sidaocai/dsh-markmag",
|
||||
"bugs": {
|
||||
"url": "https://brain.sidaocai.cn/git/sidaocai/dsh-markmag/issues"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node scripts/build-client.mjs",
|
||||
"prepack": "node scripts/build-client.mjs",
|
||||
"prepublishOnly": "node scripts/preflight.mjs"
|
||||
},
|
||||
"files": [
|
||||
"src",
|
||||
"dist",
|
||||
"cordis.patch.yml",
|
||||
"README.md",
|
||||
"LICENSE",
|
||||
"CHANGELOG.md"
|
||||
],
|
||||
"keywords": [
|
||||
"dsh",
|
||||
"deepseek-harness",
|
||||
"dsh-plugin",
|
||||
"markmag",
|
||||
"sidaocai"
|
||||
],
|
||||
"license": "UNLICENSED"
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
// 把「四道菜团队模型」通道写进桌面版 DSH:改 profile patch + 写入凭据 ref。
|
||||
// key 从工作区 .local-credentials.json 读,不打印。
|
||||
import fs from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const HOME = homedir()
|
||||
const PROJ = join(HOME, 'Documents/Essay_AI/Essay_system/dsh-markmag')
|
||||
const patchPath = join(HOME, '.dsh/profiles/desktop/cordis.patch.yml')
|
||||
const credPath = join(HOME, '.dsh/.credentials.yaml')
|
||||
const STAMP = '20261107'
|
||||
|
||||
const cfg = JSON.parse(fs.readFileSync(join(PROJ, '.local-credentials.json'), 'utf8'))
|
||||
const key = cfg.key1
|
||||
if (!key || !key.startsWith('sk-mem-')) { console.error('NO_VALID_KEY'); process.exit(1) }
|
||||
|
||||
// 1. 备份
|
||||
const bak = patchPath + '.bak-' + STAMP
|
||||
if (!fs.existsSync(bak)) fs.copyFileSync(patchPath, bak)
|
||||
console.log('backup:', fs.existsSync(bak) ? 'ok' : 'FAIL')
|
||||
|
||||
// 2. profile patch:新增公司模型通道
|
||||
let patch = fs.readFileSync(patchPath, 'utf8')
|
||||
if (patch.includes('MARKMAG_TEAM_KEY')) {
|
||||
console.log('patch: already present, skip')
|
||||
} else {
|
||||
patch += [
|
||||
'',
|
||||
'# 四道菜团队模型通道:走公司网关(TDB 记忆代理),key 由凭据 MARKMAG_TEAM_KEY 提供',
|
||||
'- id: llm-deepseek',
|
||||
' name: "@deepseek-ai/dsh-llm-deepseek-api-key"',
|
||||
' config:',
|
||||
' baseURL: https://brain.sidaocai.cn/tdb-api/claude-code/default',
|
||||
' apiKeyEnv: MARKMAG_TEAM_KEY',
|
||||
'',
|
||||
].join('\n')
|
||||
fs.writeFileSync(patchPath, patch)
|
||||
console.log('patch: appended')
|
||||
}
|
||||
|
||||
// 3. 凭据 ref:MARKMAG_TEAM_KEY
|
||||
let cred = fs.readFileSync(credPath, 'utf8')
|
||||
if (cred.includes('MARKMAG_TEAM_KEY')) {
|
||||
console.log('credential: already present, skip')
|
||||
} else {
|
||||
if (!/^refs:\s*$/m.test(cred)) { console.error('CRED_NO_REFS_SECTION'); process.exit(1) }
|
||||
cred = cred.replace(/^refs:\s*$/m, 'refs:\n MARKMAG_TEAM_KEY: ' + key)
|
||||
fs.writeFileSync(credPath, cred, { mode: 0o600 })
|
||||
console.log('credential: added, perms=', (fs.statSync(credPath).mode & 0o777).toString(8))
|
||||
}
|
||||
|
||||
// 4. 自检(不打印密钥值)
|
||||
const patch2 = fs.readFileSync(patchPath, 'utf8')
|
||||
const cred2 = fs.readFileSync(credPath, 'utf8')
|
||||
const out = {
|
||||
patchHasBaseURL: patch2.includes('brain.sidaocai.cn/tdb-api/claude-code/default'),
|
||||
patchHasApiKeyEnv: patch2.includes('apiKeyEnv: MARKMAG_TEAM_KEY'),
|
||||
patchYamlEntries: (patch2.match(/^- /gm) || []).length,
|
||||
credHasRef: /^\s+MARKMAG_TEAM_KEY:\s*sk-mem-/m.test(cred2),
|
||||
credRefsLineOk: /^refs:\s*$/m.test(cred2),
|
||||
}
|
||||
console.log('SELF_CHECK', JSON.stringify(out))
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 给弹匣加「DSH 接入」四处改动(本地源码)。
|
||||
*
|
||||
* 1. GET /markmag/api/dsh/link 浏览器打开 → 显示一次性码
|
||||
* 2. POST /api/dsh/link-exchange 桌面端拿码 → 换回成员 key + 工具凭证
|
||||
* 3. POST /api/dsh/tool 桌面端调 4 个工具(凭证自验,不走会话门)
|
||||
* 4. do_POST 会话门放行 2、3 它们天生不能要求登录,靠码/凭证+限流自保
|
||||
*
|
||||
* 幂等:已经改过就跳过。改之前备份。只改本地源码,线上要另跑部署。
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const HOME = homedir()
|
||||
const SRC = join(HOME, 'Documents/Essay_AI/Essay_system/dsh-markmag')
|
||||
const SRV = join(HOME, 'markmag/server')
|
||||
const MAIN = join(SRV, 'main.py')
|
||||
const MOD = join(SRV, 'sources/dsh_link.py')
|
||||
const STAMP = '20261107-dsh'
|
||||
|
||||
const log = (k, v) => console.log(k.padEnd(16), v)
|
||||
const die = (m) => { console.error('✗ ' + m); process.exit(1) }
|
||||
|
||||
if (!fs.existsSync(MAIN)) die('没找到 ' + MAIN)
|
||||
|
||||
const bak = MAIN + '.bak-' + STAMP
|
||||
if (!fs.existsSync(bak)) fs.copyFileSync(MAIN, bak)
|
||||
log('backup:', fs.existsSync(bak) ? 'ok' : 'FAIL')
|
||||
|
||||
fs.copyFileSync(join(SRC, 'deploy/markmag/dsh_link.py'), MOD)
|
||||
fs.copyFileSync(join(SRC, 'deploy/markmag/dsh_revoke.py'), join(SRV, 'sources/dsh_revoke.py'))
|
||||
log('module:', fs.existsSync(MOD) ? 'dsh_link.py + dsh_revoke.py' : 'FAIL')
|
||||
|
||||
let src = fs.readFileSync(MAIN, 'utf8')
|
||||
const before = src
|
||||
|
||||
// ── patch 1:GET 页面 ─────────────────────────────────────
|
||||
const GET_ANCHOR = ' # 默认拒绝(server 实例):API → 401 JSON;页面 → 302 引导登录页'
|
||||
const GET_BLOCK = [
|
||||
' if path == "api/dsh/link": # 11-07 DSH 接入码:浏览器打开显示一次性码',
|
||||
' s = self._sess()',
|
||||
' if not s:',
|
||||
' self.send_response(302)',
|
||||
' self.send_header("Location", "/markmag/auth/callback.html")',
|
||||
' self.send_header("Content-Length", "0")',
|
||||
' self.end_headers()',
|
||||
' return',
|
||||
' import sources.dsh_link as DL',
|
||||
' r = DL.issue(s)',
|
||||
' if not r.get("ok"):',
|
||||
' self._send(400, r)',
|
||||
' return',
|
||||
' self._send(200, DL.page_html(r["code"], r["expires_in"]).encode("utf-8"),',
|
||||
' "text/html; charset=utf-8")',
|
||||
' return',
|
||||
'',
|
||||
'',
|
||||
].join('\n')
|
||||
if (src.includes('if path == "api/dsh/link":')) {
|
||||
log('get route:', 'skip')
|
||||
} else {
|
||||
if (!src.includes(GET_ANCHOR)) die('GET 锚点没找到')
|
||||
src = src.replace(GET_ANCHOR, GET_BLOCK + GET_ANCHOR)
|
||||
log('get route:', 'added')
|
||||
}
|
||||
|
||||
// ── patch 2:POST 兑换 ────────────────────────────────────
|
||||
const POST_ANCHOR = ' elif path == "api/agent/token" and self.command == "POST":'
|
||||
const POST_BLOCK = [
|
||||
' elif path == "api/dsh/link-exchange" and self.command == "POST": # 11-07 桌面端拿码换成员 key',
|
||||
' import sources.dsh_link as DL',
|
||||
' r = DL.redeem(body.get("code", ""))',
|
||||
' self._send(200 if r.get("ok") else 400, r)',
|
||||
].join('\n')
|
||||
if (src.includes('elif path == "api/dsh/link-exchange"')) {
|
||||
log('post route:', 'skip')
|
||||
} else {
|
||||
if (!src.includes(POST_ANCHOR)) die('POST 锚点没找到')
|
||||
src = src.replace(POST_ANCHOR, POST_BLOCK + '\n' + POST_ANCHOR)
|
||||
log('post route:', 'added')
|
||||
}
|
||||
|
||||
// ── patch 3:POST 工具面 ──────────────────────────────────
|
||||
const TOOL_BLOCK = [
|
||||
' elif path == "api/dsh/tool" and self.command == "POST": # 11-07 DSH 工具面:凭证自验,不走会话门',
|
||||
' import sources.dsh_link as DL',
|
||||
' r = DL.dispatch(self.headers.get("X-MarkMag-Token", ""), body.get("tool", ""), body.get("args") or {})',
|
||||
' self._send(200 if r.get("ok") else 401, r)',
|
||||
].join('\n')
|
||||
if (src.includes('elif path == "api/dsh/tool"')) {
|
||||
log('tool route:', 'skip')
|
||||
} else {
|
||||
if (!src.includes(POST_ANCHOR)) die('POST 锚点没找到(工具面)')
|
||||
src = src.replace(POST_ANCHOR, TOOL_BLOCK + '\n' + POST_ANCHOR)
|
||||
log('tool route:', 'added')
|
||||
}
|
||||
|
||||
// ── patch 4:会话门放行两条自证路径 ───────────────────────
|
||||
const GATE_RE = /^(\s+)if not config\.PRIVATE_ENABLED and path .*not self\._sess\(\):$/m
|
||||
const GATE_WANT = 'if not config.PRIVATE_ENABLED and path not in ("api/auth/dingtalk/login", "api/dsh/link-exchange", "api/dsh/tool") and not self._sess():'
|
||||
if (src.includes('"api/dsh/tool")')) {
|
||||
log('session gate:', 'skip')
|
||||
} else if (!GATE_RE.test(src)) {
|
||||
die('会话门那行没找到,main.py 结构和预期不符')
|
||||
} else {
|
||||
src = src.replace(GATE_RE, (m, indent) => indent + GATE_WANT)
|
||||
log('session gate:', 'opened for exchange + tool')
|
||||
}
|
||||
|
||||
// ── patch 5:成员停用即吊销 key + 手动吊销端点 ────────────
|
||||
const SETACTIVE_OLD = [
|
||||
' elif path == "api/admin/members/set-active" and self.command == "POST":',
|
||||
' if not self._admin():',
|
||||
' return self._send(403, {"err": "forbidden"})',
|
||||
' import sources.members_store as M',
|
||||
' ok = M.set_active(body.get("union_id"), bool(body.get("active")))',
|
||||
' self._send(200 if ok else 404, {"ok": ok})',
|
||||
].join('\n')
|
||||
const SETACTIVE_NEW = [
|
||||
' elif path == "api/admin/members/set-active" and self.command == "POST":',
|
||||
' if not self._admin():',
|
||||
' return self._send(403, {"err": "forbidden"})',
|
||||
' import sources.members_store as M',
|
||||
' uid_x = body.get("union_id")',
|
||||
' want_on = bool(body.get("active"))',
|
||||
' ok = M.set_active(uid_x, want_on)',
|
||||
' extra = {}',
|
||||
' if ok and not want_on: # 11-07 停用即吊销他名下全部 TDB key(离职即断)',
|
||||
' import sources.dsh_revoke as RV',
|
||||
' extra["keys"] = RV.revoke_member_keys(uid_x)',
|
||||
' self._send(200 if ok else 404, {"ok": ok, **extra})',
|
||||
' elif path == "api/admin/members/revoke-keys" and self.command == "POST": # 11-07 手动吊销(补漏用)',
|
||||
' if not self._admin():',
|
||||
' return self._send(403, {"err": "forbidden"})',
|
||||
' import sources.dsh_revoke as RV',
|
||||
' self._send(200, RV.revoke_member_keys(body.get("union_id")))',
|
||||
' elif path == "api/admin/members/key-status" and self.command == "POST": # 11-07 只看现状,不动数据',
|
||||
' if not self._admin():',
|
||||
' return self._send(403, {"err": "forbidden"})',
|
||||
' import sources.dsh_revoke as RV',
|
||||
' self._send(200, RV.revoke_status(body.get("union_id")))',
|
||||
].join('\n')
|
||||
if (src.includes('api/admin/members/revoke-keys')) {
|
||||
log('revoke hook:', 'skip')
|
||||
} else if (!src.includes(SETACTIVE_OLD)) {
|
||||
die('set-active 端点结构和预期不符,不敢改')
|
||||
} else {
|
||||
src = src.replace(SETACTIVE_OLD, SETACTIVE_NEW)
|
||||
log('revoke hook:', 'wired into set-active')
|
||||
}
|
||||
|
||||
if (src !== before) fs.writeFileSync(MAIN, src)
|
||||
|
||||
// ── 自检 ──────────────────────────────────────────────────
|
||||
const after = fs.readFileSync(MAIN, 'utf8')
|
||||
const checks = {
|
||||
getRoute: after.includes('if path == "api/dsh/link":'),
|
||||
exchangeRoute: after.includes('elif path == "api/dsh/link-exchange"'),
|
||||
toolRoute: after.includes('elif path == "api/dsh/tool"'),
|
||||
gateOpen: after.includes('"api/dsh/tool")'),
|
||||
moduleExists: fs.existsSync(MOD),
|
||||
toolTokenInModule: fs.readFileSync(MOD, 'utf8').includes('issue_tool_token'),
|
||||
revokeWired: after.includes('RV.revoke_member_keys(uid_x)'),
|
||||
revokeModule: fs.existsSync(join(SRV, 'sources/dsh_revoke.py')),
|
||||
}
|
||||
log('SELF_CHECK', JSON.stringify(checks))
|
||||
if (!Object.values(checks).every(Boolean)) {
|
||||
console.log('\n✗ 自检没过,用备份回滚:' + bak)
|
||||
process.exit(1)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env node
|
||||
// 幂等:把「四道菜团队模型」通道写进桌面版 DSH profile,列出网关实际支持的模型。
|
||||
import fs from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const HOME = homedir()
|
||||
const PROJ = join(HOME, 'Documents/Essay_AI/Essay_system/dsh-markmag')
|
||||
const patchPath = join(HOME, '.dsh/profiles/desktop/cordis.patch.yml')
|
||||
const STAMP = '20261107'
|
||||
|
||||
const BLOCK = [
|
||||
'# 四道菜团队模型通道:走公司网关(TDB 记忆代理),key 由凭据 MARKMAG_TEAM_KEY 提供',
|
||||
'- id: llm-deepseek',
|
||||
' name: "@deepseek-ai/dsh-llm-deepseek-api-key"',
|
||||
' config:',
|
||||
' baseURL: https://brain.sidaocai.cn/tdb-api/claude-code/default',
|
||||
' apiKeyEnv: MARKMAG_TEAM_KEY',
|
||||
' models:',
|
||||
' - id: glm-5.3',
|
||||
' name: GLM-5.3',
|
||||
' contextWindow: 128000',
|
||||
' maxTokens: 8192',
|
||||
' - id: glm-5.3-flash',
|
||||
' name: GLM-5.3-Flash',
|
||||
' contextWindow: 128000',
|
||||
' maxTokens: 8192',
|
||||
].join('\n')
|
||||
|
||||
// 备份
|
||||
const bak = patchPath + '.bak-' + STAMP + '-2'
|
||||
if (!fs.existsSync(bak)) fs.copyFileSync(patchPath, bak)
|
||||
console.log('backup:', fs.existsSync(bak) ? 'ok' : 'FAIL')
|
||||
|
||||
let patch = fs.readFileSync(patchPath, 'utf8')
|
||||
const MARK = '# 四道菜团队模型通道'
|
||||
const idx = patch.indexOf(MARK)
|
||||
if (idx >= 0) {
|
||||
patch = patch.slice(0, idx).trimEnd() + '\n' + BLOCK + '\n'
|
||||
console.log('patch: replaced existing block')
|
||||
} else {
|
||||
patch = patch.trimEnd() + '\n\n' + BLOCK + '\n'
|
||||
console.log('patch: appended')
|
||||
}
|
||||
fs.writeFileSync(patchPath, patch)
|
||||
|
||||
// 自检
|
||||
const out = fs.readFileSync(patchPath, 'utf8')
|
||||
const checks = {
|
||||
baseURL: out.includes('brain.sidaocai.cn/tdb-api/claude-code/default'),
|
||||
apiKeyEnv: out.includes('apiKeyEnv: MARKMAG_TEAM_KEY'),
|
||||
hasGlm: out.includes('id: glm-5.3') && out.includes('id: glm-5.3-flash'),
|
||||
noDupBlock: (out.match(/四道菜团队模型通道/g) || []).length === 1,
|
||||
yamlTopLevelEntries: (out.match(/^- /gm) || []).length,
|
||||
}
|
||||
console.log('SELF_CHECK', JSON.stringify(checks))
|
||||
console.log('--- 追加块 ---')
|
||||
console.log(BLOCK)
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env node
|
||||
/** 把 panel.css + panel.template.js 合成 dist/client.js(客户端半片)。 */
|
||||
import fs from "node:fs"
|
||||
import { homedir } from "node:os"
|
||||
import { join, dirname } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const root = join(here, "..")
|
||||
const css = fs.readFileSync(join(root, "src/panel/panel.css"), "utf8")
|
||||
let tpl = fs.readFileSync(join(root, "src/panel/panel.template.js"), "utf8")
|
||||
if (!tpl.includes("__CSS_JSON__")) {
|
||||
console.error("模板里没有 __CSS_JSON__ 占位,拒绝生成")
|
||||
process.exit(1)
|
||||
}
|
||||
tpl = tpl.replace("__CSS_JSON__", JSON.stringify(css))
|
||||
fs.mkdirSync(join(root, "dist"), { recursive: true })
|
||||
fs.writeFileSync(join(root, "dist/client.js"), tpl)
|
||||
const kb = (fs.statSync(join(root, "dist/client.js")).size / 1024).toFixed(1)
|
||||
console.log("built dist/client.js " + kb + " KB (css " + css.split("\n").length + " 行)")
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 把 @sidaocai/dsh-markmag 装进桌面版 DSH 的 profile。
|
||||
*
|
||||
* 为什么手工做:桌面版 profile 由 Electron 拥有,npm 的 dsh CLI 管不了它,
|
||||
* 所以直接按它认的结构摆文件 —— 包进 node_modules + 名字进 bundles。
|
||||
*
|
||||
* 幂等:跑几次结果一样。改任何文件前先备份。会顺手清掉旧包名(dsh-markmag)的残留。
|
||||
*/
|
||||
import fs from "node:fs"
|
||||
import { homedir } from "node:os"
|
||||
import { join, dirname } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
const HOME = homedir()
|
||||
const PLUGIN = "@sidaocai/dsh-markmag"
|
||||
const LEGACY = "dsh-markmag"
|
||||
const PROFILE = join(HOME, ".dsh/profiles/desktop")
|
||||
const PKG = join(PROFILE, "package.json")
|
||||
const PATCH = join(PROFILE, "cordis.patch.yml")
|
||||
const DEST = join(PROFILE, "node_modules", PLUGIN)
|
||||
const STAMP = "20261107-plugin"
|
||||
const SRC = join(dirname(fileURLToPath(import.meta.url)), "..")
|
||||
|
||||
const log = (k, v) => console.log(k.padEnd(16), v)
|
||||
const die = (m) => { console.error("✗ " + m); process.exit(1) }
|
||||
|
||||
if (!fs.existsSync(PKG)) die("没找到桌面版 profile:" + PKG)
|
||||
|
||||
// 1. 备份
|
||||
for (const f of [PKG, PATCH]) {
|
||||
if (!fs.existsSync(f)) continue
|
||||
const bak = f + ".bak-" + STAMP
|
||||
if (!fs.existsSync(bak)) fs.copyFileSync(f, bak)
|
||||
}
|
||||
log("backup:", fs.existsSync(PKG + ".bak-" + STAMP) ? "ok" : "FAIL")
|
||||
|
||||
// 2. 清旧包名残留
|
||||
const legacyDir = join(PROFILE, "node_modules", LEGACY)
|
||||
if (fs.existsSync(legacyDir)) {
|
||||
fs.rmSync(legacyDir, { recursive: true, force: true })
|
||||
log("legacy:", "已移除 node_modules/" + LEGACY)
|
||||
}
|
||||
|
||||
// 3. 摆包
|
||||
fs.rmSync(DEST, { recursive: true, force: true })
|
||||
fs.mkdirSync(DEST, { recursive: true })
|
||||
for (const item of ["package.json", "cordis.patch.yml", "src", "dist", "README.md", "LICENSE", "CHANGELOG.md"]) {
|
||||
const from = join(SRC, item)
|
||||
if (fs.existsSync(from)) fs.cpSync(from, join(DEST, item), { recursive: true })
|
||||
}
|
||||
log("plugin:", fs.existsSync(join(DEST, "src/host.js")) ? "installed" : "FAIL")
|
||||
|
||||
// 4. 登记进 profile
|
||||
const pkg = JSON.parse(fs.readFileSync(PKG, "utf8"))
|
||||
pkg.dsh ??= {}
|
||||
pkg.dsh.profile ??= {}
|
||||
pkg.dsh.profile.bundles = (pkg.dsh.profile.bundles || []).filter((b) => b !== LEGACY)
|
||||
if (!pkg.dsh.profile.bundles.includes(PLUGIN)) pkg.dsh.profile.bundles.push(PLUGIN)
|
||||
pkg.dependencies ??= {}
|
||||
delete pkg.dependencies[LEGACY]
|
||||
pkg.dependencies[PLUGIN] = "file:" + SRC
|
||||
fs.writeFileSync(PKG, JSON.stringify(pkg, null, 2) + "\n")
|
||||
log("bundles:", PLUGIN)
|
||||
|
||||
// 5. 摘掉历史手工段
|
||||
let patch = fs.existsSync(PATCH) ? fs.readFileSync(PATCH, "utf8") : ""
|
||||
const MARK = "# 四道菜团队模型通道"
|
||||
const at = patch.indexOf(MARK)
|
||||
if (at >= 0) {
|
||||
patch = patch.slice(0, at).trimEnd() + "\n"
|
||||
fs.writeFileSync(PATCH, patch)
|
||||
log("manual block:", "removed")
|
||||
} else log("manual block:", "none")
|
||||
|
||||
// 6. 自检
|
||||
const bundlePatch = fs.readFileSync(join(DEST, "cordis.patch.yml"), "utf8")
|
||||
const checks = {
|
||||
bundleListed: JSON.parse(fs.readFileSync(PKG, "utf8")).dsh.profile.bundles.includes(PLUGIN),
|
||||
hostExists: fs.existsSync(join(DEST, "src/host.js")),
|
||||
clientExists: fs.existsSync(join(DEST, "dist/client.js")),
|
||||
patchHasGateway: bundlePatch.includes("brain.sidaocai.cn/tdb-api/claude-code/default"),
|
||||
patchHasGlm: bundlePatch.includes("glm-5.3-flash"),
|
||||
hostInserted: bundlePatch.includes("@sidaocai/dsh-markmag"),
|
||||
noLegacy: !fs.readdirSync(join(PROFILE, "node_modules")).includes(LEGACY),
|
||||
}
|
||||
log("SELF_CHECK", JSON.stringify(checks))
|
||||
if (!Object.values(checks).every(Boolean)) {
|
||||
console.log("\n✗ 自检没过,用备份回滚:" + PKG + ".bak-" + STAMP)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log("\n重启桌面版 DSH 生效。")
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 用一次性接入码换你的团队模型 key,写进 DSH 凭据(MARKMAG_TEAM_KEY)。
|
||||
*
|
||||
* 用法:
|
||||
* 1. 浏览器打开 https://brain.sidaocai.cn/markmag/api/dsh/link (已登录弹匣)
|
||||
* 2. 页面上有个 6 位码
|
||||
* 3. node ~/Documents/Essay_AI/Essay_system/dsh-markmag/scripts/login.mjs ABC123
|
||||
*
|
||||
* key 全程不打印、不落盘(除了 DSH 自己的凭据文件,权限 600)。
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const MARKMAG = 'https://brain.sidaocai.cn/markmag'
|
||||
const CRED_PATH = join(homedir(), '.dsh/.credentials.yaml')
|
||||
const REF = 'MARKMAG_TEAM_KEY'
|
||||
|
||||
const code = (process.argv[2] || '').trim().toUpperCase()
|
||||
if (!/^[A-Z0-9]{8}$/.test(code)) {
|
||||
console.error('用法: node login.mjs <8位接入码>')
|
||||
console.error(' 接入码在 https://brain.sidaocai.cn/markmag/api/dsh/link 看(需先登录弹匣)')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// ── 1. 换 key ─────────────────────────────────────────────
|
||||
let data
|
||||
try {
|
||||
const res = await fetch(MARKMAG + '/api/dsh/link-exchange', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ code }),
|
||||
signal: AbortSignal.timeout(20000),
|
||||
})
|
||||
data = await res.json()
|
||||
} catch (e) {
|
||||
console.error('✗ 连不上弹匣:' + (e.name === 'TimeoutError' ? '超时' : e.message))
|
||||
process.exit(1)
|
||||
}
|
||||
if (!data.ok) {
|
||||
console.error('✗ ' + (data.err || '换 key 失败'))
|
||||
process.exit(1)
|
||||
}
|
||||
const key = data.user_key || ''
|
||||
if (!key.startsWith('sk-mem-')) {
|
||||
console.error('✗ 返回的 key 形状不对,拒绝写入')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// ── 2. 写进 DSH 凭据 ─────────────────────────────────────
|
||||
if (!fs.existsSync(CRED_PATH)) {
|
||||
console.error('✗ 没找到 ' + CRED_PATH + '(DSH 至少启动过一次才会生成)')
|
||||
process.exit(1)
|
||||
}
|
||||
const bak = CRED_PATH + '.bak-' + Date.now()
|
||||
fs.copyFileSync(CRED_PATH, bak)
|
||||
|
||||
let cred = fs.readFileSync(CRED_PATH, 'utf8')
|
||||
const line = /^(\s+)MARKMAG_TEAM_KEY:\s*.*$/m
|
||||
if (line.test(cred)) {
|
||||
cred = cred.replace(line, '$1' + REF + ': ' + key)
|
||||
} else if (/^refs:\s*$/m.test(cred)) {
|
||||
cred = cred.replace(/^refs:\s*$/m, 'refs:\n ' + REF + ': ' + key)
|
||||
} else {
|
||||
cred = cred.trimEnd() + '\nrefs:\n ' + REF + ': ' + key + '\n'
|
||||
}
|
||||
fs.writeFileSync(CRED_PATH, cred, { mode: 0o600 })
|
||||
|
||||
// ── 3. 自检(只看形状,不打印值)──────────────────────────
|
||||
const after = fs.readFileSync(CRED_PATH, 'utf8')
|
||||
const out = {
|
||||
refWritten: new RegExp('^\\s+' + REF + ':\\s*sk-mem-', 'm').test(after),
|
||||
perms: (fs.statSync(CRED_PATH).mode & 0o777).toString(8),
|
||||
model: data.model || '(未返回)',
|
||||
member: data.name || '(未返回)',
|
||||
backup: bak.endsWith('.yaml') ? '-' : 'ok',
|
||||
}
|
||||
console.log('SELF_CHECK', JSON.stringify(out))
|
||||
console.log('\n好了,' + (out.member || '你') + ' 的团队通道已就位。重启 DSH 或直接开新会话。')
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 发布前检查(npm publish 会自动跑)。任何一项不过就中止。
|
||||
* 目的:不靠人记住,靠脚本拦。
|
||||
*/
|
||||
import fs from "node:fs"
|
||||
import { join, dirname } from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..")
|
||||
const pkg = JSON.parse(fs.readFileSync(join(ROOT, "package.json"), "utf8"))
|
||||
const fail = []
|
||||
const ok = []
|
||||
|
||||
// 1. 必填元数据
|
||||
if (!pkg.name.startsWith("@")) fail.push("包名没加 scope(应为 @sidaocai/dsh-markmag)")
|
||||
else ok.push("包名带 scope")
|
||||
if (pkg.private) fail.push("package.json 里 private=true,发不出去")
|
||||
else ok.push("未设 private")
|
||||
if (!pkg.publishConfig || !pkg.publishConfig.registry) fail.push("缺 publishConfig.registry,可能误发到公共 npm")
|
||||
else ok.push("发布目标已锁定私有源")
|
||||
|
||||
// 2. 敏感文件不能进包
|
||||
const forbidden = [".local-credentials.json", ".env", "credentials.json"]
|
||||
for (const f of forbidden) {
|
||||
if (fs.existsSync(join(ROOT, f))) fail.push("项目根存在敏感文件:" + f)
|
||||
}
|
||||
if (!fail.length) ok.push("项目根无已知敏感文件")
|
||||
|
||||
// 3. files 白名单不能含敏感目录
|
||||
const files = pkg.files || []
|
||||
for (const bad of ["scripts", "deploy", "docs", "node_modules"]) {
|
||||
if (files.includes(bad)) fail.push("files 白名单含 " + bad + "(不该发布)")
|
||||
}
|
||||
if (!fail.length) ok.push("files 白名单干净")
|
||||
|
||||
// 4. 产物必须存在且比源码新
|
||||
const client = join(ROOT, "dist/client.js")
|
||||
if (!fs.existsSync(client)) fail.push("缺 dist/client.js,先跑 build")
|
||||
else {
|
||||
const ct = fs.statSync(client).mtimeMs
|
||||
const srcs = [join(ROOT, "src/panel/panel.css"), join(ROOT, "src/panel/panel.template.js")]
|
||||
for (const s of srcs) {
|
||||
if (fs.existsSync(s) && fs.statSync(s).mtimeMs > ct) {
|
||||
fail.push("dist/client.js 比 " + s.split("/").slice(-1)[0] + " 旧,先跑 build")
|
||||
}
|
||||
}
|
||||
ok.push("产物存在且是最新")
|
||||
}
|
||||
|
||||
// 5. 版本必须记进 CHANGELOG
|
||||
const cl = fs.existsSync(join(ROOT, "CHANGELOG.md")) ? fs.readFileSync(join(ROOT, "CHANGELOG.md"), "utf8") : ""
|
||||
if (!cl.includes(pkg.version)) fail.push("CHANGELOG 里没有 " + pkg.version + " 的记录")
|
||||
else ok.push("CHANGELOG 已记录该版本")
|
||||
|
||||
console.log("发布前检查:" + pkg.name + "@" + pkg.version)
|
||||
for (const o of ok) console.log(" ✓ " + o)
|
||||
if (fail.length) {
|
||||
console.log()
|
||||
for (const f of fail) console.log(" ✗ " + f)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log("\n通过。")
|
||||
@@ -0,0 +1,22 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
const cfg = JSON.parse(readFileSync(join(homedir(), 'Documents/Essay_AI/Essay_system/dsh-markmag/.local-credentials.json'), 'utf8'))
|
||||
const key = cfg.key1
|
||||
const url = 'https://brain.sidaocai.cn/tdb-api/claude-code/default/v1/messages'
|
||||
const candidates = ['glm-5.3', 'glm-5.3-flash', 'glm-5.3-flashx', 'deepseek-v4-pro', 'deepseek-flash', 'deepseek-chat', 'deepseek-v3', 'kimi-k2', 'qwen3-max']
|
||||
for (const model of candidates) {
|
||||
const t0 = Date.now()
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01' },
|
||||
body: JSON.stringify({ model, max_tokens: 8, messages: [{ role: 'user', content: 'hi' }] }),
|
||||
signal: AbortSignal.timeout(30000),
|
||||
})
|
||||
const text = await res.text()
|
||||
const ok = res.status === 200
|
||||
const brief = ok ? 'OK' : (() => { try { const j = JSON.parse(text); return (j.error?.code || '') + ' ' + (j.error?.message || '').slice(0, 60) } catch { return text.slice(0, 60) } })()
|
||||
console.log((ok ? '✅' : '❌'), model.padEnd(16), res.status, (Date.now() - t0) + 'ms', brief)
|
||||
} catch (e) { console.log('❌', model.padEnd(16), 'FAIL', e.name) }
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 一条命令接通「你的个人 key」:改弹匣 → 部署 → 取码 → 写进 DSH 凭据。
|
||||
*
|
||||
* node ~/Documents/Essay_AI/Essay_system/dsh-markmag/scripts/setup-account.mjs
|
||||
*
|
||||
* 中间只需要做一件事:把浏览器页面上的 6 位码粘进来。
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { execFileSync, execSync } from 'node:child_process'
|
||||
import { createInterface } from 'node:readline/promises'
|
||||
|
||||
const HOME = homedir()
|
||||
const PROJ = join(HOME, 'Documents/Essay_AI/Essay_system/dsh-markmag')
|
||||
const CRED = join(HOME, '.dsh/.credentials.yaml')
|
||||
const MARKMAG = 'https://brain.sidaocai.cn/markmag'
|
||||
const LINK_PAGE = MARKMAG + '/api/dsh/link'
|
||||
const REF = 'MARKMAG_TEAM_KEY'
|
||||
const step = (n, t) => console.log('\n[' + n + '] ' + t)
|
||||
|
||||
const rl = createInterface({ input: process.stdin, output: process.stdout })
|
||||
|
||||
console.log('这一步会做三件事:')
|
||||
console.log(' 1. 给弹匣源码加一个「接入码」页面(改本地文件,自动备份)')
|
||||
console.log(' 2. 部署到线上 —— 弹匣服务会重启约 3 秒')
|
||||
console.log(' 3. 打开浏览器取码,你粘回来,key 自动写进 DSH')
|
||||
const go = (await rl.question('\n继续吗?(y/N) ')).trim().toLowerCase()
|
||||
if (go !== 'y' && go !== 'yes') {
|
||||
console.log('已取消。')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// ── 1. 更新插件 + 改弹匣源码 ──────────────────────────────
|
||||
step('1/4', '更新 DSH 插件 + 给弹匣加接入入口')
|
||||
try {
|
||||
const out1 = execFileSync('node', [join(PROJ, 'scripts/install.mjs')], { encoding: 'utf8' })
|
||||
console.log('插件 ' + (out1.includes('"hostExists":true') ? 'ok' : out1.trim().split('\n').slice(-1)[0]))
|
||||
const out2 = execFileSync('node', [join(PROJ, 'scripts/apply-markmag-dsh.mjs')], { encoding: 'utf8' })
|
||||
const m = out2.match(/SELF_CHECK\s+(\{.*\})/)
|
||||
console.log('弹匣 ' + (m ? m[1] : 'ok'))
|
||||
} catch (e) {
|
||||
console.error('✗ 准备失败:' + ((e.stdout || '') + (e.message || '')).slice(-200))
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// ── 2. 部署 ───────────────────────────────────────────────
|
||||
step('2/4', '部署到线上(服务重启约 3 秒)')
|
||||
try {
|
||||
const out = execSync('bash ' + join(HOME, 'markmag/deploy/rsync.sh'), { encoding: 'utf8', stdio: 'pipe' })
|
||||
const tail = out.trim().split('\n').filter(Boolean).slice(-3).join(' · ')
|
||||
console.log('✓ ' + tail)
|
||||
} catch (e) {
|
||||
console.error('✗ 部署失败:' + ((e.stderr || '') + (e.stdout || '')).slice(-300))
|
||||
console.log(' 本地源码已改好,部署可以稍后单独跑:bash ~/markmag/deploy/rsync.sh')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// ── 3. 打开浏览器取码 ─────────────────────────────────────
|
||||
step('3/4', '打开浏览器取码')
|
||||
try {
|
||||
execSync('open "' + LINK_PAGE + '"')
|
||||
console.log('浏览器已打开(没登录会先跳钉钉登录,登完再开一次)')
|
||||
} catch {
|
||||
console.log('请手动打开:' + LINK_PAGE)
|
||||
}
|
||||
|
||||
const code = (await rl.question('\n把页面上的 8 位码粘进来:')).trim().toUpperCase()
|
||||
rl.close()
|
||||
if (!/^[A-Z0-9]{8}$/.test(code)) {
|
||||
console.error('✗ 码格式不对(应该 8 位字母数字)')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// ── 4. 换 key 写凭据 ─────────────────────────────────────
|
||||
step('4/4', '换 key 并写入 DSH')
|
||||
let data
|
||||
try {
|
||||
const res = await fetch(MARKMAG + '/api/dsh/link-exchange', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ code }),
|
||||
signal: AbortSignal.timeout(20000),
|
||||
})
|
||||
data = await res.json()
|
||||
} catch (e) {
|
||||
console.error('✗ 连不上弹匣:' + (e.name === 'TimeoutError' ? '超时' : e.message))
|
||||
process.exit(1)
|
||||
}
|
||||
if (!data.ok) {
|
||||
console.error('✗ ' + (data.err || '换 key 失败') + '(码 5 分钟过期,重新打开页面取一个)')
|
||||
process.exit(1)
|
||||
}
|
||||
const key = data.user_key || ''
|
||||
if (!key.startsWith('sk-mem-')) {
|
||||
console.error('✗ 返回的 key 形状不对,拒绝写入')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (!fs.existsSync(CRED)) {
|
||||
console.error('✗ 没找到 ' + CRED + '(DSH 至少启动过一次才会生成)')
|
||||
process.exit(1)
|
||||
}
|
||||
fs.copyFileSync(CRED, CRED + '.bak-' + Date.now())
|
||||
|
||||
// 写一条凭据(已存在则替换值)
|
||||
function setCred(text, name, value) {
|
||||
const re = new RegExp('^(\\s+)' + name + ':\\s*.*$', 'm')
|
||||
if (re.test(text)) return text.replace(re, '$1' + name + ': ' + value)
|
||||
if (/^refs:\s*$/m.test(text)) return text.replace(/^refs:\s*$/m, 'refs:\n ' + name + ': ' + value)
|
||||
return text.trimEnd() + '\nrefs:\n ' + name + ': ' + value + '\n'
|
||||
}
|
||||
|
||||
let cred = fs.readFileSync(CRED, 'utf8')
|
||||
cred = setCred(cred, REF, key)
|
||||
const toolToken = data.tool_token || ''
|
||||
if (toolToken) cred = setCred(cred, 'MARKMAG_TOOL_TOKEN', toolToken)
|
||||
fs.writeFileSync(CRED, cred, { mode: 0o600 })
|
||||
|
||||
const after = fs.readFileSync(CRED, 'utf8')
|
||||
const ok =
|
||||
new RegExp('^\\s+' + REF + ':\\s*sk-mem-', 'm').test(after) &&
|
||||
(!toolToken || /^\s+MARKMAG_TOOL_TOKEN:\s*\S+/m.test(after))
|
||||
console.log('\n' + (ok ? '✓ 完成' : '✗ 写入后自检失败') + ' ' + JSON.stringify({
|
||||
member: data.name || '?',
|
||||
model: data.model || '?',
|
||||
modelKey: true,
|
||||
toolToken: toolToken ? true : '未返回',
|
||||
perms: (fs.statSync(CRED).mode & 0o777).toString(8),
|
||||
}))
|
||||
console.log('\n以后不用再做这一步了。重启 DSH:模型通道 + 弹匣工具面都会就位。')
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env node
|
||||
// 验证:本人的 per-user key 能否过公司网关;DSH 链路(OpenAI 格式) 与 弹匣链路(Anthropic 格式) 是否都可用。
|
||||
// 只发最小请求(max_tokens=16),不打印任何 key。
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const cfgPath = join(homedir(), 'Documents/Essay_AI/Essay_system/dsh-markmag/.local-credentials.json')
|
||||
const cfg = JSON.parse(readFileSync(cfgPath, 'utf8'))
|
||||
const key = cfg.key2 || cfg.key1
|
||||
const BASE = 'https://brain.sidaocai.cn'
|
||||
|
||||
async function call(name, url, headers, body) {
|
||||
const t0 = Date.now()
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...headers },
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(40000),
|
||||
})
|
||||
const text = await res.text()
|
||||
const ms = Date.now() - t0
|
||||
console.log(`[${name}] status=${res.status} ${ms}ms`)
|
||||
console.log(' body:', text.slice(0, 400).replace(/\n/g, ' '))
|
||||
return res.status
|
||||
} catch (e) {
|
||||
console.log(`[${name}] FAIL ${Date.now() - t0}ms err=${e.name}: ${e.message}`)
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
console.log('key source: key2 =', Boolean(cfg.key2), ' key1 =', Boolean(cfg.key1))
|
||||
|
||||
// A. 弹匣链路:Anthropic messages
|
||||
await call('A-anthropic/claude-code', BASE + '/tdb-api/claude-code/default/v1/messages',
|
||||
{ 'x-api-key': key, 'anthropic-version': '2023-06-01' },
|
||||
{ model: 'deepseek-v4-pro', max_tokens: 16, messages: [{ role: 'user', content: 'ping' }] })
|
||||
|
||||
// B. DSH 链路:OpenAI chat/completions + 团队头
|
||||
await call('B-openai/dsh', BASE + '/tdb-api/dsh/default/chat/completions',
|
||||
{ authorization: 'Bearer ' + key, 'x-team-id': 'team-oek7kp1cy7', 'x-agent-id': 'agt-of5x44h7ns' },
|
||||
{ model: 'deepseek-v4-pro', max_tokens: 16, messages: [{ role: 'user', content: 'ping' }] })
|
||||
|
||||
// C. DSH 链路但不带头(看团队头是否必需)
|
||||
await call('C-openai/dsh-no-header', BASE + '/tdb-api/dsh/default/chat/completions',
|
||||
{ authorization: 'Bearer ' + key },
|
||||
{ model: 'deepseek-v4-pro', max_tokens: 16, messages: [{ role: 'user', content: 'ping' }] })
|
||||
|
||||
// D. 坏 key(确认鉴权是否真的在拦)
|
||||
await call('D-bad-key', BASE + '/tdb-api/dsh/default/chat/completions',
|
||||
{ authorization: 'Bearer sk-mem-INVALID_INVALID_INVALID' },
|
||||
{ model: 'deepseek-v4-pro', max_tokens: 16, messages: [{ role: 'user', content: 'ping' }] })
|
||||
@@ -0,0 +1,31 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
const cfg = JSON.parse(readFileSync(join(homedir(), 'Documents/Essay_AI/Essay_system/dsh-markmag/.local-credentials.json'), 'utf8'))
|
||||
const key = cfg.key1
|
||||
const BASE = 'https://brain.sidaocai.cn'
|
||||
|
||||
async function call(name, url, headers, body) {
|
||||
const t0 = Date.now()
|
||||
try {
|
||||
const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal: AbortSignal.timeout(60000) })
|
||||
const text = await res.text()
|
||||
console.log(`[${name}] ${res.status} ${Date.now() - t0}ms :: ${text.slice(0, 300).replace(/\n/g, ' ')}`)
|
||||
} catch (e) { console.log(`[${name}] FAIL ${e.name}: ${e.message}`) }
|
||||
}
|
||||
|
||||
const H_ANTH = { 'x-api-key': key, 'anthropic-version': '2023-06-01' }
|
||||
const H_OAUTH = { authorization: 'Bearer ' + key }
|
||||
|
||||
// A. 弹匣链路 + glm-5.3
|
||||
await call('A-anthropic/glm-5.3', BASE + '/tdb-api/claude-code/default/v1/messages', H_ANTH,
|
||||
{ model: 'glm-5.3', max_tokens: 32, messages: [{ role: 'user', content: '只回复两个字:在的' }] })
|
||||
|
||||
// B. DSH 链路 + 团队头 + glm-5.3
|
||||
await call('B-dsh/glm-5.3+headers', BASE + '/tdb-api/dsh/default/chat/completions',
|
||||
{ ...H_OAUTH, 'x-team-id': 'team-oek7kp1cy7', 'x-agent-id': 'agt-of5x44h7ns' },
|
||||
{ model: 'glm-5.3', max_tokens: 32, messages: [{ role: 'user', content: '只回复两个字:在的' }] })
|
||||
|
||||
// C. DSH 链路不带头
|
||||
await call('C-dsh/glm-5.3-no-header', BASE + '/tdb-api/dsh/default/chat/completions', H_OAUTH,
|
||||
{ model: 'glm-5.3', max_tokens: 32, messages: [{ role: 'user', content: '只回复两个字:在的' }] })
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* 四道菜团队中台 —— 宿主半片。
|
||||
*
|
||||
* 三件事:
|
||||
* 1. cordis.patch.yml 把模型通道指向公司网关(那份配置自己生效,不在这里管)
|
||||
* 2. MCP 工具面:弹匣的汇总/查任务/查项目/建任务,给 agent 用
|
||||
* 3. 本地面板接口:给侧边栏面板取数据(浏览器侧不碰凭证,只调这里)
|
||||
*
|
||||
* 面板取数的身份就是登录时那张工具凭证(MARKMAG_TOOL_TOKEN),所以打开面板
|
||||
* 不需要再登录一次弹匣。数据一律现取现给,不落地存储 —— 弹匣是唯一数据源,
|
||||
* 这里只是显示器(写入仍走弹匣同一套 API,规则判定全在弹匣侧)。
|
||||
*
|
||||
* 排查约定:产品 profile 没有控制台日志,每走一步都往
|
||||
* $DSH_HOME/markmag-plugin-state.json 写一行进展。
|
||||
*/
|
||||
import { writeFileSync, mkdirSync, readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
export const name = 'dsh-markmag'
|
||||
|
||||
// tools:MCP 客户端要靠这个服务把工具交给 agent 循环
|
||||
// webServer / connection:本地面板接口 + 请求准入
|
||||
export const inject = ['tools', 'webServer', 'connection']
|
||||
|
||||
const CREDENTIAL = 'MARKMAG_TEAM_KEY'
|
||||
const TOOL_CREDENTIAL = 'MARKMAG_TOOL_TOKEN'
|
||||
const MARKMAG_BASE = 'https://brain.sidaocai.cn/markmag'
|
||||
const STEPS = []
|
||||
|
||||
function stateFile() {
|
||||
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
||||
mkdirSync(home, { recursive: true })
|
||||
return join(home, 'markmag-plugin-state.json')
|
||||
}
|
||||
|
||||
function step(name, extra) {
|
||||
STEPS.push({ step: name, at: new Date().toISOString().slice(11, 19), ...(extra || {}) })
|
||||
try {
|
||||
writeFileSync(stateFile(), JSON.stringify({ updatedAt: new Date().toISOString(), pid: process.pid, steps: STEPS }, null, 1))
|
||||
} catch {
|
||||
// 状态文件写不了不影响功能
|
||||
}
|
||||
}
|
||||
|
||||
/** 工具凭证:环境变量优先,其次 DSH 凭据文件。 */
|
||||
function toolToken() {
|
||||
if (process.env.MARKMAG_TOOL_TOKEN) return process.env.MARKMAG_TOOL_TOKEN
|
||||
try {
|
||||
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
||||
const y = readFileSync(join(home, '.credentials.yaml'), 'utf8')
|
||||
const m = y.match(/^\s+MARKMAG_TOOL_TOKEN:\s*(\S+)/m)
|
||||
return m ? m[1] : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** 调弹匣工具面(同一个端点,agent 和面板共用;规则判定全在弹匣侧)。 */
|
||||
async function callMarkmag(tool, args) {
|
||||
const token = toolToken()
|
||||
if (!token) return { ok: false, err: '还没接入弹匣:缺少工具凭证' }
|
||||
try {
|
||||
const res = await fetch(MARKMAG_BASE + '/api/dsh/tool', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-markmag-token': token },
|
||||
body: JSON.stringify({ tool, args: args || {} }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
})
|
||||
return await res.json()
|
||||
} catch (e) {
|
||||
return { ok: false, err: '连不上弹匣:' + (e.name === 'TimeoutError' ? '超时' : e.message) }
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(req, limit) {
|
||||
return new Promise((resolve) => {
|
||||
const chunks = []
|
||||
let size = 0
|
||||
req.on('data', (c) => {
|
||||
size += c.length
|
||||
if (size > (limit || 1_000_000)) {
|
||||
resolve({})
|
||||
req.destroy()
|
||||
return
|
||||
}
|
||||
chunks.push(c)
|
||||
})
|
||||
req.on('end', () => {
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'))
|
||||
} catch {
|
||||
resolve({})
|
||||
}
|
||||
})
|
||||
req.on('error', () => resolve({}))
|
||||
})
|
||||
}
|
||||
|
||||
function json(res, status, body) {
|
||||
res.statusCode = status
|
||||
res.setHeader('content-type', 'application/json; charset=utf-8')
|
||||
res.setHeader('cache-control', 'no-store')
|
||||
res.end(JSON.stringify(body))
|
||||
}
|
||||
|
||||
function requestRejection(ctx, req) {
|
||||
const connection = ctx.get('connection')
|
||||
if (typeof connection?.requestRejection !== 'function') return 403
|
||||
return connection.requestRejection({ headers: req.headers })
|
||||
}
|
||||
|
||||
export function apply(ctx) {
|
||||
step('apply-entered')
|
||||
|
||||
// ── 1. MCP 工具面 ───────────────────────────────────────
|
||||
const serverPath = fileURLToPath(new URL('./mcp-server.mjs', import.meta.url))
|
||||
step('server-path-resolved', { serverPath })
|
||||
|
||||
;(async () => {
|
||||
let mcpClient
|
||||
try {
|
||||
mcpClient = await import('@deepseek-ai/dsh-mcp-client')
|
||||
step('mcp-client-imported')
|
||||
} catch (e) {
|
||||
step('mcp-client-import-failed', { error: String(e?.message || e).slice(0, 300) })
|
||||
return
|
||||
}
|
||||
try {
|
||||
ctx.plugin(mcpClient, {
|
||||
transport: 'stdio',
|
||||
serverName: 'markmag',
|
||||
command: process.execPath,
|
||||
args: [serverPath],
|
||||
env: { ELECTRON_RUN_AS_NODE: '1' },
|
||||
toolCallTimeoutMs: 30000,
|
||||
})
|
||||
step('mcp-plugin-mounted')
|
||||
} catch (e) {
|
||||
step('mcp-plugin-mount-failed', { error: String(e?.message || e).slice(0, 300) })
|
||||
}
|
||||
})()
|
||||
|
||||
// ── 2. 面板数据接口 ─────────────────────────────────────
|
||||
ctx.effect(
|
||||
() =>
|
||||
ctx.webServer.register({
|
||||
kind: 'prefix',
|
||||
path: '/__markmag',
|
||||
handler: async (req, res) => {
|
||||
try {
|
||||
const rejection = requestRejection(ctx, req)
|
||||
if (rejection) {
|
||||
json(res, rejection, { ok: false, err: 'unauthorized' })
|
||||
return
|
||||
}
|
||||
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
||||
const p = url.pathname.replace(/\/+$/, '')
|
||||
const isPost = (req.method || 'GET').toUpperCase() === 'POST'
|
||||
|
||||
// ── 写操作:面板上的按钮落到弹匣同一套 store,规则不在本地重写 ──
|
||||
if (isPost && p === '/__markmag/task/toggle') {
|
||||
const body = await readJson(req)
|
||||
json(res, 200, await callMarkmag('toggle_task', { id: body.id, to: body.to }))
|
||||
return
|
||||
}
|
||||
if (isPost && p === '/__markmag/task/update') {
|
||||
const body = await readJson(req)
|
||||
json(res, 200, await callMarkmag('update_task', { id: body.id, patch: body.patch || {} }))
|
||||
return
|
||||
}
|
||||
if (isPost && p === '/__markmag/task/create') {
|
||||
const body = await readJson(req)
|
||||
json(res, 200, await callMarkmag('create_task', Object.assign({}, body, { confirm: true })))
|
||||
return
|
||||
}
|
||||
|
||||
if (p === '/__markmag/me') {
|
||||
json(res, 200, await callMarkmag('whoami', {}))
|
||||
return
|
||||
}
|
||||
if (p === '/__markmag/summary') {
|
||||
json(res, 200, await callMarkmag('get_summary', {}))
|
||||
return
|
||||
}
|
||||
if (p === '/__markmag/projects') {
|
||||
json(res, 200, await callMarkmag('query_projects', {}))
|
||||
return
|
||||
}
|
||||
if (p === '/__markmag/tasks') {
|
||||
const args = {}
|
||||
const status = url.searchParams.get('status')
|
||||
const owner = url.searchParams.get('owner')
|
||||
const project = url.searchParams.get('project')
|
||||
if (status) args.status = status
|
||||
if (owner) args.owner = owner
|
||||
if (project) args.project = project
|
||||
json(res, 200, await callMarkmag('query_tasks', args))
|
||||
return
|
||||
}
|
||||
json(res, 404, { ok: false, err: 'not found' })
|
||||
} catch (e) {
|
||||
json(res, 500, { ok: false, err: String(e?.message || e).slice(0, 200) })
|
||||
}
|
||||
},
|
||||
}),
|
||||
'dsh-markmag: panel api'
|
||||
)
|
||||
step('panel-api-registered')
|
||||
|
||||
// ── 3. 启动提示 ─────────────────────────────────────────
|
||||
ctx.effect(() => {
|
||||
try {
|
||||
ctx.get('logger')?.info?.(
|
||||
'[dsh-markmag] 已挂载:四道菜模型通道(GLM-5.3 / GLM-5.3-Flash,凭据 ' + CREDENTIAL + ')+ 弹匣工具面 + 侧边栏面板'
|
||||
)
|
||||
} catch {}
|
||||
}, 'dsh-markmag: startup note')
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 弹匣工具面 —— MCP stdio server。
|
||||
*
|
||||
* 把弹匣的四件工具(汇总/查任务/查项目/建任务)接到 DSH 里,让 agent 能直接
|
||||
* 查团队的任务和项目,不用切到网页。权限跟着工具凭证走:部门隔离由弹匣侧
|
||||
* 按成员的 depts 判定,这里不重复实现(一份规则,一处维护)。
|
||||
*
|
||||
* 凭证来源:环境变量 MARKMAG_TOOL_TOKEN,没有就读 DSH 凭据文件。
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { createInterface } from 'node:readline'
|
||||
|
||||
const BASE = process.env.MARKMAG_BASE || 'https://brain.sidaocai.cn/markmag'
|
||||
|
||||
function readToken() {
|
||||
if (process.env.MARKMAG_TOOL_TOKEN) return process.env.MARKMAG_TOOL_TOKEN
|
||||
try {
|
||||
const y = readFileSync(join(homedir(), '.dsh/.credentials.yaml'), 'utf8')
|
||||
const m = y.match(/^\s+MARKMAG_TOOL_TOKEN:\s*(\S+)/m)
|
||||
return m ? m[1] : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'get_summary',
|
||||
description: '弹匣全局汇总:各项目健康度与阶段、未完成任务数、逾期任务、目标达成率。想知道「团队现在什么状况」时先调这个。',
|
||||
inputSchema: { type: 'object', properties: {} },
|
||||
},
|
||||
{
|
||||
name: 'query_tasks',
|
||||
description: '查弹匣里的任务。可按项目 id、负责人姓名、状态过滤。只返回当前账号有权看的部门。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
project: { type: 'string', description: '项目 id(精确匹配)' },
|
||||
owner: { type: 'string', description: '负责人姓名(精确匹配)' },
|
||||
status: { type: 'string', enum: ['todo', 'doing', 'blocked', 'done'] },
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'query_projects',
|
||||
description: '列出弹匣全部项目(健康度、阶段、进度、负责人)。',
|
||||
inputSchema: { type: 'object', properties: {} },
|
||||
},
|
||||
{
|
||||
name: 'create_task',
|
||||
description: '在弹匣里创建任务。走起草确认制:第一次不带 confirm,只生成草稿并展示给用户;用户明确同意后再带 confirm=true 真正创建。',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
required: ['title'],
|
||||
properties: {
|
||||
title: { type: 'string', description: '任务标题(动作,不是主题)' },
|
||||
owner: { type: 'string', description: '负责人姓名' },
|
||||
due: { type: 'string', description: '截止日 YYYY-MM-DD' },
|
||||
project: { type: 'string', description: '项目 id' },
|
||||
priority: { type: 'string', enum: ['P0', 'P1', 'P2'] },
|
||||
confirm: { type: 'boolean', description: '用户已明确同意创建时传 true' },
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
const TOOL_MAP = {
|
||||
get_summary: 'get_summary',
|
||||
query_tasks: 'query_tasks',
|
||||
query_projects: 'query_projects',
|
||||
create_task: 'create_task',
|
||||
}
|
||||
|
||||
async function callTool(name, args) {
|
||||
const tool = TOOL_MAP[name]
|
||||
if (!tool) return { isError: true, text: '未知工具:' + name }
|
||||
const token = readToken()
|
||||
if (!token) {
|
||||
return { isError: true, text: '还没接入弹匣:缺少工具凭证。跑一次 dsh-markmag 的 setup-account 脚本即可。' }
|
||||
}
|
||||
try {
|
||||
const res = await fetch(BASE + '/api/dsh/tool', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-markmag-token': token },
|
||||
body: JSON.stringify({ tool, args: args || {} }),
|
||||
signal: AbortSignal.timeout(20000),
|
||||
})
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!data.ok) return { isError: true, text: data.err || '弹匣返回 ' + res.status }
|
||||
return { isError: false, text: JSON.stringify(data.result, null, 1) }
|
||||
} catch (e) {
|
||||
return { isError: true, text: '连不上弹匣:' + (e.name === 'TimeoutError' ? '超时' : e.message) }
|
||||
}
|
||||
}
|
||||
|
||||
function send(obj) {
|
||||
process.stdout.write(JSON.stringify(obj) + '\n')
|
||||
}
|
||||
|
||||
const rl = createInterface({ input: process.stdin })
|
||||
rl.on('line', async (line) => {
|
||||
const raw = line.trim()
|
||||
if (!raw) return
|
||||
let msg
|
||||
try {
|
||||
msg = JSON.parse(raw)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const { id, method, params } = msg || {}
|
||||
if (!method) return
|
||||
|
||||
if (method === 'initialize') {
|
||||
return send({
|
||||
jsonrpc: '2.0',
|
||||
id,
|
||||
result: {
|
||||
protocolVersion: '2024-11-05',
|
||||
capabilities: { tools: {} },
|
||||
serverInfo: { name: 'markmag', version: '0.1.0' },
|
||||
},
|
||||
})
|
||||
}
|
||||
if (method === 'notifications/initialized' || method === 'initialized') return
|
||||
if (method === 'tools/list') return send({ jsonrpc: '2.0', id, result: { tools: TOOLS } })
|
||||
if (method === 'tools/call') {
|
||||
const r = await callTool(params?.name || '', params?.arguments || {})
|
||||
return send({
|
||||
jsonrpc: '2.0',
|
||||
id,
|
||||
result: { content: [{ type: 'text', text: r.text }], isError: r.isError },
|
||||
})
|
||||
}
|
||||
if (method === 'ping') return send({ jsonrpc: '2.0', id, result: {} })
|
||||
if (id !== undefined) {
|
||||
send({ jsonrpc: '2.0', id, error: { code: -32601, message: 'unsupported method: ' + method } })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,185 @@
|
||||
.mm-wrap{
|
||||
--ink:var(--dsw-alias-label-primary,#111);
|
||||
--ink2:var(--dsw-alias-label-secondary,#555);
|
||||
--ink3:var(--dsw-alias-label-tertiary,#888);
|
||||
--ink4:var(--dsw-alias-label-caption,#aaa);
|
||||
--line:var(--dsw-alias-border-l2,rgba(0,0,0,.1));
|
||||
--line2:var(--dsw-alias-border-l4,rgba(0,0,0,.16));
|
||||
--card:var(--dsw-alias-bg-layer-2,#fff);
|
||||
--bg:var(--dsw-alias-bg-base,#f7f7f8);
|
||||
--hover:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04));
|
||||
--primary:var(--dsw-alias-button-primary-fill,#2E6BFF);
|
||||
--primary-hover:var(--dsw-alias-button-primary-hover,#4D82FF);
|
||||
--on-primary:var(--dsw-alias-label-primary-inverted,#fff);
|
||||
--ok:var(--dsw-alias-state-success-primary,#10B981);
|
||||
--warn:var(--dsw-alias-state-warn-primary,#D9A406);
|
||||
--err:var(--dsw-alias-state-error-primary,#E5484D);
|
||||
--info:var(--dsw-alias-state-business-primary,#2E6BFF);
|
||||
--idle:var(--dsw-alias-state-idle-primary,#9aa2ad);
|
||||
--r-sm:var(--dsw-radius-sm,8px);
|
||||
--r-md:var(--dsw-radius-md,12px);
|
||||
--r-xl:var(--dsw-radius-xl,20px);
|
||||
height:100%;overflow:auto;background:var(--bg);color:var(--ink);
|
||||
font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;
|
||||
font-size:13px;line-height:1.5;-webkit-font-smoothing:antialiased;
|
||||
}
|
||||
.mm-inner{max-width:1000px;margin:0 auto;padding:20px 22px 48px}
|
||||
.mm-head{display:flex;align-items:center;gap:11px;margin-bottom:14px}
|
||||
.mm-logo{width:32px;height:32px;border-radius:var(--r-md);flex:none;display:grid;place-items:center;
|
||||
background:var(--primary);color:var(--on-primary)}
|
||||
.mm-title{font-size:15.5px;font-weight:650;letter-spacing:.01em}
|
||||
.mm-sub{font-size:11.5px;color:var(--ink4);margin-top:2px}
|
||||
.mm-actions{margin-left:auto;display:flex;align-items:center;gap:8px;flex:none}
|
||||
.mm-btn{border:1px solid var(--line);background:transparent;color:var(--ink2);
|
||||
border-radius:var(--r-sm);padding:5px 11px;font-size:12px;cursor:pointer;transition:.15s;
|
||||
white-space:nowrap;font-family:inherit}
|
||||
.mm-btn:hover{background:var(--hover);color:var(--ink);border-color:var(--line2)}
|
||||
.mm-btn:disabled{cursor:default;opacity:.6}
|
||||
.mm-btn-primary{background:var(--primary);border-color:transparent;color:var(--on-primary);font-weight:560}
|
||||
.mm-btn-primary:hover{background:var(--primary-hover);color:var(--on-primary)}
|
||||
.mm-nav{display:flex;gap:4px;border-bottom:1px solid var(--line);margin-bottom:16px}
|
||||
.mm-nav-i{border:none;background:transparent;color:var(--ink3);font-size:13px;font-family:inherit;
|
||||
padding:8px 12px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px;transition:.15s;
|
||||
display:flex;align-items:center;gap:6px}
|
||||
.mm-nav-i:hover{color:var(--ink)}
|
||||
.mm-nav-on{color:var(--primary);border-bottom-color:var(--primary);font-weight:560}
|
||||
.mm-nav-c{font-size:10.5px;background:var(--hover);border-radius:999px;padding:0 6px;color:var(--ink3);
|
||||
font-variant-numeric:tabular-nums}
|
||||
.mm-nav-on .mm-nav-c{background:color-mix(in srgb,var(--primary) 16%,transparent);color:var(--primary)}
|
||||
.mm-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:20px}
|
||||
.mm-stat{background:var(--card);border:1px solid var(--line);border-radius:var(--r-xl);padding:15px 17px}
|
||||
.mm-stat-n{font-size:26px;font-weight:660;letter-spacing:-.02em;line-height:1.1;font-variant-numeric:tabular-nums}
|
||||
.mm-stat-l{font-size:11.5px;color:var(--ink3);margin-top:4px}
|
||||
.mm-card{background:var(--card);border:1px solid var(--line);border-radius:var(--r-xl);overflow:hidden}
|
||||
.mm-row{display:flex;align-items:center;gap:11px;padding:10px 15px;border-top:1px solid var(--line);transition:background .12s}
|
||||
.mm-row:first-child{border-top:none}
|
||||
.mm-row:hover{background:var(--hover)}
|
||||
.mm-dot{width:7px;height:7px;border-radius:50%;flex:none}
|
||||
.mm-dot-ok{background:var(--ok)}
|
||||
.mm-dot-warn{background:var(--warn)}
|
||||
.mm-dot-err{background:var(--err)}
|
||||
.mm-dot-idle{background:var(--idle)}
|
||||
.mm-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ink)}
|
||||
.mm-meta{font-size:11.5px;color:var(--ink3);flex:none;white-space:nowrap}
|
||||
.mm-date{font-family:ui-monospace,"SF Mono",Menlo,monospace;font-size:11.5px;color:var(--ink4);
|
||||
flex:none;font-variant-numeric:tabular-nums}
|
||||
.mm-date-late{color:var(--err)}
|
||||
.mm-badge{font-size:11px;font-weight:560;padding:2px 8px;border-radius:var(--r-sm);flex:none;white-space:nowrap}
|
||||
.mm-b-todo{background:var(--hover);color:var(--ink2)}
|
||||
.mm-b-doing{background:color-mix(in srgb,var(--info) 14%,transparent);color:var(--info)}
|
||||
.mm-b-blocked{background:color-mix(in srgb,var(--err) 14%,transparent);color:var(--err)}
|
||||
.mm-b-done{background:color-mix(in srgb,var(--ok) 14%,transparent);color:var(--ok)}
|
||||
.mm-empty{padding:24px 16px;text-align:center;color:var(--ink4);font-size:12.5px}
|
||||
.mm-err{background:color-mix(in srgb,var(--err) 10%,transparent);border:1px solid var(--err);
|
||||
color:var(--err);border-radius:var(--r-md);padding:10px 13px;font-size:12.5px;margin-bottom:16px}
|
||||
.mm-foot{margin-top:20px;font-size:11px;color:var(--ink4);line-height:1.7;text-align:center}
|
||||
.mm-sk{height:13px;border-radius:var(--r-sm);background:var(--dsw-alias-bg-skeleton,rgba(0,0,0,.06));
|
||||
animation:mm-pulse 1.4s ease-in-out infinite}
|
||||
@keyframes mm-pulse{0%,100%{opacity:.55}50%{opacity:1}}
|
||||
|
||||
.mm-sched{display:flex;gap:14px;align-items:flex-start}
|
||||
.mm-cal{flex:1;min-width:0;background:var(--card);border:1px solid var(--line);border-radius:var(--r-xl);padding:12px}
|
||||
.mm-cal-h{display:flex;align-items:center;gap:6px;margin-bottom:8px;padding:0 2px}
|
||||
.mm-cal-m{font-size:13.5px;font-weight:640;font-variant-numeric:tabular-nums}
|
||||
.mm-cal-sp{margin-left:auto;display:flex;gap:3px}
|
||||
.mm-cal-b{height:23px;padding:0 7px;border:1px solid var(--line);background:transparent;color:var(--ink3);
|
||||
border-radius:var(--r-sm);cursor:pointer;display:grid;place-items:center;font-size:11.5px;line-height:1;font-family:inherit}
|
||||
.mm-cal-b:hover{background:var(--hover);color:var(--ink)}
|
||||
.mm-cal-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:2px}
|
||||
.mm-cal-w{font-size:10px;color:var(--ink4);text-align:center;padding:2px 0 4px}
|
||||
.mm-cal-d{border:none;background:transparent;border-radius:var(--r-sm);cursor:pointer;font-family:inherit;
|
||||
height:90px;display:flex;flex-direction:column;align-items:stretch;gap:2px;padding:4px 4px 3px;
|
||||
color:var(--ink2);position:relative;transition:background .12s;text-align:left;overflow:hidden}
|
||||
.mm-cal-d:hover{background:var(--hover)}
|
||||
.mm-cal-pad{height:90px}
|
||||
.mm-cal-n{font-size:10.5px;line-height:1.15;color:var(--ink3);flex:none;font-variant-numeric:tabular-nums}
|
||||
.mm-today{box-shadow:inset 0 0 0 1.5px var(--primary)}
|
||||
.mm-today .mm-cal-n{color:var(--primary);font-weight:650}
|
||||
.mm-sel{background:var(--primary)!important}
|
||||
.mm-sel .mm-cal-n{color:var(--on-primary)}
|
||||
.mm-ev{font-size:9.5px;line-height:1.45;border-radius:3px;padding:0 3px;overflow:hidden;text-overflow:ellipsis;
|
||||
white-space:nowrap;background:var(--hover);color:var(--ink2);flex:none;max-width:100%}
|
||||
.mm-ev-late{background:color-mix(in srgb,var(--err) 13%,transparent);color:var(--err)}
|
||||
.mm-ev-doing{background:color-mix(in srgb,var(--info) 13%,transparent);color:var(--info)}
|
||||
.mm-ev-more{font-size:9px;color:var(--ink4);padding-left:2px;flex:none}
|
||||
.mm-sel .mm-ev{background:rgba(255,255,255,.22);color:var(--on-primary)}
|
||||
.mm-sel .mm-ev-late{background:rgba(255,255,255,.22);color:var(--on-primary)}
|
||||
.mm-sel .mm-ev-more{color:rgba(255,255,255,.72)}
|
||||
.mm-day{width:268px;flex:none}
|
||||
.mm-day-h{margin-bottom:8px}
|
||||
.mm-day-t{font-size:13px;font-weight:640;font-variant-numeric:tabular-nums}
|
||||
.mm-day-s{font-size:11.5px;color:var(--ink4);margin-top:2px}
|
||||
@media (max-width:820px){.mm-sched{flex-direction:column}.mm-day{width:100%}}
|
||||
|
||||
/* 甘特图 */
|
||||
.mm-gantt{background:var(--card);border:1px solid var(--line);border-radius:var(--r-xl);overflow:hidden}
|
||||
.mm-gantt-h{display:flex;align-items:stretch;border-bottom:1px solid var(--line);background:var(--hover)}
|
||||
.mm-gantt-hn{width:170px;flex:none;padding:7px 14px;font-size:11px;color:var(--ink3);display:flex;align-items:center}
|
||||
.mm-gantt-cols{flex:1;display:flex;min-width:0}
|
||||
.mm-gantt-c{flex:1;min-width:0;text-align:center;font-size:9.5px;color:var(--ink4);padding:5px 0 4px;
|
||||
border-left:1px solid var(--line);line-height:1.35;overflow:hidden}
|
||||
.mm-gantt-c-w{font-size:9px;color:var(--ink4);opacity:.75}
|
||||
.mm-gantt-cow{color:var(--primary);font-weight:650;background:color-mix(in srgb,var(--primary) 8%,transparent)}
|
||||
.mm-gantt-row{display:flex;align-items:stretch;border-top:1px solid var(--line);height:36px}
|
||||
.mm-gantt-row:first-child{border-top:none}
|
||||
.mm-gantt-row:hover{background:var(--hover)}
|
||||
.mm-gantt-n{width:170px;flex:none;display:flex;align-items:center;gap:7px;padding:0 14px;min-width:0}
|
||||
.mm-gantt-nm{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12.5px}
|
||||
.mm-gantt-track{flex:1;position:relative;display:flex;min-width:0}
|
||||
.mm-gantt-cell{flex:1;min-width:0;border-left:1px solid var(--line)}
|
||||
.mm-gantt-cell-cow{background:color-mix(in srgb,var(--primary) 5%,transparent)}
|
||||
.mm-gantt-bar{position:absolute;top:50%;height:15px;transform:translateY(-50%);border-radius:4px;
|
||||
background:var(--primary);opacity:.82;z-index:1;min-width:4px}
|
||||
.mm-gantt-bar-doing{background:var(--info)}
|
||||
.mm-gantt-bar-late{background:var(--err);opacity:.9}
|
||||
.mm-gantt-bar-done{background:var(--ok);opacity:.55}
|
||||
.mm-gantt-lbl{position:absolute;top:50%;transform:translateY(-50%);font-size:9.5px;color:var(--ink3);
|
||||
padding-left:6px;white-space:nowrap;z-index:1}
|
||||
.mm-gantt-legend{display:flex;gap:14px;margin-top:10px;padding-left:2px;flex-wrap:wrap}
|
||||
.mm-lgi{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--ink4)}
|
||||
.mm-lgd{width:16px;height:8px;border-radius:3px}
|
||||
|
||||
/* 身份 / 焦点 / 项目矩阵 / 可点行 */
|
||||
.mm-id{font-size:11.5px;color:var(--ink4);margin-top:2px}
|
||||
.mm-row-click{cursor:pointer}
|
||||
.mm-focus{background:var(--card);border:1px solid var(--line);border-radius:var(--r-xl);overflow:hidden;margin-bottom:20px}
|
||||
.mm-focus-h{display:flex;align-items:center;gap:8px;padding:11px 15px 9px}
|
||||
.mm-focus-t{font-size:12px;font-weight:640;color:var(--err)}
|
||||
.mm-focus-c{font-size:11px;color:var(--ink4)}
|
||||
.mm-focus-i{display:flex;align-items:center;gap:10px;padding:10px 15px;border-top:1px solid var(--line);
|
||||
cursor:pointer;transition:background .12s}
|
||||
.mm-focus-i:hover{background:var(--hover)}
|
||||
.mm-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}
|
||||
.mm-grid-1{grid-template-columns:1fr}
|
||||
.mm-pcard{background:var(--card);border:1px solid var(--line);border-radius:var(--r-lg);padding:13px 15px;
|
||||
cursor:pointer;transition:.15s;min-width:0}
|
||||
.mm-pcard:hover{border-color:var(--line2);background:var(--hover)}
|
||||
.mm-pcard-n{font-size:13.5px;font-weight:600;color:var(--ink);margin-bottom:7px;line-height:1.35}
|
||||
.mm-pcard-m{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--ink3);flex-wrap:wrap}
|
||||
.mm-bar{height:4px;border-radius:2px;background:var(--hover);overflow:hidden;margin-top:9px}
|
||||
.mm-bar-i{height:100%;border-radius:2px;background:var(--primary)}
|
||||
.mm-empty-hint{padding:22px 16px;text-align:center;color:var(--ink4);font-size:12.5px;line-height:1.9}
|
||||
.mm-actions-2{display:flex;gap:6px;margin-bottom:9px;flex-wrap:wrap}
|
||||
|
||||
/* 行内操作 / 改期 / 新建 */
|
||||
.mm-row-ops{margin-left:auto;display:flex;gap:5px;opacity:0;transition:opacity .12s;flex:none}
|
||||
.mm-row:hover .mm-row-ops,.mm-focus-i:hover .mm-row-ops{opacity:1}
|
||||
.mm-op{height:21px;padding:0 7px;border:1px solid var(--line);border-radius:6px;background:transparent;
|
||||
color:var(--ink3);font-size:11px;cursor:pointer;font-family:inherit;line-height:19px;white-space:nowrap}
|
||||
.mm-op:hover{background:var(--hover);color:var(--ink);border-color:var(--line2)}
|
||||
.mm-op-done:hover{color:var(--ok);border-color:var(--ok)}
|
||||
.mm-op:disabled{opacity:.45;cursor:default}
|
||||
.mm-date-edit{cursor:pointer;border-bottom:1px dashed var(--line2)}
|
||||
.mm-date-edit:hover{color:var(--ink);border-bottom-color:var(--ink3)}
|
||||
.mm-date-in{width:126px;border:1px solid var(--primary);border-radius:6px;padding:1px 4px;
|
||||
font-size:11.5px;font-family:inherit;background:var(--card);color:var(--ink)}
|
||||
.mm-new{margin-top:10px}
|
||||
.mm-new-row{display:flex;gap:8px;flex-wrap:wrap;align-items:center;padding:12px 15px}
|
||||
.mm-in{border:1px solid var(--line);border-radius:var(--r-sm);padding:6px 9px;font-size:12.5px;
|
||||
font-family:inherit;background:var(--bg);color:var(--ink);min-width:0}
|
||||
.mm-in:focus{outline:none;border-color:var(--primary)}
|
||||
.mm-in-t{flex:1;min-width:170px}
|
||||
.mm-in-d{width:142px}
|
||||
.mm-in-s{width:150px}
|
||||
.mm-ok{background:color-mix(in srgb,var(--ok) 10%,transparent);border:1px solid var(--ok);color:var(--ok);
|
||||
border-radius:var(--r-md);padding:9px 13px;font-size:12.5px;margin-bottom:14px}
|
||||
@@ -0,0 +1,434 @@
|
||||
/**
|
||||
* 弹匣工作台 —— DSH 客户端半片(侧边栏面板)。
|
||||
*
|
||||
* 定位:DSH 里「我现在该干什么」+ 就地处理 + 一键跳回弹匣看全貌。
|
||||
* 数据与写操作全部走 /__markmag/*(宿主转调弹匣 API,鉴权用工具凭证)。
|
||||
*
|
||||
* 写操作的规矩:面板只把按钮接到弹匣已有的能力上(tasks_store.cycle / update / create),
|
||||
* 状态机、字段白名单、部门可见性、活动日志、依赖预警全在弹匣侧判定,这里一行规则都不重写。
|
||||
*
|
||||
* 默认个人看板;第二栏的可见范围由弹匣后端 _vis_ok 决定,面板只按角色给名字。
|
||||
* 产物由 scripts/build-client.mjs 从 panel.css + panel.template.js 合成。
|
||||
*/
|
||||
window.__ModuleLoader__.load({
|
||||
id: "dsh-markmag",
|
||||
factory: function (require) {
|
||||
const module = { exports: {} }
|
||||
const exports = module.exports
|
||||
|
||||
const reactMod = require("react")
|
||||
const React = reactMod && reactMod.default ? reactMod.default : reactMod
|
||||
const h = React.createElement
|
||||
const useState = React.useState
|
||||
const useEffect = React.useEffect
|
||||
const useCallback = React.useCallback
|
||||
const useMemo = React.useMemo
|
||||
|
||||
const KEY = "markmag"
|
||||
const BASE = "https://brain.sidaocai.cn/markmag/"
|
||||
const CSS = __CSS_JSON__
|
||||
|
||||
const HEALTH_CLASS = { green: "mm-dot-ok", yellow: "mm-dot-warn", amber: "mm-dot-warn", red: "mm-dot-err" }
|
||||
const HEALTH_TXT = { green: "健康", yellow: "注意", amber: "注意", red: "异常" }
|
||||
const STATUS = {
|
||||
todo: ["待办", "mm-b-todo"],
|
||||
doing: ["进行中", "mm-b-doing"],
|
||||
blocked: ["受阻", "mm-b-blocked"],
|
||||
done: ["已完成", "mm-b-done"],
|
||||
}
|
||||
const FILTERS = [["", "全部"], ["todo", "待办"], ["doing", "进行中"], ["blocked", "受阻"]]
|
||||
|
||||
function pad2(n) { return String(n).padStart(2, "0") }
|
||||
function todayStr() {
|
||||
const d = new Date()
|
||||
return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate())
|
||||
}
|
||||
function openInMarkmag(hash) { window.open(BASE + (hash || ""), "_blank", "noopener") }
|
||||
|
||||
async function postJson(url, body) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body || {}),
|
||||
})
|
||||
return await res.json()
|
||||
} catch (e) {
|
||||
return { ok: false, err: "请求失败:" + (e.message || e) }
|
||||
}
|
||||
}
|
||||
|
||||
function Icon(props) {
|
||||
const size = (props && props.size) || 20
|
||||
return h("svg", {
|
||||
width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
|
||||
strokeWidth: 1.9, strokeLinecap: "round", strokeLinejoin: "round",
|
||||
},
|
||||
h("rect", { x: 3, y: 4.5, width: 18, height: 15, rx: 2.5 }),
|
||||
h("path", { d: "M7.5 9.5h9" }),
|
||||
h("path", { d: "M7.5 13.5h5.5" })
|
||||
)
|
||||
}
|
||||
|
||||
function Logo() {
|
||||
return h("div", { className: "mm-logo" },
|
||||
h("svg", {
|
||||
width: 17, height: 17, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor",
|
||||
strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round",
|
||||
},
|
||||
h("rect", { x: 3.5, y: 5, width: 17, height: 14, rx: 2.5 }),
|
||||
h("path", { d: "M8 10h8" }),
|
||||
h("path", { d: "M8 14h4.5" })
|
||||
))
|
||||
}
|
||||
|
||||
function Badge(props) {
|
||||
const st = STATUS[props.status] || [props.status || "", "mm-b-todo"]
|
||||
return h("span", { className: "mm-badge " + st[1] }, st[0])
|
||||
}
|
||||
|
||||
function Skeleton() {
|
||||
return [0, 1, 2].map(function (i) {
|
||||
return h("div", { key: i, className: "mm-row" },
|
||||
h("div", { className: "mm-sk", style: { width: (150 + i * 60) + "px" } }))
|
||||
})
|
||||
}
|
||||
|
||||
function Panel() {
|
||||
const sMe = useState(null), me = sMe[0], setMe = sMe[1]
|
||||
const sTasks = useState([]), tasks = sTasks[0], setTasks = sTasks[1]
|
||||
const sProjects = useState([]), projects = sProjects[0], setProjects = sProjects[1]
|
||||
const sErr = useState(""), err = sErr[0], setErr = sErr[1]
|
||||
const sNote = useState(""), note = sNote[0], setNote = sNote[1]
|
||||
const sLoading = useState(true), loading = sLoading[0], setLoading = sLoading[1]
|
||||
const sAt = useState(""), at = sAt[0], setAt = sAt[1]
|
||||
const sTab = useState("mine"), tab = sTab[0], setTab = sTab[1]
|
||||
const sFilter = useState(""), filter = sFilter[0], setFilter = sFilter[1]
|
||||
const sUrgent = useState(false), urgent = sUrgent[0], setUrgent = sUrgent[1]
|
||||
const sBusy = useState(0), busy = sBusy[0], setBusy = sBusy[1]
|
||||
const sEditing = useState(0), editing = sEditing[0], setEditing = sEditing[1]
|
||||
const sNew = useState(false), showNew = sNew[0], setShowNew = sNew[1]
|
||||
const sForm = useState({ title: "", due: "", project: "" }), form = sForm[0], setForm = sForm[1]
|
||||
|
||||
const load = useCallback(function () {
|
||||
setLoading(true)
|
||||
setErr("")
|
||||
Promise.all([
|
||||
fetch("/__markmag/me", { credentials: "same-origin" }).then(function (r) { return r.json() }),
|
||||
fetch("/__markmag/tasks", { credentials: "same-origin" }).then(function (r) { return r.json() }),
|
||||
fetch("/__markmag/projects", { credentials: "same-origin" }).then(function (r) { return r.json() }),
|
||||
]).then(function (res) {
|
||||
const m = res[0], t = res[1], p = res[2]
|
||||
if (m && m.ok && m.result) setMe(m.result)
|
||||
else if (m && !m.ok) throw new Error(m.err || "读取身份失败")
|
||||
setTasks(t && t.ok && t.result && t.result.tasks ? t.result.tasks : [])
|
||||
setProjects(p && p.ok && p.result && p.result.projects ? p.result.projects : [])
|
||||
setAt(new Date().toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" }))
|
||||
}).catch(function (e) {
|
||||
setErr(e.message || String(e))
|
||||
}).then(function () {
|
||||
setLoading(false)
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(function () { load() }, [load])
|
||||
|
||||
// ── 写操作:都落到弹匣同一套 store,成功后重新拉一遍 ──
|
||||
async function doToggle(t) {
|
||||
setBusy(t.id); setErr(""); setNote("")
|
||||
const r = await postJson("/__markmag/task/toggle", { id: t.id })
|
||||
setBusy(0)
|
||||
if (r && r.ok) {
|
||||
const st = r.result && r.result.status
|
||||
setNote((st === "done" ? "已完成:" : "状态:" + (STATUS[st] ? STATUS[st][0] : st) + " ") + t.title)
|
||||
load()
|
||||
} else setErr((r && r.err) || "操作失败")
|
||||
}
|
||||
|
||||
async function doSetDue(t, due) {
|
||||
setEditing(0); setErr(""); setNote("")
|
||||
if (!due || due === t.due) return
|
||||
setBusy(t.id)
|
||||
const r = await postJson("/__markmag/task/update", { id: t.id, patch: { due: due } })
|
||||
setBusy(0)
|
||||
if (r && r.ok) { setNote("截止日已改为 " + due + ":" + t.title); load() }
|
||||
else setErr((r && r.err) || "改期失败")
|
||||
}
|
||||
|
||||
async function doCreate() {
|
||||
const title = (form.title || "").trim()
|
||||
if (!title) { setErr("先写个任务标题"); return }
|
||||
setBusy(-1); setErr(""); setNote("")
|
||||
const payload = { title: title }
|
||||
if (form.due) payload.due = form.due
|
||||
if (form.project) payload.project = form.project
|
||||
const r = await postJson("/__markmag/task/create", payload)
|
||||
setBusy(0)
|
||||
if (r && r.ok) {
|
||||
setNote("已建任务:" + title)
|
||||
setForm({ title: "", due: "", project: "" })
|
||||
setShowNew(false)
|
||||
load()
|
||||
} else setErr((r && r.err) || "建任务失败")
|
||||
}
|
||||
|
||||
const today = todayStr()
|
||||
const myName = (me && me.name) || ""
|
||||
const myRole = (me && me.role) || "member"
|
||||
const scopeLabel = myRole === "admin" ? "全团队" : (myRole === "dept_admin" ? "本部门" : "部门可见")
|
||||
|
||||
const mine = useMemo(function () {
|
||||
return tasks.filter(function (t) { return t.owner === myName || t.created_by === myName })
|
||||
}, [tasks, myName])
|
||||
|
||||
const openTasks = useMemo(function () {
|
||||
return tasks.filter(function (t) { return t.status !== "done" })
|
||||
}, [tasks])
|
||||
|
||||
const focus = useMemo(function () {
|
||||
return openTasks.filter(function (t) { return t.due && t.due <= today })
|
||||
.sort(function (a, b) { return a.due < b.due ? -1 : 1 })
|
||||
}, [openTasks, today])
|
||||
|
||||
const overdueCount = useMemo(function () {
|
||||
return openTasks.filter(function (t) { return t.due && t.due < today }).length
|
||||
}, [openTasks, today])
|
||||
|
||||
const base = tab === "mine" ? mine.filter(function (t) { return t.status !== "done" }) : openTasks
|
||||
const shown = useMemo(function () {
|
||||
let list = base
|
||||
if (urgent) list = list.filter(function (t) { return t.due && t.due < today })
|
||||
if (filter) list = list.filter(function (t) { return t.status === filter })
|
||||
return list.slice().sort(function (a, b) {
|
||||
if (!a.due && !b.due) return 0
|
||||
if (!a.due) return 1
|
||||
if (!b.due) return -1
|
||||
return a.due < b.due ? -1 : 1
|
||||
})
|
||||
}, [base, urgent, filter, today])
|
||||
|
||||
/** 一行任务:徽章 + 标题 + 负责人 + 日期(可改)+ hover 操作(完成/改期/去弹匣) */
|
||||
function TaskLine(t) {
|
||||
const late = t.due && t.due < today
|
||||
const isEditing = editing === t.id
|
||||
const ops = h("div", { className: "mm-row-ops" },
|
||||
h("button", {
|
||||
className: "mm-op mm-op-done",
|
||||
disabled: busy === t.id,
|
||||
onClick: function (e) { e.stopPropagation(); doToggle(t) },
|
||||
}, t.status === "done" ? "重开" : "完成"),
|
||||
h("button", {
|
||||
className: "mm-op",
|
||||
onClick: function (e) { e.stopPropagation(); setEditing(isEditing ? 0 : t.id) },
|
||||
}, "改期"),
|
||||
h("button", {
|
||||
className: "mm-op",
|
||||
onClick: function (e) { e.stopPropagation(); openInMarkmag("#today") },
|
||||
}, "弹匣"))
|
||||
const dateEl = isEditing
|
||||
? h("input", {
|
||||
className: "mm-date-in",
|
||||
type: "date",
|
||||
defaultValue: t.due || today,
|
||||
autoFocus: true,
|
||||
onClick: function (e) { e.stopPropagation() },
|
||||
onChange: function (e) { doSetDue(t, e.target.value) },
|
||||
onBlur: function () { setEditing(0) },
|
||||
})
|
||||
: h("span", {
|
||||
className: "mm-date mm-date-edit" + (late ? " mm-date-late" : ""),
|
||||
style: { width: 70, textAlign: "right" },
|
||||
onClick: function (e) { e.stopPropagation(); setEditing(t.id) },
|
||||
}, t.due || "设日期")
|
||||
return h("div", {
|
||||
key: t.id,
|
||||
className: "mm-row mm-row-click",
|
||||
onClick: function () { openInMarkmag("#today") },
|
||||
},
|
||||
h(Badge, { status: t.status }),
|
||||
h("span", { className: "mm-name" }, t.title),
|
||||
h("span", { className: "mm-meta", style: { flex: "none" } }, t.owner || ""),
|
||||
dateEl,
|
||||
ops)
|
||||
}
|
||||
|
||||
const focusEl = focus.length
|
||||
? h("div", { className: "mm-focus" },
|
||||
h("div", { className: "mm-focus-h" },
|
||||
h("span", { className: "mm-focus-t" },
|
||||
overdueCount ? "要处理:" + overdueCount + " 项已逾期" : "今天到期"),
|
||||
h("span", { className: "mm-focus-c" }, "可直接完成或改期")),
|
||||
focus.slice(0, 6).map(function (t) { return TaskLine(t) }))
|
||||
: null
|
||||
|
||||
const statsEl = h("div", { className: "mm-stats" },
|
||||
h("div", { className: "mm-stat", style: { cursor: "pointer" },
|
||||
onClick: function () { setTab("scope"); setUrgent(false); setFilter("") } },
|
||||
h("div", { className: "mm-stat-n" }, String(mine.filter(function (t) { return t.status !== "done" }).length)),
|
||||
h("div", { className: "mm-stat-l" }, "我的未完成")),
|
||||
h("div", { className: "mm-stat", style: { cursor: "pointer" },
|
||||
onClick: function () { setTab("scope"); setUrgent(true); setFilter("") } },
|
||||
h("div", { className: "mm-stat-n", style: overdueCount ? { color: "var(--err)" } : null }, String(overdueCount)),
|
||||
h("div", { className: "mm-stat-l" }, "已逾期")),
|
||||
h("div", { className: "mm-stat", style: { cursor: "pointer" },
|
||||
onClick: function () { openInMarkmag("#proj") } },
|
||||
h("div", { className: "mm-stat-n" }, String(projects.length)),
|
||||
h("div", { className: "mm-stat-l" }, "项目")))
|
||||
|
||||
const tabsEl = h("div", { className: "mm-actions-2" },
|
||||
[["mine", "我的"], ["scope", scopeLabel]].map(function (item) {
|
||||
const k = item[0], label = item[1]
|
||||
return h("button", {
|
||||
key: k,
|
||||
className: "mm-tab" + (tab === k ? " mm-tab-on" : ""),
|
||||
onClick: function () { setTab(k); setUrgent(false) },
|
||||
}, label)
|
||||
}),
|
||||
h("span", { style: { flex: 1 } }),
|
||||
urgent ? h("button", { className: "mm-tab mm-tab-on", onClick: function () { setUrgent(false) } }, "只看逾期 ×") : null)
|
||||
|
||||
const filtersEl = h("div", { className: "mm-actions-2" },
|
||||
FILTERS.map(function (f) {
|
||||
const v = f[0], label = f[1]
|
||||
return h("button", {
|
||||
key: "f" + v,
|
||||
className: "mm-tab" + (filter === v ? " mm-tab-on" : ""),
|
||||
onClick: function () { setFilter(v) },
|
||||
}, label)
|
||||
}))
|
||||
|
||||
const taskRows = shown.length
|
||||
? shown.map(function (t) { return TaskLine(t) })
|
||||
: (loading
|
||||
? h(Skeleton)
|
||||
: h("div", { className: "mm-empty-hint" },
|
||||
tab === "mine" ? "你手上没有到期任务" : "这个范围里没有任务"))
|
||||
|
||||
const projectOptions = projects.map(function (p) {
|
||||
return h("option", { key: p.id, value: p.id }, p.name)
|
||||
})
|
||||
|
||||
const newEl = h("div", { className: "mm-new" },
|
||||
showNew
|
||||
? h("div", { className: "mm-card" },
|
||||
h("div", { className: "mm-new-row" },
|
||||
h("input", {
|
||||
className: "mm-in mm-in-t",
|
||||
placeholder: "任务标题",
|
||||
value: form.title,
|
||||
autoFocus: true,
|
||||
onChange: function (e) { setForm(Object.assign({}, form, { title: e.target.value })) },
|
||||
onKeyDown: function (e) { if (e.key === "Enter") doCreate() },
|
||||
}),
|
||||
h("input", {
|
||||
className: "mm-in mm-in-d",
|
||||
type: "date",
|
||||
value: form.due,
|
||||
onChange: function (e) { setForm(Object.assign({}, form, { due: e.target.value })) },
|
||||
}),
|
||||
h("select", {
|
||||
className: "mm-in mm-in-s",
|
||||
value: form.project,
|
||||
onChange: function (e) { setForm(Object.assign({}, form, { project: e.target.value })) },
|
||||
}, h("option", { value: "" }, "不挂项目"), projectOptions),
|
||||
h("button", {
|
||||
className: "mm-btn mm-btn-primary",
|
||||
disabled: busy === -1,
|
||||
onClick: doCreate,
|
||||
}, busy === -1 ? "提交中…" : "建任务"),
|
||||
h("button", { className: "mm-btn", onClick: function () { setShowNew(false) } }, "取消")))
|
||||
: h("button", {
|
||||
className: "mm-btn",
|
||||
style: { width: "100%" },
|
||||
onClick: function () { setShowNew(true); setNote("") },
|
||||
}, "+ 快速建任务"))
|
||||
|
||||
const projectCards = projects.length
|
||||
? projects.map(function (p, i) {
|
||||
const key = String(p.health || "").toLowerCase()
|
||||
const pct = typeof p.progress === "number" ? Math.max(0, Math.min(100, p.progress)) : null
|
||||
return h("div", {
|
||||
key: p.id || i,
|
||||
className: "mm-pcard",
|
||||
onClick: function () { openInMarkmag(p.id ? "#d/" + p.id : "#proj") },
|
||||
},
|
||||
h("div", { className: "mm-pcard-n" }, p.name),
|
||||
h("div", { className: "mm-pcard-m" },
|
||||
h("span", { className: "mm-dot " + (HEALTH_CLASS[key] || "mm-dot-idle") }),
|
||||
h("span", null, HEALTH_TXT[key] || "—"),
|
||||
p.stage ? h("span", null, "· " + p.stage) : null,
|
||||
p.owner ? h("span", null, "· " + p.owner) : null),
|
||||
pct === null ? null : h("div", { className: "mm-bar" },
|
||||
h("div", { className: "mm-bar-i", style: { width: pct + "%" } })))
|
||||
})
|
||||
: h("div", { className: "mm-pcard" },
|
||||
h("div", { className: "mm-pcard-n" }, loading ? "读取中…" : "还没有项目"))
|
||||
|
||||
const identity = me
|
||||
? myName + (myRole === "admin" ? " · 团队负责人" : myRole === "dept_admin" ? " · 部门负责人" : "")
|
||||
: ""
|
||||
|
||||
return h("div", { className: "mm-wrap" },
|
||||
h("style", { dangerouslySetInnerHTML: { __html: CSS } }),
|
||||
h("div", { className: "mm-inner" },
|
||||
h("div", { className: "mm-head" },
|
||||
h(Logo),
|
||||
h("div", null,
|
||||
h("div", { className: "mm-title" }, "弹匣工作台"),
|
||||
h("div", { className: "mm-sub" }, identity || (at ? "数据更新于 " + at : "四道菜 · 团队作战台"))),
|
||||
h("div", { className: "mm-actions" },
|
||||
h("button", { className: "mm-btn", onClick: load, disabled: loading },
|
||||
loading ? "读取中…" : "刷新"),
|
||||
h("button", {
|
||||
className: "mm-btn mm-btn-primary",
|
||||
onClick: function () { openInMarkmag("#today") },
|
||||
}, "弹匣全貌"))),
|
||||
|
||||
err ? h("div", { className: "mm-err" }, err) : null,
|
||||
note ? h("div", { className: "mm-ok" }, note) : null,
|
||||
focusEl,
|
||||
statsEl,
|
||||
|
||||
h("div", { className: "mm-sec" },
|
||||
h("div", { className: "mm-sec-h" },
|
||||
h("span", { className: "mm-sec-t" }, "任务"),
|
||||
h("span", { className: "mm-sec-c" }, String(shown.length))),
|
||||
tabsEl,
|
||||
filtersEl,
|
||||
h("div", { className: "mm-card" }, taskRows),
|
||||
newEl),
|
||||
|
||||
h("div", { className: "mm-sec" },
|
||||
h("div", { className: "mm-sec-h" },
|
||||
h("span", { className: "mm-sec-t" }, "项目"),
|
||||
h("span", { className: "mm-sec-c" }, String(projects.length))),
|
||||
h("div", { className: "mm-grid" }, projectCards)),
|
||||
|
||||
h("div", { className: "mm-foot" }, "悬停任务行可完成 / 改期 · 写操作与弹匣同一套规则")))
|
||||
}
|
||||
|
||||
function apply(ctx) {
|
||||
ctx.slots.inject("main", function () {
|
||||
return ctx.slots.register({ name: "main", key: KEY }, Panel)
|
||||
})
|
||||
ctx.effect(function () {
|
||||
let dispose = null
|
||||
function mount() {
|
||||
if (dispose) dispose()
|
||||
dispose = ctx.slots.inject("sidebar.panellist", function () {
|
||||
return ctx.slots.register(
|
||||
{ name: "sidebar.panellist", id: KEY, order: 6, label: function () { return "弹匣工作台" } },
|
||||
Icon
|
||||
)
|
||||
})
|
||||
}
|
||||
mount()
|
||||
return function () { if (dispose) dispose() }
|
||||
}, "dsh-markmag: sidebar entry")
|
||||
}
|
||||
|
||||
module.exports = { inject: ["slots"], apply: apply }
|
||||
return module.exports
|
||||
},
|
||||
})
|
||||
Reference in new issue
Block a user