dsh-gufa-code 1.3.116 → 1.3.118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,7 +41,8 @@ dsh plugin add dsh-gufa-code
41
41
  - Monaco 编辑器(离线随包分发,无需联网下载);Monaco 自带 81 种语言全部映射(ABAP、Apex、Clojure、Elixir、F#、GraphQL、HCL/Terraform、Julia、Objective-C、Pascal、Perl、Protobuf、R、RST、Scheme、Solidity、SystemVerilog/Verilog、Tcl、TypeSpec、VB、WGSL、Bicep、Batch、CoffeeScript、Cypher、DAX、Logstash/ECL、MIPS、Power Query、Q#、Redis、SPARQL、Structured Text、Modula-3、ATS、Pony 系列等);
42
42
  - **HTML 模板语法高亮**:EJS / Eta、ERB、Nunjucks / Jinja2(`.njk/.nunjucks/.jinja/.jinja2/.j2`)、Blade(`.blade.php`)、Haml、Slim,以及 Monaco 内置的 Handlebars / Mustache / Pug / Twig / Liquid / Razor / FreeMarker;扩展名自动识别;
43
43
  - 多标签、按扩展名语法高亮、面包屑、状态栏(分支 / 行列 / 保存状态);
44
- - **AI Tab 行内补全已默认关闭**:实测结果质量不稳定、且请求会增加输入延迟;基础代码联想(Monaco 建议列表)保持开启;
44
+ - **JS/TS 实时诊断**:Host 侧用 TypeScript 编译器分析当前编辑内容(含未保存改动),语法错误、未定义变量以下划线/波浪线标出,并计入问题面板;动态 JS/JSON 项目里容易误报的属性类型错误默认不展示;Monaco 的自动缩进/括号引号自动闭合保持开启;
45
+ - **AI Tab 行内补全已移除**(结果质量不稳定且增加输入延迟);基础代码联想(Monaco 建议列表 / 当前文档单词)保持开启;
45
46
  - **AI/外部修改自动刷新**:已打开的标签每 1.6s 检查一次磁盘 mtime/size,AI 在会话里改完代码后编辑器自动换成新内容(保留光标位置),不需要关闭重开;点击文件树里的已打开文件也会重新对齐磁盘;有未保存修改时不会覆盖用户内容;
46
47
  - 保存走磁盘版本冲突检测 + 原子写;未保存标记;
47
48
  - **⌘/Ctrl + 点击跳转定义 / 方法实现**:Python 走 **Pyright 语言服务(LSP)**,JS/TS 走 Monaco 内置 TypeScript 语言服务(点击前会按需把当前文件的 import 依赖加载进 Monaco,跨文件变量/函数由 TS 语言服务解析);其他语言暂用项目级定义搜索兜底;优先走 Monaco 语言服务;目标文件没在 Monaco 里打开、或语言没有内置语言服务时,自动用项目级定义搜索兜底(函数 / 类 / 方法 / const / type 等声明)。兜底会解析 import/require 直接定位来源文件,并跳过压缩产物/大文件;同一个文件里的声明、import 命中的定义、目录距离近的定义直接跳,只有多个真正同名的声明才弹「跳转到定义」列表,点同名属性/变量时不会拿远端无关的 const 来凑数;按住 ⌘/Ctrl 悬停时,可跳转的符号会显示下划线 + 手型光标;
package/client.js CHANGED
@@ -16,7 +16,7 @@ const GUFA_NS = 'gufa-code'
16
16
  const G = {}
17
17
  G.NS = GUFA_NS
18
18
  /** 客户端构建标记(排查页面是否加载了新代码时看标题栏) */
19
- G.BUILD = '1.3.116'
19
+ G.BUILD = '1.3.118'
20
20
  G.PANEL_ID = 'gufa-code'
21
21
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
22
22
  G.pendingEntryWorkspace = null
@@ -3097,6 +3097,9 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3097
3097
  lineHeight: 20,
3098
3098
  fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',
3099
3099
  autoIndent: 'full',
3100
+ autoClosingBrackets: 'languageDefined',
3101
+ autoClosingQuotes: 'languageDefined',
3102
+ autoSurround: 'languageDefined',
3100
3103
  detectIndentation: true,
3101
3104
  tabSize: 2,
3102
3105
  insertSpaces: true,
@@ -3114,7 +3117,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3114
3117
  wordBasedSuggestions: 'currentDocument',
3115
3118
  acceptSuggestionOnEnter: 'on',
3116
3119
  tabCompletion: 'on',
3117
- inlineSuggest: { enabled: false, showToolbar: 'never' },
3118
3120
  }
3119
3121
  }
3120
3122
 
@@ -3361,6 +3363,16 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3361
3363
  } catch (error) {
3362
3364
  /* 模板语言注册失败不影响编辑器 */
3363
3365
  }
3366
+ /* 诊断改由 Host 的 TypeScript 编译器提供(dsh-app worker 不可靠),
3367
+ 关闭 Monaco worker 诊断避免重复/后台报错;补全建议仍由 worker 提供。 */
3368
+ try {
3369
+ const typescriptLanguages = monaco.languages.typescript
3370
+ const diagnosticsOff = { noSemanticValidation: true, noSyntaxValidation: true }
3371
+ typescriptLanguages?.typescriptDefaults?.setDiagnosticsOptions(diagnosticsOff)
3372
+ typescriptLanguages?.javascriptDefaults?.setDiagnosticsOptions(diagnosticsOff)
3373
+ } catch (error) {
3374
+ /* ignore */
3375
+ }
3364
3376
  try {
3365
3377
  const instance = monaco.editor.create(host, gufaEditorOptions(propsRef.current.theme))
3366
3378
  editor = instance
@@ -3777,134 +3789,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3777
3789
  } catch {
3778
3790
  /* ignore */
3779
3791
  }
