cardbuddy 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +21 -6
  2. package/dist/cli.js +17 -6
  3. package/dist/config.js +20 -2
  4. package/dist/portGuard.js +293 -0
  5. package/dist/preview-editor/assets/index-B4VZgNSK.css +1 -0
  6. package/dist/preview-editor/assets/index-jl4YJzKv.js +180 -0
  7. package/dist/preview-editor/index.html +2 -2
  8. package/dist/server-core/_vendor/finmall-env.mjs +4 -4
  9. package/dist/server-core/ai-chat.js +3710 -0
  10. package/dist/server-core/assetProxy.js +3 -22
  11. package/dist/server-core/buildDataFromSchema.js +36 -4
  12. package/dist/server-core/cardFiles.js +95 -2
  13. package/dist/server-core/cardImage.js +14 -0
  14. package/dist/server-core/cardListCache.js +0 -17
  15. package/dist/server-core/cardSave.js +2 -0
  16. package/dist/server-core/cardValidate.js +3 -0
  17. package/dist/server-core/index.js +6 -5
  18. package/dist/server-core/logStream.js +1 -6
  19. package/dist/server-core/sliceUpload.js +8 -1
  20. package/dist/standalone.js +24 -8
  21. package/dist/vendored/App.vue +405 -125
  22. package/dist/vendored/api.js +4 -4
  23. package/dist/vendored/assets/svgIcons/icons.svg +28 -0
  24. package/dist/vendored/components/AiSettings.vue +392 -0
  25. package/dist/vendored/components/CardGallery.vue +51 -5
  26. package/dist/vendored/components/ChatComposer.vue +413 -0
  27. package/dist/vendored/components/ChatMessage.vue +383 -0
  28. package/dist/vendored/components/ChatPanel.vue +937 -0
  29. package/dist/vendored/components/ComponentPalette.vue +1 -1
  30. package/dist/vendored/components/DebugPanel.vue +732 -90
  31. package/dist/vendored/components/Dropdown.vue +4 -2
  32. package/dist/vendored/components/MarkdownBody.vue +64 -0
  33. package/dist/vendored/components/NewCardDialog.vue +132 -0
  34. package/dist/vendored/components/NumberStepper.vue +125 -0
  35. package/dist/vendored/components/ProgressSlider.vue +9 -1
  36. package/dist/vendored/components/RemotePreview.vue +1 -1
  37. package/dist/vendored/components/StructureTree.vue +2 -2
  38. package/dist/vendored/main.js +1 -0
  39. package/dist/vendored/runtime/adapter.js +1 -1
  40. package/dist/vendored/runtime/ai-api.js +165 -0
  41. package/dist/vendored/runtime/clipboard-node.js +0 -5
  42. package/dist/vendored/runtime/markdown.js +140 -0
  43. package/dist/vendored/skills/.manifest.json +1101 -0
  44. package/dist/vendored/skills/dsl-card-generator/scripts/autofix_schema.py +249 -0
  45. package/dist/vendored/skills/dsl-card-generator/scripts/check_topology.py +678 -0
  46. package/dist/vendored/skills/dsl-card-generator/scripts/derive_data_json.py +81 -0
  47. package/dist/vendored/skills/dsl-card-generator/scripts/lib/paths.py +105 -0
  48. package/dist/vendored/skills/dsl-card-generator/scripts/validate_schema.py +624 -0
  49. package/dist/vendored/skills/finmall-card-sync/scripts/api_batch_sync.mjs +900 -0
  50. package/dist/vendored/skills/finmall-card-sync/scripts/slice_upload.mjs +699 -0
  51. package/dist/vendored/skills/shared/finmall-config.mjs +124 -0
  52. package/dist/vendored/styles/ai-chat.css +1850 -0
  53. package/dist/vendored/styles/app.css +725 -213
  54. package/dist/vendored/styles/card-gallery.css +48 -10
  55. package/dist/vendored/styles/card-select.css +13 -6
  56. package/dist/vendored/styles/dropdown.css +1 -2
  57. package/dist/vendored/styles/json-tree.css +3 -3
  58. package/dist/vendored/styles/node-inspector.css +13 -289
  59. package/dist/vendored/styles/setters.css +48 -49
  60. package/dist/vendored/styles/structure-tree.css +6 -11
  61. package/package.json +1 -1
  62. package/dist/preview-editor/assets/index-B9MOriNv.js +0 -80
  63. package/dist/preview-editor/assets/index-CwD14gm3.css +0 -1
  64. package/dist/vendored/assets/logo.png +0 -0
