dsh-llama-cpp-provider 0.0.0-stage → 0.3.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 spark
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # Llama.cpp for DeepSeek Harness
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [中文](docs/DETAIL.zh.md)
4
+
5
+ ![Llama.cpp in DSH](docs/preview.png)
6
+
7
+ ## The models on your computer. Right inside DeepSeek Harness.
8
+
9
+ Llama.cpp makes local models feel like any other model in DSH. It's ready the moment DSH opens, and it quits when DSH does. No internet. No keys. Your conversations stay on this computer.
10
+
11
+ ## Before you begin
12
+
13
+ Install llama.cpp.
14
+
15
+ - **macOS**: Open Terminal and run
16
+ `curl -LsSf https://llama.app/install.sh | sh`
17
+ - **Windows**: Open PowerShell and run
18
+ `irm https://llama.app/install.ps1 | iex`
19
+
20
+ When it's done, reopen DSH.
21
+
22
+ ## Install the plugin
23
+
24
+ In DSH, go to Plugins, click Add plugin, and install the npm package `dsh-llama-cpp-provider`.
25
+
26
+ ## Add Llama.cpp
27
+
28
+ 1. Go to Settings > Models, then click Add model provider.
29
+ 2. Under Third-party model provider, choose **Llama.cpp**.
30
+ 3. Click Fetch available models, then click Save.
31
+
32
+ That's it. Choose a model under Llama.cpp in any session and start chatting.
33
+
34
+ ## Tips
35
+
36
+ - When you add or edit Llama.cpp, its card shows whether llama.cpp is ready. If it isn't installed yet, the card tells you what to do.
37
+ - Want to tune a model? Edit llama.cpp's `models.user.ini` file, and Llama.cpp picks it up automatically.
38
+ - Don't see Llama.cpp under Third-party model provider after installing the plugin? Reopen DSH.
39
+ - Want a green dot next to Llama.cpp? Enter any API key on its card. Local models don't need one, so Llama.cpp works either way.
40
+
41
+ ## License
42
+
43
+ [MIT](LICENSE)
package/client.js ADDED
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Llama.cpp — browser half. Shows read-only notes on the Llama.cpp card in
3
+ * Settings > Models (while adding it, or while its editor is open): where
4
+ * the llama executable and models-preset file were found, or how to install
5
+ * llama.cpp when they were not.
6
+ */
7
+ window.__ModuleLoader__.load({
8
+ id: '@local/dsh-llama-cpp',
9
+ factory(require) {
10
+ const React = require('react')
11
+ const h = React.createElement
12
+
13
+ const PKG = '@local/dsh-llama-cpp'
14
+ const ROUTE = 'llama.dsh'
15
+ const PI_AI_NS = 'llm-pi-ai'
16
+ const NS = 'llama-cpp'
17
+ const REMOTE_NS = 'llamaCpp'
18
+ const INSTALL_URL = 'https://github.com/ggml-org/llama.cpp#quick-start'
19
+
20
+ const zh = {
21
+ title: 'Llama.cpp 本地服务',
22
+ binary: 'llama 命令',
23
+ preset: 'models-preset 文件',
24
+ auto: '已自动找到:{path}',
25
+ binaryNone: '没有找到 llama 命令。请按 llama.cpp 官方教程安装:',
26
+ binaryInstallMac: 'macOS / Linux:curl -LsSf https://llama.app/install.sh | sh',
27
+ binaryInstallWin: 'Windows(PowerShell):irm https://llama.app/install.ps1 | iex',
28
+ binaryAfter: '安装后重启 DSH。',
29
+ presetNone: '没有找到 models.user.ini,llama 服务会以默认设置启动。',
30
+ loading: '正在读取…',
31
+ failed: '无法读取本地服务信息',
32
+ guide: '官方教程',
33
+ }
34
+ const en = {
35
+ title: 'Llama.cpp local server',
36
+ binary: 'llama executable',
37
+ preset: 'models-preset file',
38
+ auto: 'Found automatically: {path}',
39
+ binaryNone: 'No llama executable was found. Install llama.cpp by following the official guide:',
40
+ binaryInstallMac: 'macOS / Linux: curl -LsSf https://llama.app/install.sh | sh',
41
+ binaryInstallWin: 'Windows (PowerShell): irm https://llama.app/install.ps1 | iex',
42
+ binaryAfter: 'Restart DSH after installing.',
43
+ presetNone: 'No models.user.ini was found; the llama server starts with default settings.',
44
+ loading: 'Loading…',
45
+ failed: 'Could not read local server information',
46
+ guide: 'Official guide',
47
+ }
48
+
49
+ // ---- Remote (read-only getInfo on the Host) ----
50
+ const IDENTITY_SCHEMA = {
51
+ '~standard': { version: 1, vendor: PKG, validate: value => ({ value }) },
52
+ parse: value => value,
53
+ }
54
+ const CONTRIBUTION = {
55
+ package: PKG,
56
+ descriptors: [{
57
+ id: PKG + '#' + REMOTE_NS + '/getInfo',
58
+ service: REMOTE_NS,
59
+ namespace: REMOTE_NS,
60
+ method: 'getInfo',
61
+ invocation: { kind: 'direct' },
62
+ parameters: [],
63
+ result: { mode: 'strict', typeSymbol: PKG + '#getInfo:result', create: () => IDENTITY_SCHEMA },
64
+ }],
65
+ }
66
+
67
+ const fill = (s, vars) => String(s).replace(/\{(\w+)\}/g, (_, k) => (vars && k in vars ? vars[k] : ''))
68
+ const muted = { fontSize: 12, opacity: 0.75, lineHeight: 1.6 }
69
+ const code = { fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)', fontSize: 12, wordBreak: 'break-all' }
70
+
71
+ function PathLine({ label, item, none, t }) {
72
+ let body
73
+ if (item.source === 'auto') body = h('span', { style: code }, fill(t('auto'), { path: item.path }))
74
+ else if (item.source === 'config' && item.exists) body = h('span', { style: code }, fill(t('config'), { path: item.path }))
75
+ else if (item.source === 'config') body = h('span', { style: { ...code, color: 'var(--dsw-color-danger, #d33)' } }, fill(t('configMissing'), { path: item.path }))
76
+ else body = none
77
+ // One line per item: label, then where it was found.
78
+ return h('div', { style: { display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 0 } },
79
+ h('span', { style: { fontSize: 12, fontWeight: 600, flexShrink: 0, whiteSpace: 'nowrap' } }, label),
80
+ h('div', { style: { ...muted, minWidth: 0 } }, body))
81
+ }
82
+
83
+ function Info({ api, t }) {
84
+ const [info, setInfo] = React.useState(null)
85
+ const [error, setError] = React.useState(false)
86
+ React.useEffect(() => {
87
+ let live = true
88
+ api.getInfo().then(v => { if (live) setInfo(v) }, err => {
89
+ console.error('[llama.cpp] getInfo failed', err)
90
+ if (live) setError(true)
91
+ })
92
+ return () => { live = false }
93
+ }, [])
94
+
95
+ const box = children => h('div', {
96
+ style: {
97
+ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12, paddingTop: 12,
98
+ borderTop: '1px solid var(--dsw-color-border, rgba(127,127,127,.25))',
99
+ },
100
+ }, h('span', { style: { fontSize: 13, fontWeight: 600 } }, t('title')), ...children)
101
+
102
+ if (error) return box([h('div', { style: muted }, t('failed'))])
103
+ if (!info) return box([h('div', { style: muted }, t('loading'))])
104
+
105
+ const win = info.platform === 'win32'
106
+ const binaryNone = h('div', null,
107
+ h('div', null, t('binaryNone'), ' ',
108
+ h('a', { href: INSTALL_URL, target: '_blank', rel: 'noreferrer' }, t('guide'))),
109
+ h('div', { style: code }, win ? t('binaryInstallWin') : t('binaryInstallMac')),
110
+ h('div', null, t('binaryAfter')))
111
+
112
+ return box([
113
+ h(PathLine, { key: 'b', label: t('binary'), item: info.binary, none: binaryNone, t }),
114
+ h(PathLine, { key: 'p', label: t('preset'), item: info.preset, none: t('presetNone'), t }),
115
+ ])
116
+ }
117
+
118
+ // Show on the add-provider draft (configured is false), and on a saved
119
+ // row only while its editor is open: the editor is then rendered right
120
+ // after this slot area inside the card.
121
+ function useEditorOpen(anchor, enabled) {
122
+ const [open, setOpen] = React.useState(false)
123
+ React.useEffect(() => {
124
+ let el = anchor.current
125
+ if (!enabled || !el) return
126
+ while (el.parentElement && el.parentElement.tagName !== 'LI') el = el.parentElement
127
+ const card = el.parentElement
128
+ if (!card) return
129
+ const check = () => setOpen(!!el.nextElementSibling)
130
+ check()
131
+ const mo = new MutationObserver(check)
132
+ mo.observe(card, { childList: true })
133
+ return () => mo.disconnect()
134
+ }, [enabled])
135
+ return open
136
+ }
137
+
138
+ return {
139
+ inject: ['slots', 'locale', 'remote'],
140
+ apply(ctx) {
141
+ const t = ctx.locale.bind(NS)
142
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'llama-cpp: dictionaries')
143
+
144
+ ctx.effect(() => {
145
+ let disposed = false
146
+ let disposer = null
147
+ Promise.resolve(ctx.remote.$mount(CONTRIBUTION)).then(d => {
148
+ if (disposed) { Promise.resolve(d()).catch(() => {}); return }
149
+ disposer = d
150
+ }, err => console.error('[llama.cpp] remote mount failed', err))
151
+ return () => { disposed = true; if (disposer) return disposer() }
152
+ }, 'llama-cpp: remote')
153
+
154
+ const api = {
155
+ getInfo() {
156
+ const ns = (typeof ctx.get === 'function' && ctx.get('remote.' + REMOTE_NS)) || (ctx.remote && ctx.remote[REMOTE_NS])
157
+ if (!ns) return Promise.reject(new Error('llama.cpp remote is not mounted yet'))
158
+ return ns.getInfo().then(r => { if (!r.ok) throw r.error; return r.value })
159
+ },
160
+ }
161
+
162
+ // On the add-provider draft the page renders this area after the
163
+ // editor; move it visually above the editor (CSS order only, React's
164
+ // DOM is left untouched) so it matches the edit card.
165
+ function useAboveEditor(anchor, enabled) {
166
+ React.useEffect(() => {
167
+ let el = anchor.current
168
+ if (!enabled || !el) return
169
+ while (el.parentElement && !el.previousElementSibling) el = el.parentElement
170
+ const editor = el.previousElementSibling
171
+ const panel = el.parentElement
172
+ if (!editor || !panel) return
173
+ const saved = { display: panel.style.display, dir: panel.style.flexDirection, editor: editor.style.order, el: el.style.order }
174
+ if (getComputedStyle(panel).display !== 'flex') { panel.style.display = 'flex'; panel.style.flexDirection = 'column' }
175
+ editor.style.order = '2'
176
+ el.style.order = '1'
177
+ return () => {
178
+ panel.style.display = saved.display
179
+ panel.style.flexDirection = saved.dir
180
+ editor.style.order = saved.editor
181
+ el.style.order = saved.el
182
+ }
183
+ }, [enabled])
184
+ }
185
+
186
+ function Extra(props) {
187
+ const anchor = React.useRef(null)
188
+ const mine = !!props.provider && props.provider.provider === ROUTE
189
+ const draft = props.configured === false
190
+ const editorOpen = useEditorOpen(anchor, mine && !draft)
191
+ useAboveEditor(anchor, mine && draft)
192
+ if (!mine) return null
193
+ return h('div', { ref: anchor }, draft || editorOpen ? h(Info, { api, t: props.t || t }) : null)
194
+ }
195
+
196
+ ctx.effect(() => ctx.slots.inject('settings.models.provider-card', () => ctx.slots.register({
197
+ name: 'settings.models.provider-card', key: PI_AI_NS, locale: NS,
198
+ }, Extra)), 'llama-cpp: provider card')
199
+ },
200
+ }
201
+ },
202
+ })
@@ -0,0 +1,12 @@
1
+ # Starts `llama serve` (router mode) when DSH boots and offers a llama.cpp
2
+ # entry under Settings > Models > Add model provider.
3
+ - insert:
4
+ - id: llama-cpp-server
5
+ name: '@local/dsh-llama-cpp'
6
+ config:
7
+ modelsMax: 1
8
+ extraArgs: []
9
+ autostart: true
10
+ # Offer llama.cpp under Models > Add model provider until it is configured.
11
+ offerProvider: true
12
+ piAiEntryId: llm-pi-ai
package/docs/DETAIL.md ADDED
@@ -0,0 +1,31 @@
1
+ ![Llama.cpp in DSH](preview.png)
2
+
3
+ ## The models on your computer. Right inside DeepSeek Harness.
4
+
5
+ Llama.cpp makes local models feel like any other model in DSH. It's ready the moment DSH opens, and it quits when DSH does. No internet. No keys. Your conversations stay on this computer.
6
+
7
+ ## Before you begin
8
+
9
+ Install llama.cpp.
10
+
11
+ - **macOS**: Open Terminal and run
12
+ `curl -LsSf https://llama.app/install.sh | sh`
13
+ - **Windows**: Open PowerShell and run
14
+ `irm https://llama.app/install.ps1 | iex`
15
+
16
+ When it's done, reopen DSH.
17
+
18
+ ## Add Llama.cpp
19
+
20
+ 1. Go to Settings > Models, then click Add model provider.
21
+ 2. Under Third-party model provider, choose **Llama.cpp**.
22
+ 3. Click Fetch available models, then click Save.
23
+
24
+ That's it. Choose a model under Llama.cpp in any session and start chatting.
25
+
26
+ ## Tips
27
+
28
+ - When you add or edit Llama.cpp, its card shows whether llama.cpp is ready. If it isn't installed yet, the card tells you what to do.
29
+ - Want to tune a model? Edit llama.cpp's `models.user.ini` file, and Llama.cpp picks it up automatically.
30
+ - Don't see Llama.cpp under Third-party model provider after installing the plugin? Reopen DSH.
31
+ - Want a green dot next to Llama.cpp? Enter any API key on its card. Local models don't need one, so Llama.cpp works either way.
@@ -0,0 +1,31 @@
1
+ ![DSH 中的 Llama.cpp](preview.png)
2
+
3
+ ## 在 DeepSeek Harness 里,直接用你电脑上的模型。
4
+
5
+ Llama.cpp 让本地模型像其他模型一样,在 DSH 中随选随用。打开 DSH,它就已经就绪;关掉 DSH,它也随之退出。无需联网,无需密钥,你的对话只留在这台电脑上。
6
+
7
+ ## 开始之前
8
+
9
+ 先安装 llama.cpp。
10
+
11
+ - **macOS**:打开「终端」,运行
12
+ `curl -LsSf https://llama.app/install.sh | sh`
13
+ - **Windows**:打开 PowerShell,运行
14
+ `irm https://llama.app/install.ps1 | iex`
15
+
16
+ 安装完成后,重新打开 DSH。
17
+
18
+ ## 添加 Llama.cpp
19
+
20
+ 1. 前往「设置」>「模型」,点按「添加模型供应商」。
21
+ 2. 在「第三方模型供应商」中选择 **Llama.cpp**。
22
+ 3. 点按「获取可用模型」,然后点按「保存」。
23
+
24
+ 就这么简单。现在,在任意会话的模型列表里选择 Llama.cpp 下的模型,即可开始对话。
25
+
26
+ ## 小提示
27
+
28
+ - 添加或编辑 Llama.cpp 时,卡片上会告诉你 llama.cpp 是否已就绪。如果还没安装,这里也会告诉你该怎么做。
29
+ - 想调整模型参数?编辑 llama.cpp 的 `models.user.ini` 文件即可,Llama.cpp 会自动读取。
30
+ - 安装插件后,如果在「第三方模型供应商」里找不到 Llama.cpp,请重新打开 DSH。
31
+ - 想让 Llama.cpp 卡片旁亮起绿点?在卡片上随便填一个 API 密钥即可。本地模型并不需要密钥,填不填都能正常使用。
Binary file
package/icon.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-selfhst="llama-cpp-light"><path d="m512 334.5-81.7 141.7-.1-.1C415.8 498.4 391 512 364.3 512H102.4l102.4-177.5zm-307.2 0H0L170.3 39.3c14-24.3 40-39.3 68-39.3h159.5z" fill="#fff"/></svg>
package/index.js ADDED
@@ -0,0 +1,318 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync, statSync } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { basename, delimiter, join } from 'node:path'
5
+
6
+ import z from '@deepseek-ai/schemastery'
7
+ import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
8
+
9
+ const REMOTE_NS = 'llamaCpp'
10
+ const REMOTE_METHOD_DESCRIPTOR = '@deepseek-ai/dsh-typert-protocol/remote-methods'
11
+
12
+ /** Where a path came from, so the Models card can explain it. */
13
+ function locate(configured, detect) {
14
+ if (configured) return { path: configured, source: 'config', exists: existsSync(configured) }
15
+ const found = detect()
16
+ return found ? { path: found, source: 'auto', exists: true } : { path: '', source: 'none', exists: false }
17
+ }
18
+
19
+ /** Read-only facts the Models card shows under Llama.cpp. */
20
+ function makeInfoService(getConfig) {
21
+ class LlamaCppInfo extends TypertRemoteService {
22
+ constructor(ctx) { super(ctx, REMOTE_NS) }
23
+ getInfo() {
24
+ const config = getConfig()
25
+ return {
26
+ platform: process.platform,
27
+ binary: locate('', detectBinary),
28
+ preset: locate('', detectPreset),
29
+ }
30
+ }
31
+ }
32
+ Object.defineProperty(LlamaCppInfo.prototype, REMOTE_METHOD_DESCRIPTOR, {
33
+ configurable: true,
34
+ value: Object.freeze({ version: 1, methods: Object.freeze([Object.freeze({ method: 'getInfo', invocation: Object.freeze({ kind: 'direct' }) })]) }),
35
+ })
36
+ return LlamaCppInfo
37
+ }
38
+
39
+ const isWin = process.platform === 'win32'
40
+
41
+ export const Config = z.object({
42
+ modelsMax: z.number(),
43
+ extraArgs: z.array(z.string()).default([]),
44
+ autostart: z.boolean().default(true),
45
+ offerProvider: z.boolean().default(true),
46
+ piAiEntryId: z.string().default('llm-pi-ai'),
47
+ apiKey: z.string(),
48
+ })
49
+
50
+ /** Read a field that may be a volatile reference. */
51
+ const val = (config, key) => {
52
+ const v = config[key]
53
+ return v && typeof v === 'object' && typeof v.get === 'function' ? v.get() : v
54
+ }
55
+ const ROUTE = 'llama.dsh'
56
+ const HOST = '127.0.0.1'
57
+ const PORT = 19931
58
+ const DISPLAY_NAME = 'Llama.cpp'
59
+ const PI_AI_NAME = '@deepseek-ai/dsh-llm-pi-ai'
60
+
61
+ function isExecutable(file) {
62
+ try { return statSync(file).isFile() } catch { return false }
63
+ }
64
+
65
+ /** Find llama-server or llama on PATH, then in common install dirs. */
66
+ export function detectBinary() {
67
+ const names = isWin ? ['llama-server.exe', 'llama.exe'] : ['llama-server', 'llama']
68
+ const dirs = [
69
+ ...(process.env.PATH ?? '').split(delimiter).filter(Boolean),
70
+ join(homedir(), '.local', 'bin'),
71
+ join(homedir(), '.llama-app'),
72
+ '/opt/homebrew/bin',
73
+ '/usr/local/bin',
74
+ // install.ps1 puts llama.exe here (normally already on PATH).
75
+ ...(isWin && process.env.LOCALAPPDATA ? [join(process.env.LOCALAPPDATA, 'Microsoft', 'WindowsApps')] : []),
76
+ ]
77
+ for (const name of names) {
78
+ for (const dir of dirs) {
79
+ const file = join(dir, name)
80
+ if (isExecutable(file)) return file
81
+ }
82
+ }
83
+ return undefined
84
+ }
85
+
86
+ export function detectPreset() {
87
+ const candidates = [
88
+ join(homedir(), '.config', 'llama', 'models.user.ini'),
89
+ // Llama for Windows (ggml-org/Llama-Windows UserModelOverrides.cs):
90
+ // %USERPROFILE%\.llama\models.user.ini
91
+ join(homedir(), '.llama', 'models.user.ini'),
92
+ join(homedir(), 'models.user.ini'),
93
+ ]
94
+ return candidates.find(f => existsSync(f))
95
+ }
96
+
97
+ async function healthy(host, port) {
98
+ try {
99
+ const res = await fetch(`http://${host}:${port}/health`, { signal: AbortSignal.timeout(1500) })
100
+ return res.ok
101
+ } catch { return false }
102
+ }
103
+
104
+ const hasRoute = raw => !!(raw && typeof raw === 'object' && raw.providers && raw.providers[ROUTE])
105
+
106
+ /**
107
+ * Offer llama.dsh in Models > Add model provider while it is not configured.
108
+ * The entry is declared on behalf of the llm-pi-ai namespace, so the stock
109
+ * pi-ai editor handles it. Once the user saves it, pi-ai declares the route
110
+ * itself, so this entry is withdrawn first to avoid a duplicate declaration.
111
+ */
112
+ function offerProvider(ctx, config, baseURL) {
113
+ const llm = ctx.get('llm')
114
+ if (!llm) return
115
+ const piAiEntryId = config.piAiEntryId || 'llm-pi-ai'
116
+ let handle
117
+
118
+ const withdraw = () => {
119
+ if (!handle) return
120
+ try { handle() } catch {}
121
+ handle = undefined
122
+ }
123
+ const offer = () => {
124
+ if (handle) return
125
+ try {
126
+ handle = llm.registerConfigurableProviders([{
127
+ provider: ROUTE,
128
+ displayName: DISPLAY_NAME,
129
+ settingsNs: piAiEntryId,
130
+ settingsPath: ['providers', ROUTE],
131
+ declared: true,
132
+ defaultBaseURL: baseURL,
133
+ }])
134
+ } catch (err) {
135
+ // Already declared (configured) by pi-ai: nothing to offer.
136
+ ctx.logger.debug(`llama.cpp: provider offer skipped: ${err?.message ?? err}`)
137
+ }
138
+ }
139
+
140
+ // The local server's model ids, used when a saved profile lists none.
141
+ let serverModels = []
142
+ const loadServerModels = async () => {
143
+ for (let i = 0; i < 30 && !serverModels.length; i++) {
144
+ try {
145
+ const res = await fetch(`${baseURL}/models`, { signal: AbortSignal.timeout(2000) })
146
+ const body = await res.json()
147
+ serverModels = (body?.data ?? []).map(m => m?.id).filter(Boolean)
148
+ } catch {}
149
+ if (!serverModels.length) await new Promise(r => setTimeout(r, 2000))
150
+ }
151
+ }
152
+ loadServerModels().catch(() => {})
153
+
154
+ const piAiFiber = fiber => {
155
+ const entry = fiber?.entry
156
+ return entry?.options?.id === piAiEntryId || entry?.options?.name === PI_AI_NAME
157
+ }
158
+ const configured = () => {
159
+ const editor = ctx.get('configEditor')
160
+ const layer = editor?.configuration().find(c => c.entry?.options?.id === piAiEntryId)
161
+ if (!layer) return false
162
+ return hasRoute(layer.override) || hasRoute(layer.inherited)
163
+ }
164
+
165
+ // Model discovery is keyed by namespace and pi-ai owns llm-pi-ai's, so wrap
166
+ // its function: a llama.dsh draft with no baseURL asks the local server.
167
+ const map = llm.discoveries
168
+ if (map instanceof Map) {
169
+ const wrapped = new WeakSet()
170
+ const wrap = fn => {
171
+ if (typeof fn !== 'function' || wrapped.has(fn)) return fn
172
+ const w = (request, signal) => fn(
173
+ request?.provider === ROUTE && !request.baseURL
174
+ ? { ...request, baseURL, api: request.api || 'openai-completions' }
175
+ : request,
176
+ signal,
177
+ )
178
+ wrapped.add(w)
179
+ return w
180
+ }
181
+ const originalSet = map.set
182
+ map.set = function (key, value) {
183
+ return originalSet.call(this, key, key === piAiEntryId ? wrap(value) : value)
184
+ }
185
+ if (map.has(piAiEntryId)) originalSet.call(map, piAiEntryId, wrap(map.get(piAiEntryId)))
186
+ ctx.effect(() => () => { map.set = originalSet })
187
+ } else {
188
+ ctx.logger.warn('llama.cpp: cannot hook model discovery; enter the baseURL on the card')
189
+ }
190
+
191
+ // Runs before pi-ai's own volatile update re-declares its directory, so the
192
+ // route is withdrawn here before pi-ai tries to declare it. A saved
193
+ // llama.dsh profile without a baseURL gets this plugin's endpoint at runtime.
194
+ ctx.on('internal/config', (fiber, next) => {
195
+ let raw = next()
196
+ if (piAiFiber(fiber)) {
197
+ if (hasRoute(raw)) {
198
+ withdraw()
199
+ const profile = raw.providers[ROUTE]
200
+ // pi-ai has no catalog for llama.dsh, so every model needs an api;
201
+ // llama-server speaks OpenAI chat completions.
202
+ // A local llama-server needs no key, but pi-ai refuses a request with
203
+ // no auth. Profiles have no apiKey field (only apiKeyEnv), yet pi-ai
204
+ // accepts an authorization header as auth, so add one at runtime
205
+ // when the user configured neither a key nor their own header.
206
+ const hdrs = (profile && profile.headers) || {}
207
+ const hasAuthHeader = Object.keys(hdrs).some(k => k.toLowerCase() === 'authorization')
208
+ const needsKey = profile && typeof profile === 'object' && !profile.apiKeyEnv && !hasAuthHeader
209
+ // pi-ai has no catalog for this route, so a profile saved without a
210
+ // model list fails validation; fall back to the server's own list.
211
+ const noModels = !!(profile && typeof profile === 'object'
212
+ && !(Array.isArray(profile.models) && profile.models.length) && serverModels.length)
213
+ if (profile && typeof profile === 'object' && (!profile.baseURL || !profile.api || !profile.displayName || needsKey || noModels)) {
214
+ raw = {
215
+ ...raw,
216
+ providers: {
217
+ ...raw.providers,
218
+ [ROUTE]: {
219
+ ...profile,
220
+ displayName: profile.displayName || DISPLAY_NAME,
221
+ api: profile.api || 'openai-completions',
222
+ ...(noModels ? { models: serverModels.map(id => ({ id, name: id })) } : {}),
223
+ baseURL: profile.baseURL || baseURL,
224
+ ...(needsKey ? { headers: { ...hdrs, authorization: `Bearer ${config.apiKey || 'llama-local'}` } } : {}),
225
+ },
226
+ },
227
+ }
228
+ }
229
+ } else queueMicrotask(() => { if (!configured()) offer() })
230
+ }
231
+ return raw
232
+ })
233
+
234
+ // internal/config is a waterfall: earlier listeners wrap later ones, and
235
+ // pi-ai validates what its next() returns. When pi-ai's listener was added
236
+ // after this one (pi-ai reloaded after this plugin started), it validated
237
+ // before this listener filled in api/models. Keep this listener last.
238
+ const keepLast = () => {
239
+ const hooks = ctx.events?._hooks?.['internal/config']
240
+ if (!Array.isArray(hooks)) return
241
+ const i = hooks.findIndex(h => h?.ctx?.fiber === ctx.fiber)
242
+ if (i >= 0 && i !== hooks.length - 1) hooks.push(hooks.splice(i, 1)[0])
243
+ }
244
+ keepLast()
245
+ ctx.on('internal/listener', (name) => {
246
+ if (name === 'internal/config') queueMicrotask(keepLast)
247
+ })
248
+
249
+ if (configured()) return
250
+ offer()
251
+ ctx.effect(() => () => withdraw())
252
+ }
253
+
254
+ export function apply(ctx, config = {}) {
255
+ // Fixed endpoint: llama serve's default port 9931 with a leading 1.
256
+ const host = HOST
257
+ const port = PORT
258
+ const baseURL = `http://${host}:${port}/v1`
259
+
260
+ // Read-only Remote the Models card uses to show where llama was found.
261
+ ctx.plugin(makeInfoService(() => config))
262
+
263
+ // At boot the llm service may not exist yet; wait for it instead of
264
+ // reading it once (which silently skipped the offer after a restart).
265
+ if (config.offerProvider !== false) {
266
+ ctx.inject(['llm'], ctx => offerProvider(ctx, config, baseURL))
267
+ }
268
+ if (config.autostart === false) return
269
+
270
+ let child
271
+ let stopped = false
272
+
273
+ const start = async () => {
274
+ if (await healthy(host, port)) {
275
+ ctx.logger.info(`llama.cpp: server already running at ${host}:${port}, reusing it`)
276
+ return
277
+ }
278
+ if (stopped) return
279
+ const binary = detectBinary()
280
+ if (!binary) {
281
+ ctx.logger.warn('llama.cpp: no llama-server or llama executable found; install llama.cpp and restart DSH')
282
+ return
283
+ }
284
+ const preset = detectPreset()
285
+ const args = []
286
+ // The unified `llama` CLI takes a subcommand; `llama-server` does not.
287
+ if (/^llama(\.exe)?$/i.test(basename(binary))) args.push('serve')
288
+ args.push('--host', host, '--port', String(port))
289
+ if (preset) args.push('--models-preset', preset)
290
+ if (config.modelsMax !== undefined) args.push('--models-max', String(config.modelsMax))
291
+ if (Array.isArray(config.extraArgs)) args.push(...config.extraArgs.map(String))
292
+
293
+ ctx.logger.info(`llama.cpp: starting ${binary} ${args.join(' ')}`)
294
+ child = spawn(binary, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
295
+ const relay = chunk => {
296
+ for (const line of String(chunk).split(/\r?\n/)) if (line.trim()) ctx.logger.debug(`llama.cpp: ${line}`)
297
+ }
298
+ child.stdout.on('data', relay)
299
+ child.stderr.on('data', relay)
300
+ child.on('error', err => ctx.logger.error(`llama.cpp: failed to start: ${err.message}`))
301
+ child.on('exit', (code, signal) => {
302
+ if (!stopped) ctx.logger.warn(`llama.cpp: server exited (code ${code}, signal ${signal})`)
303
+ child = undefined
304
+ })
305
+ }
306
+
307
+ ctx.effect(() => {
308
+ start().catch(err => ctx.logger.error(err))
309
+ return () => {
310
+ stopped = true
311
+ if (child && child.exitCode === null) {
312
+ const c = child
313
+ c.kill('SIGTERM')
314
+ setTimeout(() => { if (c.exitCode === null) c.kill('SIGKILL') }, 5000).unref?.()
315
+ }
316
+ }
317
+ })
318
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Llama.cpp",
4
+ "description": "Starts a local llama.cpp server with DSH and adds a Llama.cpp provider under Settings → Models.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Llama.cpp",
4
+ "description": "随 DSH 自动启动本机 llama.cpp 服务,并在「设置 → 模型」中提供 Llama.cpp 供应商。",
5
+ "detail": "docs/DETAIL.zh.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "dsh-llama-cpp-provider",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "description": "Starts llama.cpp's server with DSH and adds a Llama.cpp model provider.",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./client": "./client.js",
9
+ "./locale/*.json": "./locale/*.json",
10
+ "./icon": "./icon.svg"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "client.js",
15
+ "cordis.patch.yml",
16
+ "locale/*.json",
17
+ "icon.svg",
18
+ "README.md",
19
+ "docs",
20
+ "LICENSE"
21
+ ],
22
+ "peerDependencies": {
23
+ "@deepseek-ai/schemastery": "*",
24
+ "@deepseek-ai/dsh-typert-protocol": "*"
25
+ },
26
+ "dsh": {
27
+ "bundle": {
28
+ "patch": "./cordis.patch.yml"
29
+ },
30
+ "client": {
31
+ "platform": "web",
32
+ "immediately": true,
33
+ "inject": [
34
+ "@deepseek-ai/dsh-api-remotes",
35
+ "@deepseek-ai/dsh-client-locale",
36
+ "@deepseek-ai/dsh-client-ui-settings-models"
37
+ ]
38
+ }
39
+ },
40
+ "license": "MIT",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/sparkwj/dsh-llama-cpp.git"
44
+ }
45
+ }