3780
- /* ── Copilot 风格 Tab 行内补全(复用 Harness 模型服务) ───────── */
3781
- try {
3782
- if (typeof monaco.languages.registerInlineCompletionsProvider === 'function') {
3783
- const inlineLanguages = ['python', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact', 'java', 'go', 'rust', 'csharp', 'cpp', 'c', 'shell', 'json', 'yaml', 'sql', 'html', 'css']
3784
- const inlineCache = new Map()
3785
- let inlineLastRequestAt = 0
3786
- const inlineProvider = {
3787
- provideInlineCompletions(model, position, context, token) {
3788
- /* AI Tab 补全已默认关闭:结果质量差、且每次请求会增加延迟。
3789
- 需要重新开启时把此处的 return 去掉,并把 inlineSuggest.enabled 改回 true。 */
3790
- return Promise.resolve({ items: [] })
3791
- // eslint-disable-next-line no-unreachable
3792
- const path = modelPathRef.current
3793
- const root = modelsRootRef.current
3794
- if (path === null || path === undefined || root === null || root === undefined || root === '') {
3795
- return Promise.resolve({ items: [] })
3796
- }
3797
- if (token !== null && token !== undefined && token.isCancellationRequested === true) return Promise.resolve({ items: [] })
3798
- return new Promise((resolve) => {
3799
- let settled = false
3800
- const finish = (value) => {
3801
- if (settled) return
3802
- settled = true
3803
- resolve(value)
3804
- }
3805
- const timer = window.setTimeout(() => {
3806
- void (async () => {
3807
- try {
3808
- if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
3809
- const now = Date.now()
3810
- if (now - inlineLastRequestAt < 500) return finish({ items: [] })
3811
- inlineLastRequestAt = now
3812
- const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
3813
- if (!inlineLanguages.includes(language)) return finish({ items: [] })
3814
- const lineCount = model.getLineCount()
3815
- const startLine = Math.max(1, position.lineNumber - 140)
3816
- const endLine = Math.min(lineCount, position.lineNumber + 30)
3817
- const endColumn = model.getLineMaxColumn(endLine)
3818
- let prefix = ''
3819
- let suffix = ''
3820
- try {
3821
- prefix = model.getValueInRange(new monaco.Range(startLine, 1, position.lineNumber, position.column)).slice(-3200)
3822
- suffix = model.getValueInRange(new monaco.Range(position.lineNumber, position.column, endLine, endColumn)).slice(0, 800)
3823
- } catch {
3824
- return finish({ items: [] })
3825
- }
3826
- const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
3827
- const cacheKey = `${path}|${version}|${position.lineNumber}:${position.column}|${language}`
3828
- const cached = inlineCache.get(cacheKey)
3829
- if (cached !== undefined) return finish(cached)
3830
- const value = await G.api('completion.suggest', { root, path, language, prefix, suffix })
3831
- if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
3832
- const text = value !== null && value !== undefined && typeof value.text === 'string' ? value.text : ''
3833
- const result = text === ''
3834
- ? { items: [] }
3835
- : { items: [{ insertText: text, range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column) }] }
3836
- if (inlineCache.size > 30) inlineCache.clear()
3837
- inlineCache.set(cacheKey, result)
3838
- finish(result)
3839
- } catch {
3840
- finish({ items: [] })
3841
- }
3842
- })()
3843
- }, 260)
3844
- if (token !== null && token !== undefined && typeof token.onCancellationRequested === 'function') {
3845
- token.onCancellationRequested(() => {
3846
- window.clearTimeout(timer)
3847
- finish({ items: [] })
3848
- })
3849
- }
3850
- })
3851
- },
3852
- freeInlineCompletions() {},
3853
- }
3854
- const inlineDisposable = monaco.languages.registerInlineCompletionsProvider(inlineLanguages, inlineProvider)
3855
- if (inlineDisposable !== null && inlineDisposable !== undefined && typeof inlineDisposable.dispose === 'function') subscriptions.push(inlineDisposable)
3856
- }
3857
- } catch {
3858
- /* ignore */
3859
- }
3860
-
3861
- /* 外部/AI 修改磁盘后由 App 轮询发现,通过 bus 通知编辑器热替换 model 内容 */
3862
- try {
3863
- if (G.bus !== null && G.bus !== undefined && typeof G.bus.on === 'function') {
3864
- const offExternalReload = G.bus.on('editor:external-reload', (detail) => {
3865
- if (detail === null || detail === undefined || typeof detail.path !== 'string' || typeof detail.content !== 'string') return
3866
- const target = modelsRef.current.get(detail.path)
3867
- if (target === null || target === undefined) return
3868
- let content = ''
3869
- try {
3870
- content = target.getValue()
3871
- } catch {
3872
- return
3873
- }
3874
- if (content === detail.content) return
3875
- const active = modelPathRef.current === detail.path
3876
- let position = null
3877
- let scrollTop = 0
3878
- if (active) {
3879
- try {
3880
- position = instance.getPosition()
3881
- scrollTop = instance.getScrollTop()
3882
- } catch {
3883
- position = null
3884
- }
3885
- }
3886
- suppressChangeRef.current = true
3887
- try {
3888
- target.setValue(detail.content)
3889
- } finally {
3890
- suppressChangeRef.current = false
3891
- }
3892
- lastPropContentRef.current.set(detail.path, detail.content)
3893
- if (active && position !== null && position !== undefined) {
3894
- try {
3895
- instance.setPosition(position)
3896
- instance.setScrollTop(scrollTop)
3897
- } catch {
3898
- /* ignore */
3899
- }
3900
- }
3901
- })
3902
- if (typeof offExternalReload === 'function') subscriptions.push({ dispose: offExternalReload })
3903
- }
3904
- } catch {
3905
- /* ignore */
3906
- }
3907
-
3908
3792
  G.__gufaEditorDebug = {
3909
3793
  focus: () => {
3910
3794
  try {
@@ -3961,6 +3845,84 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
3961
3845
  }))
3962
3846
  /* 光标 / 选区变化上报(状态栏行号列、AI 上下文选区)。 */
3963
3847
  subscriptions.push(instance.onDidChangeCursorSelection(() => reportCursor()))