@@ -8,7 +8,8 @@
8
8
  :disabled="disabled"
9
9
  @click="toggle"
10
10
  >
11
- <span class="dd__label" :title="displayText">{{ displayText }}</span>
11
+ <!-- current 插槽:自定义触发器内的已选值呈现(如「彩色类型标签 + 中文名」),缺省仍为纯文本 -->
12
+ <span class="dd__label" :title="displayText"><slot name="current" :opt="current" :text="displayText">{{ displayText }}</slot></span>
12
13
  <span
13
14
  v-if="clearable && hasValue"
14
15
  class="dd__clear"
@@ -36,7 +37,8 @@
36
37
  @mousemove="onHover(opt)"
37
38
  @click="onItemClick(opt)"
38
39
  >
39
- <span class="dd__item-text">{{ opt.value }}</span>
40
+ <!-- option 插槽:自定义单个选项的内容,缺省为 opt.value 纯文本 -->
41
+ <span class="dd__item-text"><slot name="option" :opt="opt">{{ opt.value }}</slot></span>
40
42
  <svg v-if="opt.key === value" class="dd__check" viewBox="0 0 16 16" :width="checkSize" :height="checkSize" aria-hidden="true"><use href="#icon-check" /></svg>
41
43
  </li>
42
44
  <li v-if="!options.length" class="dd__empty">{{ placeholder || '无选项' }}</li>