3848
+ /* ── JS/TS 诊断(Host 侧 tsc):语法错误 / 未定义变量 / 类型错误 ── */
3849
+ const lintTimers = new Map()
3850
+ const clearLintTimers = () => {
3851
+ for (const timer of lintTimers.values()) window.clearTimeout(timer)
3852
+ lintTimers.clear()
3853
+ }
3854
+ const runLint = async (model, path) => {
3855
+ if (model === null || model === undefined || typeof path !== 'string' || path === '') return
3856
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
3857
+ if (language !== 'javascript' && language !== 'typescript') return
3858
+ const root = modelsRootRef.current
3859
+ if (root === null || root === undefined || root === '') return
3860
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
3861
+ let result = null
3862
+ try {
3863
+ result = await G.api('lint.javascript', { root, path, language, content: model.getValue() })
3864
+ } catch {
3865
+ return
3866
+ }
3867
+ try {
3868
+ if (typeof model.isDisposed === 'function' && model.isDisposed() === true) return
3869
+ if (typeof model.getVersionId === 'function' && model.getVersionId() !== version) return
3870
+ const list = result !== null && result !== undefined && Array.isArray(result.diagnostics) ? result.diagnostics : []
3871
+ const markerList = []
3872
+ for (const item of list.slice(0, 200)) {
3873
+ if (item === null || typeof item !== 'object') continue
3874
+ const severity = Number(item.severity)
3875
+ markerList.push({
3876
+ severity: severity === 1 ? monaco.MarkerSeverity.Error : (severity === 0 ? monaco.MarkerSeverity.Warning : monaco.MarkerSeverity.Info),
3877
+ message: String(item.message ?? ''),
3878
+ startLineNumber: Number(item.line) || 1,
3879
+ startColumn: Number(item.column) || 1,
3880
+ endLineNumber: Number(item.endLine ?? item.line) || 1,
3881
+ endColumn: Number(item.endColumn ?? item.column) || 1,
3882
+ source: 'gufa-ts',
3883
+ code: String(item.code ?? ''),
3884
+ })
3885
+ }
3886
+ monaco.editor.setModelMarkers(model, 'gufa-ts', markerList)
3887
+ } catch {
3888
+ /* ignore */
3889
+ }
3890
+ }
3891
+ const scheduleLint = (model, path) => {
3892
+ if (model === null || model === undefined || typeof path !== 'string' || path === '') return
3893
+ const previous = lintTimers.get(path)
3894
+ if (previous !== undefined) window.clearTimeout(previous)
3895
+ const timer = window.setTimeout(() => {
3896
+ lintTimers.delete(path)
3897
+ void runLint(model, path)
3898
+ }, 650)
3899
+ lintTimers.set(path, timer)
3900
+ }
3901
+ subscriptions.push({ dispose: clearLintTimers })
3902
+ try {
3903
+ subscriptions.push(instance.onDidChangeModel(() => {
3904
+ const model = instance.getModel()
3905
+ const path = modelPathRef.current
3906
+ if (model !== null && model !== undefined && path !== null && path !== undefined) scheduleLint(model, path)
3907
+ }))
3908
+ } catch {
3909
+ /* ignore */
3910
+ }
3911
+ subscriptions.push(instance.onDidChangeModelContent(() => {
3912
+ const model = instance.getModel()
3913
+ const path = modelPathRef.current
3914
+ if (model !== null && model !== undefined && path !== null && path !== undefined) scheduleLint(model, path)
3915
+ }))
3916
+ try {
3917
+ const initialModel = instance.getModel()
3918
+ const initialPath = modelPathRef.current
3919
+ if (initialModel !== null && initialModel !== undefined && initialPath !== null && initialPath !== undefined) {
3920
+ window.setTimeout(() => { scheduleLint(initialModel, initialPath) }, 0)
3921
+ }
3922
+ } catch {
3923
+ /* ignore */
3924
+ }
3925
+
3964
3926
  /* 语言服务(JS/TS/JSON/CSS/HTML)诊断 → 资源管理器 / 标签页 / 状态栏 */