@@ -0,0 +1,64 @@
1
+ <template>
2
+ <!-- 模型输出经 marked 解析 + DOMPurify 消毒后注入;代码块由 enhanceCodeBlocks 补高亮与复制按钮 -->
3
+ <div ref="bodyEl" class="md-body" v-html="html"></div>
4
+ </template>
5
+
6
+ <script>
7
+ import { renderMarkdown, enhanceCodeBlocks, resetCodeHighlight } from '../runtime/markdown.js'
8
+
9
+ export default {
10
+ name: 'MarkdownBody',
11
+ props: {
12
+ /** Markdown 原文(流式时为「到目前为止」的完整文本) */
13
+ source: { type: String, default: '' },
14
+ /** 是否仍在流式输出:为真时用 rAF 合并重渲染,并允许代码块反复重刷高亮 */
15
+ streaming: { type: Boolean, default: false },
16
+ },
17
+ data() {
18
+ return { html: '', _raf: 0 }
19
+ },
20
+ watch: {
21
+ source: {
22
+ immediate: true,
23
+ handler() {
24
+ this.scheduleRender()
25
+ },
26
+ },
27
+ streaming(val) {
28
+ // 流结束:立即补一次完整渲染(含未高亮完的代码块)
29
+ if (!val) this.renderNow()
30
+ },
31
+ },
32
+ beforeUnmount() {
33
+ if (this._raf) cancelAnimationFrame(this._raf)
34
+ this._raf = 0
35
+ },
36
+ methods: {
37
+ scheduleRender() {
38
+ if (!this.streaming) {
39
+ this.renderNow()
40
+ return
41
+ }
42
+ if (this._raf) return
43
+ this._raf = requestAnimationFrame(() => {
44
+ this._raf = 0
45
+ this.renderNow()
46
+ })
47
+ },
48
+ renderNow() {
49
+ if (this._raf) {
50
+ cancelAnimationFrame(this._raf)
51
+ this._raf = 0
52
+ }
53
+ this.html = renderMarkdown(this.source)
54
+ this.$nextTick(() => {
55
+ const el = this.$refs.bodyEl
56
+ if (!el) return
57
+ // 文本变了 → 旧高亮结果作废,重新上色(enhanceCodeBlocks 只处理未标记的块)
58
+ resetCodeHighlight(el)
59
+ enhanceCodeBlocks(el)
60
+ })
61
+ },
62
+ },
63
+ }
64
+ </script>
@@ -0,0 +1,132 @@
1
+ <!--
2
+ 新增空白卡片弹窗:顶栏「新增空白卡片」图标按钮(网格预览旁边)触发。
3
+ 卡片 ID 必填、描述选填:ID 校验形状(字母/数字开头,含 _ -),描述 ≤200 字,留空则由后端用 ID 兜显示名;
4
+ ID 重名做前置判定(父级传 existing-ids = 实时扫描 src/cards 的本地卡片):撞上就红字提示并禁用「创建」,
5
+ 不必等后端 409 才知道;后端仍是权威闸(列表可能过期、macOS 文件系统不区分大小写)。
6
+ 确认后 POST /__cards 由后端写空骨架(schema + 派生 data)到 src/cards/<id>/。
7
+ 失败(ID 已存在 / 校验不过 / 服务报错)原地红字保留弹窗;成功 emit created(id),
8
+ 父级关弹窗 + 刷列表 + 切换到新卡。
9
+ 骨架与「编辑变量」弹窗同构(ni-overlay / ni-panel / ni-head / ni-foot),视觉语言统一。
10
+ -->
11
+ <template>
12
+ <transition name="modal">
13
+ <div v-if="visible" class="ni-overlay" @click.self="$emit('close')">
14
+ <div class="ni-panel modal-card newcard-dlg" role="alertdialog" aria-modal="true" aria-label="新增空白卡片">
15
+ <div class="ni-head">
16
+ <span class="ni-title">新增空白卡片</span>
17
+ <button class="ni-close" type="button" title="关闭" @click="$emit('close')"></button>
18
+ </div>
19
+ <div class="ni-body">
20
+ <div class="ni-scroll">
21
+ <div class="ni-field-row">
22
+ <label class="ni-field-label"><i>*</i>卡片 ID</label>
23
+ <input
24
+ class="ni-input"
25
+ :class="{ 'newcard-dlg__input--dup': !!dupId }"
26
+ type="text"
27
+ v-model="id"
28
+ placeholder="英文标识,如 myNewCard(字母/数字/_/-)"
29
+ :aria-invalid="dupId ? 'true' : null"
30
+ :disabled="busy"
31
+ @keydown.enter="submit"
32
+ />
33
+ </div>
34
+ <div class="ni-field-row">
35
+ <label class="ni-field-label">卡片描述</label>
36
+ <input
37
+ class="ni-input"
38
+ type="text"
39
+ v-model="desc"
40
+ placeholder="选填,卡片用途简述;留空则用卡片 ID 作显示名"
41
+ :disabled="busy"
42
+ @keydown.enter="submit"
43
+ />
44
+ </div>
45
+ <p v-if="dupId" class="newcard-dlg__err" role="alert">卡片 ID 已存在:本地已有「{{ dupId }}」,换一个 ID</p>
46
+ <p v-else-if="error" class="newcard-dlg__err" role="alert">{{ error }}</p>
47
+ </div>
48
+ </div>
49
+ <div class="ni-foot">
50
+ <span class="ni-tip">创建后写入 src/cards/&lt;id&gt;/ 空骨架,并切换到新卡</span>
51
+ <div class="ni-foot-btns">
52
+ <button class="ni-btn ni-btn--ghost" type="button" :disabled="busy" @click="$emit('close')">取消</button>
53
+ <button class="ni-btn" type="button" :disabled="busy || !!dupId" @click="submit">{{ busy ? '创建中…' : '创建' }}</button>
54
+ </div>
55
+ </div>
56
+ </div>
57
+ </div>
58
+ </transition>
59
+ </template>
60
+
61
+ <script>
62
+ import { apiFetch } from '@/api.js'
63
+
64
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/
65
+
66
+ export default {
67
+ name: 'NewCardDialog',
68
+ props: {
69
+ visible: { type: Boolean, default: false },
70
+ /** 本地已有卡片 ID(父级实时拉 GET /__cards):用于 ID 重名前置判定 */
71
+ existingIds: { type: Array, default: () => [] },
72
+ },
73
+ emits: ['close', 'created'],
74
+ data() {
75
+ return { id: '', desc: '', error: '', busy: false }
76
+ },
77
+ computed: {
78
+ /** 与本地卡片撞名的 ID(未撞返回空串):输入即时判定,不等提交 */
79
+ dupId() {
80
+ const id = this.id.trim()
81
+ if (!id) return ''
82
+ return this.existingIds.find((x) => x === id) || ''
83
+ },
84
+ },
85
+ watch: {
86
+ // 每次打开重置:上一次的失败错误 / 半截输入不带进新会话
87
+ visible(v) {
88
+ if (v) {
89
+ this.id = ''
90
+ this.desc = ''
91
+ this.error = ''
92
+ this.busy = false
93
+ }
94
+ },
95
+ },
96
+ methods: {
97
+ validate() {
98
+ const id = this.id.trim()
99
+ const desc = this.desc.trim()
100
+ if (!id) return '卡片 ID 必填'
101
+ if (!ID_RE.test(id)) return '卡片 ID 只能以字母/数字开头,含字母/数字/_/-(≤64 字符)'
102
+ if (this.dupId) return `卡片 ID 已存在:本地已有「${this.dupId}」,换一个 ID`
103
+ if (desc.length > 200) return '卡片描述过长(≤200 字)'
104
+ return ''
105
+ },
106
+ async submit() {
107
+ if (this.busy) return
108
+ const err = this.validate()
109
+ if (err) {
110
+ this.error = err
111
+ return
112
+ }
113
+ this.busy = true
114
+ this.error = ''
115
+ try {
116
+ const res = await apiFetch('/__cards', {
117
+ method: 'POST',
118
+ headers: { 'Content-Type': 'application/json' },
119
+ body: JSON.stringify({ id: this.id.trim(), desc: this.desc.trim() }),
120
+ })
121
+ const r = await res.json().catch(() => null)
122
+ if (!res.ok) throw new Error((r && (r.message || r.error)) || `HTTP ${res.status}`)
123
+ this.$emit('created', this.id.trim())
124
+ } catch (e) {
125
+ this.error = `创建失败:${e.message}`
126
+ } finally {
127
+ this.busy = false
128
+ }
129
+ },
130
+ },
131
+ }
132
+ </script>
@@ -0,0 +1,125 @@
1
+ <!--
2
+ 数字步进输入框:[−] 输入框 [+]。
3
+
4
+ 与 setters/SetNumber.vue 的分工:SetNumber 复刻编辑器 common/InputNumber(方向键步进 + 单位后缀 +
5
+ 预设值浮层),本组件只做「显式 − / + 按钮 + 直接键入」,用于变量默认值这类需要一眼看到步进入口、
6
+ 又不带单位 / 预设的表单场景。方向键上下同样可步进,键盘与鼠标两条路都在。
7
+
8
+ 外壳直接复用 setters.css 的 .st-number 家族(同一 28px 高、同一底色 / 边框 / 发丝线附属件语言),
9
+ 只新增 − / + 按钮这一种附属件,不另起一套样式。
10
+
11
+ 约定沿用 setter 家族:value 进、input 出,且**文本原样**上抛(组件内不转数字),由调用方决定解析口径;
12
+ 非法字符当场回滚,因此不产生需要额外报错文案的中间态。
13
+ -->
14
+ <template>
15
+ <div class="st-number st-number--step">
16
+ <button
17
+ type="button"
18
+ class="st-number__step"
19
+ title="减少"
20
+ aria-label="减少"
21
+ :disabled="disabled || !canStep(-1)"
22
+ @click="bump(-1)"
23
+ >
24
+ <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
25
+ <line x1="3.5" y1="8" x2="12.5" y2="8" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
26
+ </svg>
27
+ </button>
28
+ <input
29
+ ref="field"
30
+ class="st-number__field"
31
+ type="text"
32
+ inputmode="decimal"
33
+ :value="text"
34
+ :placeholder="placeholder"
35
+ :disabled="disabled"
36
+ @input="onInput($event.target.value)"
37
+ @change="$emit('change')"
38
+ @keydown.up.prevent="bump(1)"
39
+ @keydown.down.prevent="bump(-1)"
40
+ />
41
+ <button
42
+ type="button"
43
+ class="st-number__step st-number__step--inc"
44
+ title="增加"
45
+ aria-label="增加"
46
+ :disabled="disabled || !canStep(1)"
47
+ @click="bump(1)"
48
+ >
49
+ <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
50
+ <path d="M8 3.5v9M3.5 8h9" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" />
51
+ </svg>
52
+ </button>
53
+ </div>
54
+ </template>
55
+
56
+ <script>
57
+ /** 允许键入的数字字面量:空串 / 负号 / 整数 / 小数(含 "12." ".5" 这类输入中间态) */
58
+ const NUM_TEXT = /^-?(?:\d+(?:\.\d*)?|\.\d*)?$/
59
+
60
+ export default {
61
+ name: 'NumberStepper',
62
+ props: {
63
+ value: { type: [String, Number], default: '' },
64
+ /** 步长,支持小数(如 0.1);非正数或非数值回落 1 */
65
+ step: { type: Number, default: 1 },
66
+ min: { type: Number, default: -Infinity },
67
+ max: { type: Number, default: Infinity },
68
+ placeholder: { type: String, default: '请输入数字' },
69
+ disabled: { type: Boolean, default: false },
70
+ },
71
+ emits: ['input', 'change'],
72
+ data() {
73
+ return { text: '' }
74
+ },
75
+ computed: {
76
+ stepSize() {
77
+ return Number.isFinite(this.step) && this.step > 0 ? this.step : 1
78
+ },
79
+ /** 当前文本对应的数值;空串或 "-" 这类未成形的输入为 null */
80
+ num() {
81
+ const n = parseFloat(this.text)
82
+ return Number.isFinite(n) ? n : null
83
+ },
84
+ },
85
+ watch: {
86
+ value: {
87
+ immediate: true,
88
+ handler(v) {
89
+ const next = v === undefined || v === null ? '' : String(v)
90
+ if (next !== this.text) this.text = next
91
+ },
92
+ },
93
+ },
94
+ methods: {
95
+ /** 越界后按钮置灰:未设边界(±Infinity)时始终可点 */
96
+ canStep(dir) {
97
+ const base = this.num === null ? 0 : this.num
98
+ return dir > 0 ? base < this.max : base > this.min
99
+ },
100
+ /** 消掉二进制浮点噪声(0.1 + 0.2 → 0.30000000000000004) */
101
+ tidy(n) {
102
+ return Number(n.toPrecision(12))
103
+ },
104
+ clamp(n) {
105
+ return Math.min(this.max, Math.max(this.min, n))
106
+ },
107
+ onInput(v) {
108
+ if (!NUM_TEXT.test(v)) {
109
+ // 非法按键丢弃并回滚显示(与 SetNumber 同一手法):绑定的 text 未变,需手动写回 DOM
110
+ this.$refs.field.value = this.text
111
+ return
112
+ }
113
+ this.text = v
114
+ this.$emit('input', v)
115
+ },
116
+ bump(dir) {
117
+ if (this.disabled) return
118
+ const base = this.num === null ? 0 : this.num
119
+ this.text = String(this.clamp(this.tidy(base + dir * this.stepSize)))
120
+ this.$emit('input', this.text)
121
+ this.$emit('change')
122
+ },
123
+ },
124
+ }
125
+ </script>
@@ -53,7 +53,15 @@ export default {
53
53
  rootStyle() {
54
54
  // 注意:滑块根不裁切自身内容。滑块块在 0%/100% 时会落在轨道端点、且
55
55
  // 按下时整体放大 1.2×,若这里 overflow:hidden 会把块裁掉。
56
- return { height: 'auto', boxSizing: 'border-box' }
56
+ // 节点高度下限:不得小于轨道(processHeight + 上下内置 8px 外边距)与滑块块
57
+ // (blockHeight)高度,避免节点被布局压缩(flex shrink / 定高父容器)后轨道 / 滑块块溢出裁切。
58
+ const trackH = (Number(this.processHeight) || 5) + 16
59
+ const blockH = Number(this.blockHeight) || 15
60
+ return {
61
+ height: 'auto',
62
+ minHeight: this.adapter.doSize(Math.max(trackH, blockH)),
63
+ boxSizing: 'border-box',
64
+ }
57
65
  },
58
66
  min() {
59
67
  const n = Number(this.minProgress)
@@ -81,7 +81,7 @@ export default {
81
81
  methods: {
82
82
  buildSocket(cardId) {
83
83
  // 对应 ubomp config/uat.env.js:CARD_WEBSOCKET = wss://<host>/pmb-web
84
- // 域名不硬编码:从 .env.finmall 的 FINMALL_BASE_URL 经 vite 暴露到
84
+ // 域名不硬编码:从 .env.cb 的 FINMALL_BASE_URL 经 vite 暴露到
85
85
  // import.meta.env 读取(默认 UAT 域名),部署到其他环境时改配置即可。
86
86
  const base = import.meta.env.FINMALL_BASE_URL || 'https://uat-pkg.finmall.com'
87
87
  const wsHost = base.replace(/^https?:/, 'wss:')
@@ -8,7 +8,7 @@
8
8
  <template>
9
9
  <div class="st">
10
10
  <!--
11
- 顶部工具条:与数据绑定 tab JsonTree 的 .jt__toolbar 同款
11
+ 顶部工具条:与变量 mock 视图 JsonTree 的 .jt__toolbar 同款
12
12
  (sticky 顶部 + .jt__tool 按钮风格),保持两个 tab 操作入口一致。
13
13
  -->
14
14
  <div class="st__toolbar st__toolbar--top">
@@ -40,7 +40,7 @@
40
40
  title="按组件名 / 类型 / 实例ID 过滤结构树"
41
41
  />
42
42
  <!--
43
- 顶部「+ 添加」按钮:与数据绑定 tab(JsonTree)工具栏右侧的「+ 添加」同款,
43
+ 顶部「+ 添加」按钮:与变量 mock 视图(JsonTree)工具栏右侧的「+ 添加」同款,
44
44
  位于面板右上角。插入锚点由「当前选中节点」决定(未选中→根;容器→末尾子节点;
45
45
  非容器→其后兄弟),与线上编辑器「卡片-组件」面板行为一致。
46
46
  -->
@@ -13,6 +13,7 @@ import './styles/structure-tree.css'
13
13
  import './styles/node-inspector.css'
14
14
  import './styles/dropdown.css'
15
15
  import './styles/setters.css'
16
+ import './styles/ai-chat.css'
16
17
 
17
18
  import PropControl from './components/PropControl.vue'
18
19
  import PropTree from './components/PropTree.vue'
@@ -25,7 +25,7 @@ export const URL_PREFIX_ALIAS = {
25
25
  * 卡片 data.json 里有不少写死的完整 CDN 地址,直接请求会跨域也吃不到本地缓存。
26
26
  * 统一改写成同源路径,交给 vite 的资源代理中间件。
27
27
  *
28
- * 域名不硬编码:从 .env.finmall 的 FINMALL_BASE_URL 读取(vite 以
28
+ * 域名不硬编码:从 .env.cb 的 FINMALL_BASE_URL 读取(vite 以
29
29
  * envPrefix FINMALL_ 暴露到 import.meta.env),未配置时回退 UAT 域名。
30
30
  */
31
31
  const BASE_URL = import.meta.env.FINMALL_BASE_URL || 'https://uat-pkg.finmall.com'
@@ -0,0 +1,165 @@
1
+ /**
2
+ * AI 开发助手与本地服务(cardbuddy /__ai/*)的前端 API 层。
3
+ *
4
+ * 统一走 preview/api.js 的 apiFetch:自动拼接 apiBase(dev 直连 8787 / 部署态读设置 /
5
+ * 非回环主机走同源代理),并附带可选 x-dev-token。图片预览这类 <img src> 无法带自定义头,
6
+ * 故单独用 aiFileUrl() 拼绝对地址(本地服务默认无 token,行为一致)。
7
+ *
8
+ * 本地文件挂载原则:文件不上传,只在面板内预览 + 把「本机绝对路径」交给模型;
9
+ * 浏览器出于安全拿不到拖入文件的绝对路径,故有 locate(按名字+大小反查)与
10
+ * stash(剪贴板截图落盘到 .cache/ai-attachments/)两条兜底链路。
11
+ */
12
+ import { apiFetch, resolveApiBase } from '../api.js'
13
+
14
+ /** 图片预览地址(后端按路径直出本机文件,不落库不外传) */
15
+ export function aiFileUrl(absPath) {
16
+ const base = resolveApiBase() || ''
17
+ return `${base}/__ai/fs/raw?path=${encodeURIComponent(absPath)}`
18
+ }
19
+
20
+ async function jsonOrThrow(resp) {
21
+ const data = await resp.json().catch(() => ({}))
22
+ if (!resp.ok) {
23
+ // /__ai/* 上 404/405 几乎都是本地服务还跑着改造前的旧代码:直接给可操作提示,别只吐裸状态码
24
+ let pathname = ''
25
+ try {
26
+ pathname = new URL(resp.url).pathname
27
+ } catch {
28
+ /* resp.url 异常时退化为裸状态码提示 */
29
+ }
30
+ const stale = (resp.status === 404 || resp.status === 405) && pathname.startsWith('/__ai/')
31
+ const msg = stale
32
+ ? '本地开发服务仍在运行改造前的旧代码(缺少该接口),请重启 npm run dev(cardbuddy)后重试'
33
+ : (data.message || data.error || `HTTP ${resp.status}`)
34
+ const err = new Error(msg)
35
+ err.code = data.error
36
+ err.payload = data
37
+ throw err
38
+ }
39
+ return data
40
+ }
41
+
42
+ /** 读取模型配置(默认脱敏:hasKey / apiKeyMasked;reveal=true 附明文 apiKey 供设置面板回显,仅回环来源可调) */
43
+ export async function fetchAiConfig(reveal = false) {
44
+ return jsonOrThrow(await apiFetch(`/__ai/config${reveal ? '?reveal=1' : ''}`))
45
+ }
46
+
47
+ /** 保存模型配置(写入 .env.cb.local,个人覆盖层,不入库) */
48
+ export async function saveAiConfig(form) {
49
+ return jsonOrThrow(await apiFetch('/__ai/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) }))
50
+ }
51
+
52
+ /** 连通性自测:返回 { ok, latencyMs, message?, model? } */
53
+ /** 探测网关「单次输出上限」窗口(models 元数据优先,缺失则二分试探) */
54
+ export async function probeMaxTokens() {
55
+ return jsonOrThrow(await apiFetch('/__ai/probe-maxtokens', { method: 'POST' }))
56
+ }
57
+
58
+ export async function pingAi(form) {
59
+ return jsonOrThrow(await apiFetch('/__ai/ping', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) }))
60
+ }
61
+
62
+ /** 调起系统选择器(macOS):kind = image | file | folder */
63
+ export async function pickLocalPaths(kind = 'image') {
64
+ return jsonOrThrow(await apiFetch('/__ai/fs/pick', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind, multiple: true }) }))
65
+ }
66
+
67
+ /** 路径元信息(文件 / 文件夹浅层清单) */
68
+ export async function statLocalPath(absPath) {
69
+ return jsonOrThrow(await apiFetch(`/__ai/fs/stat?path=${encodeURIComponent(absPath)}`))
70
+ }
71
+
72
+ /** 拖拽落点反查绝对路径(浏览器 File 无 path,用名字 + 大小在常用根目录里找唯一匹配) */
73
+ export async function locateDroppedFile({ name, relPath, size }) {
74
+ return jsonOrThrow(await apiFetch('/__ai/fs/locate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, relPath, size }) }))
75
+ }
76
+
77
+ /** 剪贴板截图落盘为本机文件,返回与 stat 同构的元信息 */
78
+ export async function stashPastedImage(dataUrl) {
79
+ return jsonOrThrow(await apiFetch('/__ai/fs/stash', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ dataUrl }) }))
80
+ }
81
+
82
+ /**
83
+ * 对话内审批回落:skill_exec / shell_exec 的「允许一次 / 本回合不再询问 / 拒绝」。
84
+ * scope='turn' 时后端在本轮请求内记住该工具已授权,管线连跑多步不必逐步点确认。
85
+ */
86
+ export async function approveToolCall({ approvalId, ok, scope = 'once' }) {
87
+ return jsonOrThrow(await apiFetch('/__ai/approve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ approvalId, ok, scope }) }))
88
+ }
89
+
90
+ /** 读取按卡片保存的对话记录 */
91
+ export async function loadChatHistory(cardId) {
92
+ if (!cardId) return { cardId: '', messages: [], updatedAt: 0 }
93
+ return jsonOrThrow(await apiFetch(`/__ai/history?cardId=${encodeURIComponent(cardId)}`))
94
+ }
95
+
96
+ /** 保存对话记录(后端裁剪到最近 200 条) */
97
+ export async function saveChatHistory(cardId, messages) {
98
+ if (!cardId) return { ok: false, error: 'missing-card-id' }
99
+ return jsonOrThrow(await apiFetch('/__ai/history', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cardId, messages }) }))
100
+ }
101
+
102
+ /** 清除某张卡片的对话记录 */
103
+ export async function clearChatHistory(cardId) {
104
+ if (!cardId) return { ok: false, error: 'missing-card-id' }
105
+ return jsonOrThrow(await apiFetch(`/__ai/history?cardId=${encodeURIComponent(cardId)}`, { method: 'DELETE' }))
106
+ }
107
+
108
+ /** 本地服务是否可用(部署态未配置 → null) */
109
+ export function aiServiceAvailable() {
110
+ return resolveApiBase() !== null
111
+ }
112
+
113
+ /**
114
+ * 流式对话:POST /__ai/chat,逐事件回调。
115
+ * @param {{ messages:any[], cardContext?:{id:string}, attachments?:any[], config?:object, signal?:AbortSignal, onEvent:(e:object)=>void }} opts
116
+ */
117
+ export async function streamChat({ messages, cardContext, attachments = [], config = {}, signal, onEvent }) {
118
+ const resp = await apiFetch('/__ai/chat', {
119
+ method: 'POST',
120
+ headers: { 'Content-Type': 'application/json' },
121
+ body: JSON.stringify({ messages, cardContext, attachments, config }),
122
+ signal,
123
+ })
124
+ if (!resp.ok || !resp.body) {
125
+ const detail = await resp.json().catch(() => ({}))
126
+ throw new Error(detail.message || detail.error || `HTTP ${resp.status}`)
127
+ }
128
+ const reader = resp.body.getReader()
129
+ const decoder = new TextDecoder()
130
+ let buffer = ''
131
+ const drain = (chunkText) => {
132
+ buffer += chunkText
133
+ const lines = buffer.split('\n')
134
+ buffer = lines.pop() || ''
135
+ for (const line of lines) {
136
+ const trimmed = line.trim()
137
+ if (!trimmed.startsWith('data:')) continue
138
+ const payload = trimmed.slice(5).trim()
139
+ if (!payload) continue
140
+ let evt
141
+ try {
142
+ evt = JSON.parse(payload)
143
+ } catch {
144
+ continue // 半截 JSON:等下一个 chunk 拼齐
145
+ }
146
+ onEvent(evt)
147
+ if (evt.type === 'done') return true
148
+ }
149
+ return false
150
+ }
151
+ try {
152
+ while (true) {
153
+ const { done, value } = await reader.read()
154
+ if (done) break
155
+ if (drain(decoder.decode(value, { stream: true }))) break
156
+ }
157
+ drain(decoder.decode())
158
+ } finally {
159
+ try {
160
+ reader.releaseLock?.()
161
+ } catch {
162
+ /* 已中止时忽略 */
163
+ }
164
+ }
165
+ }
@@ -40,11 +40,6 @@ export function setClipboardNode(schemaNode, sourceCardId = null) {
40
40
  nodeClipboard.sourceCardId = sourceCardId || null
41
41
  }
42
42
 
43
- export function clearClipboard() {
44
- nodeClipboard.node = null
45
- nodeClipboard.sourceCardId = null
46
- }
47
-
48
43
  /**
49
44
  * 递归收集子树中所有节点的 className(去重),用于跨卡片粘贴前的兼容性校验。
50
45
  * @param {Object} node schema 节点