3965
3927
  const publishProblems = () => {
3966
3928
  if (typeof G.problemsStore?.set !== 'function') return
@@ -7,8 +7,8 @@
7
7
  <key>CFBundleDisplayName</key><string>古法编程悬浮层</string>
8
8
  <key>CFBundleExecutable</key><string>gufa-float</string>
9
9
  <key>CFBundlePackageType</key><string>APPL</string>
10
- <key>CFBundleShortVersionString</key><string>1.3.116</string>
11
- <key>CFBundleVersion</key><string>1.3.116</string>
10
+ <key>CFBundleShortVersionString</key><string>1.3.118</string>
11
+ <key>CFBundleVersion</key><string>1.3.118</string>
12
12
  <key>LSUIElement</key><true/>
13
13
  <key>NSHighResolutionCapable</key><true/>
14
14
  <key>NSPrincipalClass</key><string>NSApplication</string>
@@ -76,11 +76,19 @@
76
76
  - 正确策略(两层):`staged.length > 0` 时**只**调 `git.commit`(Host 是 `git commit -m`,只消费 index),未暂存保持不动;`staged.length === 0` 且存在改动时才自动 `git.stage` 全部再提交(快捷模式)。按钮只在没有改动或没填 message 时禁用。
77
77
  - 单测覆盖:暂存 `src/staged.ts`、保留未跟踪 `src/unstaged.ts` 后提交,断言 unstaged 文件不在 HEAD 且仍出现在 status 的未暂存列表里。
78
78
 
79
- ## 0.14 AI Tab 补全已关闭(1.3.116)
79
+ ## 0.14 AI Tab 补全已移除,改为 Host 侧 JS/TS 诊断(1.3.117)
80
80
 
81
- - 1.3.90 引入的 AI ghost text 实测结果质量不稳定、且每次停顿都会触发模型请求(约 1s),体感卡顿;用户要求先关掉。
82
- - 关闭方式:`gufaEditorOptions` 的 `inlineSuggest.enabled=false`,并且 inline provider 的 `provideInlineCompletions` 直接返回空(双保险,不再触发任何 completion.suggest 请求)。
83
- - 基础代码联想仍由 Monaco 的 `quickSuggestions / wordBasedSuggestions` 提供;Host 的 `completion.suggest` API 保留但客户端不再调用,后续想重做可复用。
81
+ - 1.3.90 引入的 AI ghost text 结果质量不稳定、每次停顿触发模型请求(约 1s)体感卡顿;用户要求直接去掉。客户端 inline provider、`inlineSuggest` 选项、Host `completion.suggest` 路由/模块均已删除。
82
+ - 诊断改由 Host 的 TypeScript 编译器提供(`host/lint.js`,依赖 `typescript@5.x`,**不要装 typescript@7**:7.x 是 native 预览,npm 包没有 JS API,`createProgram` 等全是 undefined)。
83
+ - 客户端 debounce 650ms 调 `lint.javascript`,Host 解析当前内容 + 本地 import,返回语法/语义诊断;客户端 `setModelMarkers(model,'gufa-ts',markers)`。
84
+ - 同时关闭 Monaco worker 诊断(`noSemanticValidation/noSyntaxValidation=true`),避免 dsh-app 自定义协议下 worker importScripts 失败产生重复/后台报错;补全仍由 worker 提供。
85
+ - 模块解析失败码(2307/2792 等)忽略,并注入 Node 全局 shim(process/require/module/Buffer 等),否则 JS 文件会被 `Cannot find name process` 淹没。
86
+
87
+ ## 0.15 诊断误报:只保留语法 + 未定义变量(1.3.118)
88
+
89
+ - 全量 `getSemanticDiagnostics` 在动态 JS/JSON 配置项目里误报极多:`lodash` 的 UMD 包报 2306 "File is not a module"、从 `config.json` 推断出的类型报 2339 "Property 'username' does not exist"、`node-uuid` 类型声明报 `v4` 不存在等等。用户看到的 3/19/45 行“语法错误”都是这类噪音。
90
+ - 策略:语法诊断(`getSyntacticDiagnostics`)全保留;语义诊断白名单 `2304/2552/2448/2454`(Cannot find name / Block-scoped variable before declaration 等),其余(2339、2306、模块解析类)不展示。
91
+ - 实测 `baiducomp/taskks.js` 从 4 条误报 → 0 条;回归测试覆盖“属性不存在不报”。
84
92
 
85
93
  ## 1. 弹窗/菜单层级:只有一个正确做法(反复踩过多次,最终定案)
86
94
 
package/host/fs.js CHANGED
@@ -285,16 +285,16 @@ export function register(router, env) {
285
285
  /* Python 语言服务(LSP/pyright):/lsp/definition API;Cmd+点击与悬停由客户端调用 */
286
286
  registerLsp(router, env)
287
287
 
288
- /* Tab 行内补全:借用 Harness 自己的模型服务(completion.js 用带 mtime 的动态 import,改它免重启) */
289
- router.method('completion.suggest', async (body) => {
288
+ /* JS/TS 诊断:TypeScript 编译器在 Host 侧跑,返回 Monaco marker 需要的位置 */
289
+ router.method('lint.javascript', async (body) => {
290
290
  let stamp = '0'
291
291
  try {
292
- stamp = String(statSync(new URL('./completion.js', import.meta.url)).mtimeMs)
292
+ stamp = String(statSync(new URL('./lint.js', import.meta.url)).mtimeMs)
293
293
  } catch {
294
294
  stamp = '0'
295
295
  }
296
- const module = await import(new URL(`./completion.js?gufa-completion=${stamp}`, import.meta.url).href)
297
- return module.suggest(body, env)
296
+ const module = await import(new URL(`./lint.js?gufa-lint=${stamp}`, import.meta.url).href)
297
+ return module.diagnose(body, env)
298
298
  })
299
299
 
300
300
  /* ⌘⇧N:打开新的 Harness 实例窗口(Electron 单实例下新建 BrowserWindow)。
package/host/lint.js ADDED
@@ -0,0 +1,201 @@
1
+ /**
2
+ * JS/TS 诊断(语法错误 + 未定义变量等语义错误):Host 侧用 TypeScript 编译器
3
+ * 直接分析当前编辑内容,返回 Monaco marker 需要的行列信息。
4
+ *
5
+ * 不用 Monaco 的 TS worker:桌面壳页面是 dsh-app:// 自定义协议,worker 里
6
+ * importScripts 自定义协议资源会失败,导致语法/语义诊断时有时无;Host 侧
7
+ * 编译结果稳定,且可以随插件依赖(typescript)一起分发。
8
+ */
9
+ import { readFile } from 'node:fs/promises'
10
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
11
+
12
+ import ts from 'typescript'
13
+
14
+ import { ApiError, badRequest } from './context.js'
15
+
16
+ const IGNORED_CODES = new Set([
17
+ 2307, // Cannot find module(项目的模块解析/依赖不一定完整,避免盖住真正的错误)
18
+ 2792,
19
+ 7016,
20
+ 2688,
21
+ 1479,
22
+ 2580, // Cannot find name 'require' 等(由 globals shim 兜底,仍兜不住时静默)
23
+ ])
24
+
25
+ /** 只保留用户真正需要的语义诊断:未定义变量(2304/2552)等;
26
+ * 属性类型不匹配(2339 等)在动态 JS/JSON 配置项目里误报太多,直接不展示。 */
27
+ const SEMANTIC_CODES = new Set([2304, 2552, 2448, 2454])
28
+
29
+ const GLOBALS_FILE = '/__gufa_code_globals__.d.ts'
30
+ const GLOBALS_TEXT = [
31
+ 'declare var process: any;',
32
+ 'declare var require: any;',
33
+ 'declare var module: any;',
34
+ 'declare var exports: any;',
35
+ 'declare var __dirname: string;',
36
+ 'declare var __filename: string;',
37
+ 'declare var Buffer: any;',
38
+ 'declare var global: any;',
39
+ 'declare function setTimeout(handler: any, timeout?: any, ...args: any[]): any;',
40
+ 'declare function clearTimeout(handle?: any): void;',
41
+ 'declare function setInterval(handler: any, timeout?: any, ...args: any[]): any;',
42
+ 'declare function clearInterval(handle?: any): void;',
43
+ 'declare function setImmediate(handler: any, ...args: any[]): any;',
44
+ 'declare function clearImmediate(handle?: any): void;',
45
+ '',
46
+ ].join('\n')
47
+
48
+ function canonical(file) {
49
+ return resolve(file)
50
+ }
51
+
52
+ function inside(root, target) {
53
+ const rel = relative(root, target)
54
+ return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
55
+ }
56
+
57
+ function severityOf(category) {
58
+ if (category === ts.DiagnosticCategory.Error) return 1
59
+ if (category === ts.DiagnosticCategory.Warning) return 0
60
+ return 2
61
+ }
62
+
63
+ export async function diagnose(body, env) {
64
+ if (typeof body.root !== 'string' || body.root === '') throw badRequest('root is required')
65
+ const project = env.projects.ensure(body.root)
66
+ const root = project.root
67
+ const rawPath = typeof body.path === 'string' ? body.path : ''
68
+ if (rawPath === '') throw badRequest('path is required')
69
+ const absolute = resolve(root, rawPath)
70
+ if (!inside(root, absolute)) throw new ApiError('path-outside', '路径超出项目范围', 403)
71
+ const extension = rawPath.split('.').pop()?.toLowerCase() ?? ''
72
+ if (!['js', 'jsx', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].includes(extension)) return { diagnostics: [] }
73
+ let content = typeof body.content === 'string' ? body.content : ''
74
+ if (content === '') {
75
+ try {
76
+ content = await readFile(absolute, 'utf8')
77
+ } catch {
78
+ throw new ApiError('not-found', `文件不存在:${rawPath}`, 404)
79
+ }
80
+ }
81
+
82
+ const virtual = new Map([
83
+ [canonical(absolute), content],
84
+ [GLOBALS_FILE, GLOBALS_TEXT],
85
+ ])
86
+ const options = {
87
+ allowJs: true,
88
+ checkJs: true,
89
+ noEmit: true,
90
+ target: ts.ScriptTarget.ES2022,
91
+ module: ts.ModuleKind.ESNext,
92
+ moduleResolution: ts.ModuleResolutionKind.NodeJs,
93
+ jsx: ts.JsxEmit.Preserve,
94
+ esModuleInterop: true,
95
+ allowSyntheticDefaultImports: true,
96
+ resolveJsonModule: true,
97
+ skipLibCheck: true,
98
+ skipDefaultLibCheck: true,
99
+ strict: false,
100
+ noImplicitAny: false,
101
+ noUnusedLocals: false,
102
+ noUnusedParameters: false,
103
+ types: [],
104
+ lib: ['lib.es2022.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
105
+ allowNonTsExtensions: true,
106
+ baseUrl: root,
107
+ }
108
+ const nodeHost = ts.createCompilerHost(options)
109
+ const host = {
110
+ ...nodeHost,
111
+ getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile) {
112
+ const file = canonical(fileName)
113
+ if (virtual.has(file)) return ts.createSourceFile(file, virtual.get(file), languageVersion ?? ts.ScriptTarget.Latest, true)
114
+ return nodeHost.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile)
115
+ },
116
+ readFile(fileName) {
117
+ const file = canonical(fileName)
118
+ if (virtual.has(file)) return virtual.get(file)
119
+ return nodeHost.readFile(fileName)
120
+ },
121
+ fileExists(fileName) {
122
+ const file = canonical(fileName)
123
+ if (virtual.has(file)) return true
124
+ return nodeHost.fileExists(fileName)
125
+ },
126
+ getCurrentDirectory: () => root,
127
+ getCanonicalFileName: (fileName) => canonical(fileName),
128
+ }
129
+
130
+ /* 解析本地 import,拼成一个小 Program;这样跨文件定义/未定义变量判断更准。 */
131
+ const rootNames = [absolute, GLOBALS_FILE]
132
+ const seen = new Set([canonical(absolute), GLOBALS_FILE])
133
+ const queue = [canonical(absolute)]
134
+ while (queue.length > 0 && seen.size <= 40) {
135
+ const file = queue.shift()
136
+ const text = virtual.get(file) ?? ts.sys.readFile(file)
137
+ if (typeof text !== 'string') continue
138
+ let pre = null
139
+ try {
140
+ pre = ts.preProcessFile(text, true, true)
141
+ } catch {
142
+ continue
143
+ }
144
+ const references = [...(pre.importedFiles ?? []), ...(pre.referencedFiles ?? [])]
145
+ for (const reference of references) {
146
+ try {
147
+ const resolution = ts.resolveModuleName(reference.fileName, file, options, {
148
+ fileExists: host.fileExists,
149
+ readFile: host.readFile,
150
+ })
151
+ const resolved = resolution.resolvedModule?.resolvedFileName
152
+ if (typeof resolved !== 'string' || resolved === '') continue
153
+ if (!inside(root, resolved)) continue
154
+ const key = canonical(resolved)
155
+ if (seen.has(key)) continue
156
+ seen.add(key)
157
+ rootNames.push(key)
158
+ queue.push(key)
159
+ } catch {
160
+ /* 单个 import 解析失败不影响其它诊断 */
161
+ }
162
+ }
163
+ }
164
+
165
+ const program = ts.createProgram(rootNames, options, host)
166
+ const sourceFile = program.getSourceFile(canonical(absolute))
167
+ if (sourceFile === undefined || sourceFile === null) return { diagnostics: [] }
168
+ /* 语法错误全保留;语义只保留「未定义变量」这类,避免动态 JS 项目的类型误报 */
169
+ const syntactic = program.getSyntacticDiagnostics(sourceFile)
170
+ const semantic = program.getSemanticDiagnostics(sourceFile).filter((diagnostic) => SEMANTIC_CODES.has(Number(diagnostic.code)))
171
+ const collected = [...syntactic, ...semantic]
172
+ const diagnostics = []
173
+ const seenDiagnostics = new Set()
174
+ for (const diagnostic of collected) {
175
+ const code = Number(diagnostic.code)
176
+ if (IGNORED_CODES.has(code)) continue
177
+ const start = typeof diagnostic.start === 'number' ? diagnostic.start : 0
178
+ const length = typeof diagnostic.length === 'number' ? diagnostic.length : 0
179
+ const startPosition = ts.getLineAndCharacterOfPosition(sourceFile, start)
180
+ const endPosition = ts.getLineAndCharacterOfPosition(sourceFile, start + length)
181
+ const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
182
+ const key = `${code}:${start}:${message}`
183
+ if (seenDiagnostics.has(key)) continue
184
+ seenDiagnostics.add(key)
185
+ diagnostics.push({
186
+ severity: severityOf(diagnostic.category),
187
+ message,
188
+ code,
189
+ line: startPosition.line + 1,
190
+ column: startPosition.character + 1,
191
+ endLine: endPosition.line + 1,
192
+ endColumn: endPosition.character + 1,
193
+ })
194
+ if (diagnostics.length >= 200) break
195
+ }
196
+ return { diagnostics }
197
+ }
198
+
199
+ export function registerLint(router, env) {
200
+ router.method('lint.javascript', (body) => diagnose(body, env))
201
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gufa-code",
3
- "version": "1.3.116",
3
+ "version": "1.3.118",
4
4
  "description": "古法编程 · AI 辅助:一键把 DSH 主面板变成 VS Code 风格 IDE(Monaco 编辑器、文件树、Git、SSH、真实终端 + 右侧官方会话);主张亲手写、每个改动心中有数,AI 是助理、你是第一责任人",
5
5
  "icon": "icon.svg",
6
6
  "keywords": [
@@ -41,6 +41,7 @@
41
41
  ],
42
42
  "dependencies": {
43
43
  "pyright": "^1.1.414",
44
+ "typescript": "^5.9.3",
44
45
  "ws": "^8.22.0"
45
46
  },
46
47
  "dsh": {
@@ -133,6 +133,31 @@ try {
133
133
  const missingMtimes = await call(router, 'fs.mtimes', { root, paths: [] })
134
134
  check('fs.mtimes handles empty list', missingMtimes.files !== null && typeof missingMtimes.files === 'object' && Object.keys(missingMtimes.files).length === 0)
135
135
 
136
+ console.log('lint.javascript')
137
+ await call(router, 'fs.create', { root, path: 'src/lint-sample.js', kind: 'file' })
138
+ const lintResult = await call(router, 'lint.javascript', {
139
+ root,
140
+ path: 'src/lint-sample.js',
141
+ language: 'javascript',
142
+ content: 'const lintValue = undefinedVariable\n',
143
+ })
144
+ check('lint reports undefined variable', lintResult.diagnostics.some((item) => item.code === 2304 && item.line === 1), JSON.stringify(lintResult.diagnostics))
145
+ const lintSyntax = await call(router, 'lint.javascript', {
146
+ root,
147
+ path: 'src/lint-sample.js',
148
+ language: 'javascript',
149
+ content: 'const = 1\n',
150
+ })
151
+ check('lint reports syntax error', lintSyntax.diagnostics.some((item) => item.severity === 1 && item.code === 1134), JSON.stringify(lintSyntax.diagnostics))
152
+ const lintNoisy = await call(router, 'lint.javascript', {
153
+ root,
154
+ path: 'src/lint-sample.js',
155
+ language: 'javascript',
156
+ content: 'const someObject = {}\nsomeObject.missingProperty\n',
157
+ })
158
+ check('lint suppresses dynamic property warnings', lintNoisy.diagnostics.length === 0, JSON.stringify(lintNoisy.diagnostics))
159
+ await call(router, 'fs.delete', { root, path: 'src/lint-sample.js' }).catch(() => {})
160
+
136
161
  console.log('fs.search')
137
162
  await call(router, 'fs.create', { root, path: 'search.txt', kind: 'file' })
138
163
  await call(router, 'fs.write', { root, path: 'search.txt', content: 'Alpha beta\nBETA gamma\nbeta BETA\n' })
@@ -471,6 +471,9 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
471
471
  lineHeight: 20,
472
472
  fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',
473
473
  autoIndent: 'full',
474
+ autoClosingBrackets: 'languageDefined',
475
+ autoClosingQuotes: 'languageDefined',
476
+ autoSurround: 'languageDefined',
474
477
  detectIndentation: true,
475
478
  tabSize: 2,
476
479
  insertSpaces: true,
@@ -488,7 +491,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
488
491
  wordBasedSuggestions: 'currentDocument',
489
492
  acceptSuggestionOnEnter: 'on',
490
493
  tabCompletion: 'on',
491
- inlineSuggest: { enabled: false, showToolbar: 'never' },
492
494
  }
493
495
  }
494
496
 
@@ -735,6 +737,16 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
735
737
  } catch (error) {
736
738
  /* 模板语言注册失败不影响编辑器 */
737
739
  }
740
+ /* 诊断改由 Host 的 TypeScript 编译器提供(dsh-app worker 不可靠),
741
+ 关闭 Monaco worker 诊断避免重复/后台报错;补全建议仍由 worker 提供。 */
742
+ try {
743
+ const typescriptLanguages = monaco.languages.typescript
744
+ const diagnosticsOff = { noSemanticValidation: true, noSyntaxValidation: true }
745
+ typescriptLanguages?.typescriptDefaults?.setDiagnosticsOptions(diagnosticsOff)
746
+ typescriptLanguages?.javascriptDefaults?.setDiagnosticsOptions(diagnosticsOff)
747
+ } catch (error) {
748
+ /* ignore */
749
+ }
738
750
  try {
739
751
  const instance = monaco.editor.create(host, gufaEditorOptions(propsRef.current.theme))
740
752
  editor = instance
@@ -1151,134 +1163,6 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
1151
1163
  } catch {
1152
1164
  /* ignore */
1153
1165
  }
1154
- /* ── Copilot 风格 Tab 行内补全(复用 Harness 模型服务) ───────── */
1155
- try {
1156
- if (typeof monaco.languages.registerInlineCompletionsProvider === 'function') {
1157
- const inlineLanguages = ['python', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact', 'java', 'go', 'rust', 'csharp', 'cpp', 'c', 'shell', 'json', 'yaml', 'sql', 'html', 'css']
1158
- const inlineCache = new Map()
1159
- let inlineLastRequestAt = 0
1160
- const inlineProvider = {
1161
- provideInlineCompletions(model, position, context, token) {
1162
- /* AI Tab 补全已默认关闭:结果质量差、且每次请求会增加延迟。
1163
- 需要重新开启时把此处的 return 去掉,并把 inlineSuggest.enabled 改回 true。 */
1164
- return Promise.resolve({ items: [] })
1165
- // eslint-disable-next-line no-unreachable
1166
- const path = modelPathRef.current
1167
- const root = modelsRootRef.current
1168
- if (path === null || path === undefined || root === null || root === undefined || root === '') {
1169
- return Promise.resolve({ items: [] })
1170
- }
1171
- if (token !== null && token !== undefined && token.isCancellationRequested === true) return Promise.resolve({ items: [] })
1172
- return new Promise((resolve) => {
1173
- let settled = false
1174
- const finish = (value) => {
1175
- if (settled) return
1176
- settled = true
1177
- resolve(value)
1178
- }
1179
- const timer = window.setTimeout(() => {
1180
- void (async () => {
1181
- try {
1182
- if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
1183
- const now = Date.now()
1184
- if (now - inlineLastRequestAt < 500) return finish({ items: [] })
1185
- inlineLastRequestAt = now
1186
- const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
1187
- if (!inlineLanguages.includes(language)) return finish({ items: [] })
1188
- const lineCount = model.getLineCount()
1189
- const startLine = Math.max(1, position.lineNumber - 140)
1190
- const endLine = Math.min(lineCount, position.lineNumber + 30)
1191
- const endColumn = model.getLineMaxColumn(endLine)
1192
- let prefix = ''
1193
- let suffix = ''
1194
- try {
1195
- prefix = model.getValueInRange(new monaco.Range(startLine, 1, position.lineNumber, position.column)).slice(-3200)
1196
- suffix = model.getValueInRange(new monaco.Range(position.lineNumber, position.column, endLine, endColumn)).slice(0, 800)
1197
- } catch {
1198
- return finish({ items: [] })
1199
- }
1200
- const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
1201
- const cacheKey = `${path}|${version}|${position.lineNumber}:${position.column}|${language}`
1202
- const cached = inlineCache.get(cacheKey)
1203
- if (cached !== undefined) return finish(cached)
1204
- const value = await G.api('completion.suggest', { root, path, language, prefix, suffix })
1205
- if (token !== null && token !== undefined && token.isCancellationRequested === true) return finish({ items: [] })
1206
- const text = value !== null && value !== undefined && typeof value.text === 'string' ? value.text : ''
1207
- const result = text === ''
1208
- ? { items: [] }
1209
- : { items: [{ insertText: text, range: new monaco.Range(position.lineNumber, position.column, position.lineNumber, position.column) }] }
1210
- if (inlineCache.size > 30) inlineCache.clear()
1211
- inlineCache.set(cacheKey, result)
1212
- finish(result)
1213
- } catch {
1214
- finish({ items: [] })
1215
- }
1216
- })()
1217
- }, 260)
1218
- if (token !== null && token !== undefined && typeof token.onCancellationRequested === 'function') {
1219
- token.onCancellationRequested(() => {
1220
- window.clearTimeout(timer)
1221
- finish({ items: [] })
1222
- })
1223
- }
1224
- })
1225
- },
1226
- freeInlineCompletions() {},
1227
- }
1228
- const inlineDisposable = monaco.languages.registerInlineCompletionsProvider(inlineLanguages, inlineProvider)
1229
- if (inlineDisposable !== null && inlineDisposable !== undefined && typeof inlineDisposable.dispose === 'function') subscriptions.push(inlineDisposable)
1230
- }
1231
- } catch {
1232
- /* ignore */
1233
- }
1234
-
1235
- /* 外部/AI 修改磁盘后由 App 轮询发现,通过 bus 通知编辑器热替换 model 内容 */
1236
- try {
1237
- if (G.bus !== null && G.bus !== undefined && typeof G.bus.on === 'function') {
1238
- const offExternalReload = G.bus.on('editor:external-reload', (detail) => {
1239
- if (detail === null || detail === undefined || typeof detail.path !== 'string' || typeof detail.content !== 'string') return
1240
- const target = modelsRef.current.get(detail.path)
1241
- if (target === null || target === undefined) return
1242
- let content = ''
1243
- try {
1244
- content = target.getValue()
1245
- } catch {
1246
- return
1247
- }
1248
- if (content === detail.content) return
1249
- const active = modelPathRef.current === detail.path
1250
- let position = null
1251
- let scrollTop = 0
1252
- if (active) {
1253
- try {
1254
- position = instance.getPosition()
1255
- scrollTop = instance.getScrollTop()
1256
- } catch {
1257
- position = null
1258
- }
1259
- }
1260
- suppressChangeRef.current = true
1261
- try {
1262
- target.setValue(detail.content)
1263
- } finally {
1264
- suppressChangeRef.current = false
1265
- }
1266
- lastPropContentRef.current.set(detail.path, detail.content)
1267
- if (active && position !== null && position !== undefined) {
1268
- try {
1269
- instance.setPosition(position)
1270
- instance.setScrollTop(scrollTop)
1271
- } catch {
1272
- /* ignore */
1273
- }
1274
- }
1275
- })
1276
- if (typeof offExternalReload === 'function') subscriptions.push({ dispose: offExternalReload })
1277
- }
1278
- } catch {
1279
- /* ignore */
1280
- }
1281
-
1282
1166
  G.__gufaEditorDebug = {
1283
1167
  focus: () => {
1284
1168
  try {
@@ -1335,6 +1219,84 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
1335
1219
  }))
1336
1220
  /* 光标 / 选区变化上报(状态栏行号列、AI 上下文选区)。 */
1337
1221
  subscriptions.push(instance.onDidChangeCursorSelection(() => reportCursor()))
1222
+ /* ── JS/TS 诊断(Host 侧 tsc):语法错误 / 未定义变量 / 类型错误 ── */
1223
+ const lintTimers = new Map()
1224
+ const clearLintTimers = () => {
1225
+ for (const timer of lintTimers.values()) window.clearTimeout(timer)
1226
+ lintTimers.clear()
1227
+ }
1228
+ const runLint = async (model, path) => {
1229
+ if (model === null || model === undefined || typeof path !== 'string' || path === '') return
1230
+ const language = typeof model.getLanguageId === 'function' ? model.getLanguageId() : ''
1231
+ if (language !== 'javascript' && language !== 'typescript') return
1232
+ const root = modelsRootRef.current
1233
+ if (root === null || root === undefined || root === '') return
1234
+ const version = typeof model.getVersionId === 'function' ? model.getVersionId() : 0
1235
+ let result = null
1236
+ try {
1237
+ result = await G.api('lint.javascript', { root, path, language, content: model.getValue() })
1238
+ } catch {
1239
+ return
1240
+ }
1241
+ try {
1242
+ if (typeof model.isDisposed === 'function' && model.isDisposed() === true) return
1243
+ if (typeof model.getVersionId === 'function' && model.getVersionId() !== version) return
1244
+ const list = result !== null && result !== undefined && Array.isArray(result.diagnostics) ? result.diagnostics : []
1245
+ const markerList = []
1246
+ for (const item of list.slice(0, 200)) {
1247
+ if (item === null || typeof item !== 'object') continue
1248
+ const severity = Number(item.severity)
1249
+ markerList.push({
1250
+ severity: severity === 1 ? monaco.MarkerSeverity.Error : (severity === 0 ? monaco.MarkerSeverity.Warning : monaco.MarkerSeverity.Info),
1251
+ message: String(item.message ?? ''),
1252
+ startLineNumber: Number(item.line) || 1,
1253
+ startColumn: Number(item.column) || 1,
1254
+ endLineNumber: Number(item.endLine ?? item.line) || 1,
1255
+ endColumn: Number(item.endColumn ?? item.column) || 1,
1256
+ source: 'gufa-ts',
1257
+ code: String(item.code ?? ''),
1258
+ })
1259
+ }
1260
+ monaco.editor.setModelMarkers(model, 'gufa-ts', markerList)
1261
+ } catch {
1262
+ /* ignore */
1263
+ }
1264
+ }
1265
+ const scheduleLint = (model, path) => {
1266
+ if (model === null || model === undefined || typeof path !== 'string' || path === '') return
1267
+ const previous = lintTimers.get(path)
1268
+ if (previous !== undefined) window.clearTimeout(previous)
1269
+ const timer = window.setTimeout(() => {
1270
+ lintTimers.delete(path)
1271
+ void runLint(model, path)
1272
+ }, 650)
1273
+ lintTimers.set(path, timer)
1274
+ }
1275
+ subscriptions.push({ dispose: clearLintTimers })
1276
+ try {
1277
+ subscriptions.push(instance.onDidChangeModel(() => {
1278
+ const model = instance.getModel()
1279
+ const path = modelPathRef.current
1280
+ if (model !== null && model !== undefined && path !== null && path !== undefined) scheduleLint(model, path)
1281
+ }))
1282
+ } catch {
1283
+ /* ignore */
1284
+ }
1285
+ subscriptions.push(instance.onDidChangeModelContent(() => {
1286
+ const model = instance.getModel()
1287
+ const path = modelPathRef.current
1288
+ if (model !== null && model !== undefined && path !== null && path !== undefined) scheduleLint(model, path)
1289
+ }))
1290
+ try {
1291
+ const initialModel = instance.getModel()
1292
+ const initialPath = modelPathRef.current
1293
+ if (initialModel !== null && initialModel !== undefined && initialPath !== null && initialPath !== undefined) {
1294
+ window.setTimeout(() => { scheduleLint(initialModel, initialPath) }, 0)
1295
+ }
1296
+ } catch {
1297
+ /* ignore */
1298
+ }
1299
+
1338
1300
  /* 语言服务(JS/TS/JSON/CSS/HTML)诊断 → 资源管理器 / 标签页 / 状态栏 */
1339
1301
  const publishProblems = () => {
1340
1302
  if (typeof G.problemsStore?.set !== 'function') return
@@ -1,158 +0,0 @@
1
- /**
2
- * Tab 行内补全:借用 Harness 自己的模型服务(ctx.llm),不需要额外 Copilot 订阅。
3
- *
4
- * 客户端 Monaco 在光标处请求 `completion.suggest`,Host 拼一小段 FIM 风格 prompt,
5
- * 用当前默认模型(ctx.agentDefaultModel)流式生成,只回插入文本。为了保持轻量,
6
- * prompt 只带光标前后有限上下文、maxTokens 很小,客户端做防抖/限流/取消。
7
- */
8
- import { ApiError, badRequest } from './context.js'
9
-
10
- const SYSTEM_PROMPT = [
11
- 'You are an inline code completion engine inside an IDE.',
12
- 'Given the code before and after the cursor, predict the exact text the developer would type next.',
13
- 'Return ONLY the insertion text: no markdown fences, no comments explaining, no repetition of existing text.',
14
- 'Keep it short (usually one line to a few lines). Match the indentation of the surrounding code.',
15
- ].join(' ')
16
-
17
- const SUPPORTED = new Set([
18
- 'python', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact',
19
- 'json', 'markdown', 'css', 'scss', 'less', 'html', 'java', 'go', 'rust',
20
- 'csharp', 'cpp', 'c', 'shell', 'yaml', 'sql', 'php', 'ruby',
21
- ])
22
-
23
-
24
- function sanitize(text) {
25
- let value = String(text ?? '')
26
- /* 去掉模型偶尔带出的 markdown 围栏 */
27
- value = value.replace(/^```[a-zA-Z0-9_-]*\r?\n?/, '').replace(/\r?\n?```\s*$/, '')
28
- /* 只取第一段有意义的插入内容,去掉结尾整行解释 */
29
- value = value.replace(/\r\n/g, '\n')
30
- const lines = value.split('\n')
31
- while (lines.length > 0 && lines[0].trim() === '') lines.shift()
32
- while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop()
33
- value = lines.join('\n')
34
- if (value.length > 1200) value = value.slice(0, 1200)
35
- return value
36
- }
37
-
38
- function selectionOf(ctx) {
39
- try {
40
- const service = typeof ctx.get === 'function' ? ctx.get('agentDefaultModel') : undefined
41
- if (service !== undefined && service !== null && typeof service.currentSelection === 'function') return service.currentSelection()
42
- } catch {
43
- /* ignore */
44
- }
45
- return undefined
46
- }
47
-
48
- const effortCache = new Map()
49
-
50
- /** 补全要求低延迟:优先选最小 reasoning effort(不同模型 id 不同,如 off/minimal/low)。 */
51
- async function pickReasoningEffort(llm, provider, model) {
52
- const key = `${provider}|${model}`
53
- if (effortCache.has(key)) return effortCache.get(key)
54
- let chosen = ''
55
- try {
56
- const info = await llm.resolveModelInfo(provider, model)
57
- const efforts = info !== null && info !== undefined && info.reasoning !== null && info.reasoning !== undefined && Array.isArray(info.reasoning.efforts)
58
- ? info.reasoning.efforts.map((entry) => String(entry?.id ?? '')).filter((id) => id !== '')
59
- : []
60
- chosen = efforts.find((id) => /^(off|none|minimal|low)$/i.test(id)) ?? efforts[0] ?? ''
61
- } catch {
62
- chosen = ''
63
- }
64
- effortCache.set(key, chosen)
65
- return chosen
66
- }
67
-
68
- export async function suggest(body, env) {
69
- if (typeof body.prefix !== 'string' && typeof body.suffix !== 'string') throw badRequest('prefix is required')
70
- const ctx = env.ctx
71
- const llm = typeof ctx.get === 'function' ? ctx.get('llm') : undefined
72
- if (llm === undefined || llm === null || typeof llm.stream !== 'function') {
73
- throw new ApiError('llm-unavailable', '当前环境没有可用的模型服务', 503)
74
- }
75
- const language = typeof body.language === 'string' ? body.language : ''
76
- if (!SUPPORTED.has(language)) return { skipped: true, text: '' }
77
- const path = typeof body.path === 'string' ? body.path : ''
78
- const prefix = String(body.prefix ?? '').slice(-6000)
79
- const suffix = String(body.suffix ?? '').slice(0, 2000)
80
- const fallback = selectionOf(ctx)
81
- const provider = typeof body.provider === 'string' && body.provider !== '' ? body.provider : fallback?.provider
82
- const model = typeof body.model === 'string' && body.model !== '' ? body.model : fallback?.model
83
- if (typeof provider !== 'string' || provider === '' || typeof model !== 'string' || model === '') {
84
- throw new ApiError('llm-model-unavailable', '没有可用的默认模型', 503)
85
- }
86
- const userPrompt = [
87
- `File: ${path || '(untitled)'}`,
88
- `Language: ${language}`,
89
- '',
90
- 'Code before cursor:',
91
- '<<<',
92
- prefix,
93
- '>>>',
94
- '',
95
- 'Code after cursor:',
96
- '<<<',
97
- suffix,
98
- '>>>',
99
- '',
100
- 'Insertion:',
101
- ].join('\n')
102
-
103
- const reasoningEffort = await pickReasoningEffort(llm, provider, model)
104
- const controller = new AbortController()
105
- const timer = setTimeout(() => controller.abort(), 9000)
106
- let text = ''
107
- let failure = null
108
- let finishKind = ''
109
- let usage = null
110
- const startedAt = Date.now()
111
- try {
112
- const stream = llm.stream({
113
- provider,
114
- model,
115
- ...(reasoningEffort === '' ? {} : { reasoningEffort }),
116
- system: SYSTEM_PROMPT,
117
- messages: [{ role: 'user', content: [{ type: 'text', text: userPrompt }] }],
118
- maxTokens: 160,
119
- temperature: 0.2,
120
- stop: ['\n\n\n'],
121
- signal: controller.signal,
122
- })
123
- for await (const chunk of stream) {
124
- if (chunk === null || typeof chunk !== 'object') continue
125
- if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text
126
- if (chunk.type === 'reasoning-delta') continue
127
- if (chunk.type === 'usage') usage = chunk.usage
128
- if (chunk.type === 'finish') {
129
- const reason = chunk.reason
130
- finishKind = reason !== null && typeof reason === 'object' && typeof reason.kind === 'string' ? reason.kind : ''
131
- if (reason !== null && typeof reason === 'object' && (reason.kind === 'error' || reason.kind === 'aborted')) {
132
- failure = reason.failure ?? { message: reason.kind }
133
- }
134
- break
135
- }
136
- }
137
- } catch (error) {
138
- failure = { message: String(error?.message ?? error) }
139
- } finally {
140
- clearTimeout(timer)
141
- }
142
- if (failure !== null && failure !== undefined) {
143
- const message = typeof failure.message === 'string' ? failure.message : '模型调用失败'
144
- if (controller.signal.aborted) throw new ApiError('llm-timeout', '补全请求超时', 504)
145
- throw new ApiError('llm-failed', `补全模型调用失败:${message}`, 502)
146
- }
147
- const sanitized = sanitize(text)
148
- return {
149
- provider,
150
- model,
151
- text: sanitized,
152
- latencyMs: Date.now() - startedAt,
153
- }
154
- }
155
-
156
- export function registerCompletion(router, env) {
157
- router.method('completion.suggest', (body) => suggest(body, env))
158
- }