dsh-plugin-container-windows 0.0.0-stage → 0.5.1

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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/README.zh-CN.md +110 -0
  4. package/cordis.patch.yml +3 -0
  5. package/docs/ai-chat.png +0 -0
  6. package/docs/ai-new-session.png +0 -0
  7. package/docs/apple-container.png +0 -0
  8. package/docs/attach.png +0 -0
  9. package/docs/docker-console.png +0 -0
  10. package/docs/docker-overview.png +0 -0
  11. package/docs/docker-volumes.png +0 -0
  12. package/docs/image-architecture.png +0 -0
  13. package/docs/package-install.png +0 -0
  14. package/docs/provider-switch.png +0 -0
  15. package/docs/run-container.png +0 -0
  16. package/index.js +141 -0
  17. package/lib/client.js +4092 -0
  18. package/package.json +72 -4
  19. package/src/client/api.js +98 -0
  20. package/src/client/attach.jsx +134 -0
  21. package/src/client/build-image.jsx +224 -0
  22. package/src/client/components.jsx +325 -0
  23. package/src/client/hooks.js +161 -0
  24. package/src/client/i18n.js +602 -0
  25. package/src/client/icons.jsx +239 -0
  26. package/src/client/index.jsx +90 -0
  27. package/src/client/page.jsx +854 -0
  28. package/src/client/platforms.js +2 -0
  29. package/src/client/push-image.jsx +113 -0
  30. package/src/client/run-container.jsx +187 -0
  31. package/src/client/runs.js +182 -0
  32. package/src/client/store.js +91 -0
  33. package/src/client/styles.js +383 -0
  34. package/src/client/tabs/compose.jsx +94 -0
  35. package/src/client/tabs/console.jsx +211 -0
  36. package/src/client/tabs/containers.jsx +148 -0
  37. package/src/client/tabs/images.jsx +154 -0
  38. package/src/client/tabs/networks.jsx +91 -0
  39. package/src/client/tabs/overview.jsx +266 -0
  40. package/src/client/tabs/volumes.jsx +76 -0
  41. package/src/host/apple-cli.js +319 -0
  42. package/src/host/apple.js +495 -0
  43. package/src/host/attach.js +246 -0
  44. package/src/host/commands.js +241 -0
  45. package/src/host/docker-cli.js +468 -0
  46. package/src/host/images.js +143 -0
  47. package/src/host/jobs.js +245 -0
  48. package/src/host/parsers.js +484 -0
  49. package/src/host/runtime.js +379 -0
  50. package/src/host/service.js +892 -0
  51. package/src/host/tools.js +198 -0
  52. package/src/host/util.js +97 -0
@@ -0,0 +1,892 @@
1
+ /**
2
+ * Host-side Docker service exposed to the browser over the Connection generic
3
+ * RPC channel `/docker`.
4
+ *
5
+ * Every method returns `{ok:true,value}` or `{ok:false,error}`. There is no
6
+ * shell, no model-facing tool, and no persistence: query caches and command
7
+ * records live in this plugin's memory and disappear on unload.
8
+ */
9
+ import { homedir } from 'node:os'
10
+ import { readFileSync, statSync } from 'node:fs'
11
+
12
+ import {
13
+ CommandError,
14
+ describeCommand,
15
+ detectDestructive,
16
+ normalizeContext,
17
+ normalizeSubcommand,
18
+ parseArguments,
19
+ parseCommand,
20
+ resolveCwd,
21
+ } from './commands.js'
22
+ import { AppleProvider } from './apple.js'
23
+ import { AttachManager } from './attach.js'
24
+ import { AppleCliError, AppleCommandError } from './apple-cli.js'
25
+ import { DockerCli, DockerCliError, DockerCommandError } from './docker-cli.js'
26
+ import { LONG_JOB_MS, buildArgv, buildSpec, inspectBuildContext, platformOf, pushSpec } from './images.js'
27
+ import { JobManager } from './jobs.js'
28
+ import {
29
+ firstLine,
30
+ mapDockerInfo,
31
+ mapDockerVersion,
32
+ normalizeContainer,
33
+ normalizeImage,
34
+ normalizeNetwork,
35
+ normalizeVolume,
36
+ parseComposeList,
37
+ parseContexts,
38
+ parseNdjson,
39
+ parseSystemDf,
40
+ summarizeStderr,
41
+ } from './parsers.js'
42
+ import { createRuntimeResolver } from './runtime.js'
43
+ import { codeOf, isRecord, messageOf, optionalInteger, requireString } from './util.js'
44
+
45
+ /** Reported by `ping`; read once so it always matches the published package. */
46
+ const PLUGIN_VERSION = (() => {
47
+ try {
48
+ return String(JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version)
49
+ } catch {
50
+ return 'unknown'
51
+ }
52
+ })()
53
+
54
+ const STATUS_CACHE_MS = 1500
55
+ const CONTEXT_CACHE_MS = 10_000
56
+ const VALUE_CACHE_MS = 1500
57
+
58
+ /** @param {unknown} value */
59
+ function ok(value) {
60
+ return { ok: true, value }
61
+ }
62
+
63
+ /** @param {string} code @param {string} message @param {Record<string, unknown>} [details] */
64
+ function fail(code, message, details = {}) {
65
+ return { ok: false, error: { code, message, details } }
66
+ }
67
+
68
+ /** @param {unknown} error */
69
+ function failureFrom(error) {
70
+ if (error instanceof DockerCliError || error instanceof DockerCommandError || error instanceof AppleCliError || error instanceof AppleCommandError || error instanceof CommandError) {
71
+ return fail(error.code ?? 'docker/internal', error.message, {
72
+ ...(error.details ?? {}),
73
+ ...(error.stderr !== undefined ? { stderr: summarizeStderr(error.stderr) } : {}),
74
+ })
75
+ }
76
+ if (codeOf(error) !== undefined) return fail(codeOf(error), messageOf(error), error?.details ?? {})
77
+ return fail('docker/internal', messageOf(error))
78
+ }
79
+
80
+ /** @param {unknown} value */
81
+ function payloadOf(value) {
82
+ if (value === undefined || value === null) return {}
83
+ if (!isRecord(value)) throw new CommandError('请求参数必须是对象')
84
+ return value
85
+ }
86
+
87
+ /** @param {unknown} value @param {string} field */
88
+ function optionalString(value, field) {
89
+ if (value === undefined || value === null) return undefined
90
+ return requireString(value, field)
91
+ }
92
+
93
+ /** @param {unknown} value */
94
+ function optionalBoolean(value) {
95
+ return value === true
96
+ }
97
+
98
+ /** @param {string} value */
99
+ function safeIdentifier(value) {
100
+ const id = requireString(value, 'id', { max: 256 })
101
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,255}$/u.test(id)) throw new CommandError('资源 ID 不合法')
102
+ return id
103
+ }
104
+
105
+ /** @param {unknown} value */
106
+ function safeImageRef(value) {
107
+ const reference = requireString(value, 'image', { max: 512 })
108
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.:/@-]*$/u.test(reference)) throw new CommandError('镜像名不合法')
109
+ return reference
110
+ }
111
+
112
+ /** @param {unknown} value @param {string} field */
113
+ function stringList(value, field) {
114
+ if (value === undefined || value === null) return []
115
+ if (!Array.isArray(value)) throw new CommandError(`${field} 必须是字符串数组`)
116
+ if (value.length > 64) throw new CommandError(`${field} 数量过多`)
117
+ return value.map((entry, index) => requireString(entry, `${field}[${String(index)}]`, { max: 512 }))
118
+ }
119
+
120
+ /** @param {string} value */
121
+ function safePort(value) {
122
+ if (!/^(?:(?:\d{1,3}\.){3}\d{1,3}:)?\d{1,5}:\d{1,5}(?:\/(?:tcp|udp))?$/u.test(value) && !/^\d{1,5}(?:\/(?:tcp|udp))?$/u.test(value)) {
123
+ throw new CommandError(`端口格式不合法: ${value}(示例 8080:80)`)
124
+ }
125
+ return value
126
+ }
127
+
128
+ /** @param {string} value */
129
+ function safeEnv(value) {
130
+ if (!/^[A-Za-z_][A-Za-z0-9_]*=[^\r\n]*$/u.test(value)) throw new CommandError(`环境变量格式不合法: ${value}(示例 KEY=VALUE)`)
131
+ return value
132
+ }
133
+
134
+ export class DockerService {
135
+ /**
136
+ * @param {{
137
+ * subprocess: any,
138
+ * logger?: any,
139
+ * config?: Record<string, any>,
140
+ * env?: NodeJS.ProcessEnv,
141
+ * home?: string,
142
+ * platform?: NodeJS.Platform,
143
+ * }} options
144
+ */
145
+ constructor(options) {
146
+ this.logger = options.logger
147
+ this.config = options.config ?? {}
148
+ this.home = options.home ?? homedir()
149
+ this.env = options.env ?? process.env
150
+ this.platform = options.platform ?? process.platform
151
+ this.cli = new DockerCli({
152
+ subprocess: options.subprocess,
153
+ config: this.config,
154
+ env: this.env,
155
+ home: this.home,
156
+ platform: this.platform,
157
+ logger: this.logger,
158
+ })
159
+ this.jobs = new JobManager({
160
+ subprocess: options.subprocess,
161
+ cli: this.cli,
162
+ maxOutputBytes: Number(this.config.maxOutputBytes ?? 1024 * 1024),
163
+ maxRuns: Number(this.config.maxConcurrentRuns ?? 4),
164
+ idPrefix: 'docker',
165
+ })
166
+ this.runtime = createRuntimeResolver({
167
+ cli: this.cli,
168
+ platform: this.platform,
169
+ home: this.home,
170
+ env: this.env,
171
+ config: this.config,
172
+ })
173
+ this.attach = new AttachManager({
174
+ subprocess: options.subprocess,
175
+ maxBytes: Number(this.config.maxOutputBytes ?? 1024 * 1024),
176
+ maxSessions: Number(this.config.maxAttachSessions ?? 2),
177
+ })
178
+ this.apple = new AppleProvider({
179
+ subprocess: options.subprocess,
180
+ config: this.config,
181
+ env: this.env,
182
+ home: this.home,
183
+ platform: this.platform,
184
+ logger: this.logger,
185
+ })
186
+ this.contextsCache = undefined
187
+ this.toolsEnabled = false
188
+ this.imageArchCache = new Map()
189
+ this.statusCache = new Map()
190
+ this.valueCache = new Map()
191
+ }
192
+
193
+ /** @param {string} method @param {unknown} rawPayload @param {AbortSignal | undefined} signal @param {any} peer */
194
+ async handle(method, rawPayload, signal, peer) {
195
+ try {
196
+ if (peer?.principal?.kind !== 'owner') return fail('docker/forbidden', '只有 DSH owner 会话可以访问本机 Docker')
197
+ const payload = payloadOf(rawPayload)
198
+ const provider = this.providerOf(payload)
199
+ if (provider === 'apple-container' && this.platform !== 'darwin') {
200
+ return fail('docker/unsupported', 'Apple container 仅支持 macOS;当前平台请使用 Docker')
201
+ }
202
+ switch (method) {
203
+ case 'ping':
204
+ return ok({
205
+ ok: true,
206
+ plugin: 'dsh-plugin-container',
207
+ version: PLUGIN_VERSION,
208
+ dockerPath: this.cli.dockerPath ?? null,
209
+ containerPath: this.apple.cli.containerPath ?? null,
210
+ })
211
+ case 'providers':
212
+ return ok(await this.providers(signal))
213
+ case 'buildContext':
214
+ return ok(inspectBuildContext(payload.path))
215
+ case 'status':
216
+ case 'list':
217
+ case 'inspect':
218
+ case 'run':
219
+ case 'action':
220
+ case 'runtimeAction':
221
+ if (provider === 'apple-container') return ok(await this.apple[method](payload, signal))
222
+ if (method === 'action') return ok(await this.action(payload, signal))
223
+ return ok(await this[method](payload, signal))
224
+ case 'attach':
225
+ return ok(await this.attachStart(provider, payload, signal))
226
+ case 'attachPoll':
227
+ return ok(this.attach.poll(payload))
228
+ case 'attachInput':
229
+ return ok(await this.attach.write(payload))
230
+ case 'attachResize':
231
+ return ok(await this.attach.resize(payload))
232
+ case 'attachClose':
233
+ return ok(await this.attach.close(payload))
234
+ case 'poll':
235
+ case 'cancel': {
236
+ const runProvider = this.providerForRun(payload)
237
+ if (runProvider === 'apple-container') return ok(this.apple[method](payload))
238
+ return ok(method === 'poll' ? this.jobs.poll(this.pollInput(payload)) : this.jobs.cancel(requireString(payload.runId, 'runId')))
239
+ }
240
+ default:
241
+ return fail('docker/unknown-method', `未知的 RPC 方法: ${String(method)}`)
242
+ }
243
+ } catch (error) {
244
+ return failureFrom(error)
245
+ }
246
+ }
247
+
248
+ /** @param {Record<string, any>} payload */
249
+ providerOf(payload) {
250
+ return payload.provider === 'apple-container' || payload.provider === 'apple' ? 'apple-container' : 'docker'
251
+ }
252
+
253
+ /** @param {Record<string, any>} payload */
254
+ providerForRun(payload) {
255
+ const runId = typeof payload.runId === 'string' ? payload.runId : ''
256
+ if (runId.startsWith('apple_')) return 'apple-container'
257
+ if (runId.startsWith('docker_')) return 'docker'
258
+ return this.providerOf(payload)
259
+ }
260
+
261
+ enableTools() {
262
+ this.toolsEnabled = true
263
+ }
264
+
265
+ /** @param {AbortSignal | undefined} signal */
266
+ async providers(signal) {
267
+ const providers = []
268
+ try {
269
+ const path = await this.cli.ensureDocker({ signal })
270
+ providers.push({ id: 'docker', label: 'Docker', available: true, runtime: 'docker', detail: path })
271
+ } catch (error) {
272
+ providers.push({ id: 'docker', label: 'Docker', available: false, runtime: 'docker', detail: messageOf(error) })
273
+ }
274
+ providers.push(this.platform === 'darwin'
275
+ ? await this.apple.info(signal)
276
+ : { id: 'apple-container', label: 'Apple container', available: false, running: false, detail: '仅支持 macOS' })
277
+ const defaultProvider = providers.find((provider) => provider.id === 'docker' && provider.available)?.id ?? providers.find((provider) => provider.available)?.id ?? 'docker'
278
+ const features = ['attach', 'exec', 'run', 'image-architecture', 'image-push', 'image-build']
279
+ if (this.toolsEnabled) features.push('ai-tools')
280
+ return { providers, defaultProvider, features }
281
+ }
282
+
283
+ /** @param {Record<string, any>} payload */
284
+ pollInput(payload) {
285
+ return {
286
+ runId: requireString(payload.runId, 'runId'),
287
+ stdoutOffset: optionalInteger(payload.stdoutOffset, 'stdoutOffset', { min: 0 }),
288
+ stderrOffset: optionalInteger(payload.stderrOffset, 'stderrOffset', { min: 0 }),
289
+ }
290
+ }
291
+
292
+ /** @param {AbortSignal | undefined} signal */
293
+ async loadContexts(signal) {
294
+ const now = Date.now()
295
+ if (this.contextsCache !== undefined && now - this.contextsCache.at < CONTEXT_CACHE_MS) return this.contextsCache.value
296
+ let value = []
297
+ try {
298
+ await this.cli.ensureDocker({ signal })
299
+ const result = await this.cli.docker(['context', 'ls', '--format', 'json'], { context: null, signal, timeoutMs: 10_000 })
300
+ value = parseContexts(result.stdout).contexts
301
+ } catch (error) {
302
+ if (!(error instanceof DockerCliError)) {
303
+ this.logger?.warn?.(`docker status: context discovery failed: ${messageOf(error)}`)
304
+ }
305
+ value = []
306
+ }
307
+ this.contextsCache = { at: now, value }
308
+ return value
309
+ }
310
+
311
+ /**
312
+ * @param {string | undefined} requested
313
+ * @param {AbortSignal | undefined} signal
314
+ * @param {{strict?: boolean}} [options]
315
+ */
316
+ async resolveContext(requested, signal, options = {}) {
317
+ const contexts = await this.loadContexts(signal)
318
+ const known = new Set(contexts.map((context) => context.name))
319
+ let name
320
+ try {
321
+ name = normalizeContext(requested, { known })
322
+ } catch (error) {
323
+ if (options.strict === false) name = null
324
+ else throw error
325
+ }
326
+ const selected = name === null ? contexts.find((context) => context.current) ?? contexts[0] ?? null : contexts.find((context) => context.name === name) ?? null
327
+ if (name !== null && selected === null) throw new CommandError(`未知的 Docker context: ${name}`, 'docker/context-unknown')
328
+ return {
329
+ contexts,
330
+ current: contexts.find((context) => context.current) ?? null,
331
+ selected,
332
+ name: selected?.name ?? null,
333
+ }
334
+ }
335
+
336
+ /** @param {unknown} value @param {string} field */
337
+ cacheKey(parts) {
338
+ return parts.map((part) => (part === undefined || part === null ? '' : String(part))).join('\u0000')
339
+ }
340
+
341
+ /** @param {string} key @param {() => Promise<any>} produce @param {number} ttl */
342
+ async cached(key, produce, ttl = VALUE_CACHE_MS) {
343
+ const now = Date.now()
344
+ const hit = this.valueCache.get(key)
345
+ if (hit !== undefined && now - hit.at < ttl) return hit.value
346
+ const value = await produce()
347
+ this.valueCache.set(key, { at: now, value })
348
+ return value
349
+ }
350
+
351
+ invalidate() {
352
+ this.statusCache.clear()
353
+ this.valueCache.clear()
354
+ }
355
+
356
+ /**
357
+ * @param {Record<string, any>} payload
358
+ * @param {AbortSignal | undefined} signal
359
+ */
360
+ async status(payload, signal) {
361
+ const requested = optionalString(payload.context, 'context')
362
+ const cacheKey = this.cacheKey(['status', requested ?? ''])
363
+ const now = Date.now()
364
+ const hit = this.statusCache.get(cacheKey)
365
+ if (hit !== undefined && now - hit.at < STATUS_CACHE_MS) return hit.value
366
+
367
+ const contexts = await this.loadContexts(signal)
368
+ const known = new Set(contexts.map((context) => context.name))
369
+ let selectedName = requested ?? null
370
+ if (selectedName !== null && !known.has(selectedName)) selectedName = null
371
+ const current = contexts.find((context) => context.current) ?? null
372
+ const selected = selectedName === null ? current ?? contexts[0] ?? null : contexts.find((context) => context.name === selectedName) ?? null
373
+
374
+ let dockerPath = null
375
+ let cliError = null
376
+ try {
377
+ dockerPath = await this.cli.ensureDocker({ signal })
378
+ } catch (error) {
379
+ cliError = error
380
+ }
381
+
382
+ let version = null
383
+ let info = null
384
+ let daemonError = null
385
+ let daemonState = 'unknown'
386
+ let versionError = null
387
+ if (dockerPath !== null) {
388
+ try {
389
+ const result = await this.cli.docker(['version', '--format', '{{json .}}'], {
390
+ context: selected?.name ?? null,
391
+ signal,
392
+ timeoutMs: 12_000,
393
+ })
394
+ version = mapDockerVersion(JSON.parse(result.stdout))
395
+ if (version.server !== null) daemonState = 'running'
396
+ } catch (error) {
397
+ versionError = error
398
+ if (error instanceof DockerCommandError) daemonError = error.stderr || error.message
399
+ }
400
+ try {
401
+ const result = await this.cli.docker(['info', '--format', '{{json .}}'], {
402
+ context: selected?.name ?? null,
403
+ signal,
404
+ timeoutMs: 15_000,
405
+ })
406
+ info = mapDockerInfo(JSON.parse(result.stdout))
407
+ daemonState = 'running'
408
+ daemonError = null
409
+ } catch (error) {
410
+ if (daemonError === null) daemonError = error instanceof DockerCommandError ? error.stderr || error.message : messageOf(error)
411
+ if (daemonState !== 'running') {
412
+ daemonState = /cannot connect|is the docker daemon running|no such host|connection refused|permission denied|docker_engine|the system cannot find the file specified|access is denied|找不到指定的文件|无法连接/iu.test(daemonError)
413
+ ? 'stopped'
414
+ : 'unreachable'
415
+ }
416
+ }
417
+ }
418
+
419
+ let runtime
420
+ try {
421
+ const resolved = await this.runtime.resolve(contexts, selected?.name ?? requested ?? null, {
422
+ running: daemonState === 'running',
423
+ error: daemonError,
424
+ }, signal)
425
+ runtime = resolved.runtime
426
+ } catch (error) {
427
+ runtime = {
428
+ kind: 'unknown',
429
+ label: 'Docker',
430
+ profile: null,
431
+ installed: null,
432
+ running: daemonState === 'running',
433
+ vmRunning: daemonState === 'running',
434
+ canStart: false,
435
+ canStop: false,
436
+ canRestart: false,
437
+ endpoint: selected?.endpoint ?? '',
438
+ details: null,
439
+ error: messageOf(error),
440
+ }
441
+ }
442
+
443
+ const warnings = []
444
+ if (selected?.error) warnings.push(selected.error)
445
+ if (daemonError) warnings.push(firstLine(daemonError))
446
+ if (versionError !== null && daemonState !== 'running') warnings.push(firstLine(messageOf(versionError)))
447
+
448
+ const value = {
449
+ provider: 'docker',
450
+ fetchedAt: Date.now(),
451
+ platform: this.platform,
452
+ cli: {
453
+ installed: dockerPath !== null,
454
+ path: dockerPath,
455
+ version: version?.client?.version ?? null,
456
+ error: cliError === null ? null : messageOf(cliError),
457
+ },
458
+ daemon: {
459
+ state: daemonState,
460
+ error: daemonError === null ? null : summarizeStderr(daemonError),
461
+ },
462
+ context: {
463
+ selected: selected?.name ?? null,
464
+ current: current?.name ?? null,
465
+ endpoint: selected?.endpoint ?? '',
466
+ description: selected?.description ?? '',
467
+ contexts,
468
+ },
469
+ client: version?.client ?? info?.client ?? null,
470
+ server: info?.server ?? version?.server ?? null,
471
+ runtime,
472
+ env: {
473
+ dockerHost: typeof this.env.DOCKER_HOST === 'string' && this.env.DOCKER_HOST !== '',
474
+ dockerContext: typeof this.env.DOCKER_CONTEXT === 'string' ? this.env.DOCKER_CONTEXT : null,
475
+ },
476
+ capabilities: {
477
+ enableRuntimeControl: this.runtime.controlEnabled,
478
+ maxOutputBytes: Number(this.config.maxOutputBytes ?? 1024 * 1024),
479
+ defaultTimeoutMs: Number(this.config.defaultTimeoutMs ?? 120_000),
480
+ compose: true,
481
+ contexts: true,
482
+ canCompose: selected !== null,
483
+ },
484
+ warnings,
485
+ }
486
+ this.statusCache.set(cacheKey, { at: now, value })
487
+ return value
488
+ }
489
+
490
+ /**
491
+ * @param {Record<string, any>} payload
492
+ * @param {AbortSignal | undefined} signal
493
+ */
494
+ async list(payload, signal) {
495
+ const resource = requireString(payload.resource, 'resource')
496
+ const resolved = await this.resolveContext(optionalString(payload.context, 'context'), signal)
497
+ const context = resolved.name
498
+ const all = payload.all !== false
499
+ const key = this.cacheKey(['list', resource, context ?? '', all ? 'all' : 'running'])
500
+ return this.cached(key, async () => {
501
+ const command = {
502
+ containers: ['ps', ...(all ? ['-a'] : []), '--format', '{{json .}}'],
503
+ images: ['images', '--format', '{{json .}}'],
504
+ volumes: ['volume', 'ls', '--format', '{{json .}}'],
505
+ networks: ['network', 'ls', '--format', '{{json .}}'],
506
+ compose: ['compose', 'ls', '-a', '--format', 'json'],
507
+ disk: ['system', 'df', '--format', '{{json .}}'],
508
+ }[resource]
509
+ if (command === undefined) throw new CommandError(`不支持的资源类型: ${resource}`)
510
+ let result
511
+ try {
512
+ result = await this.cli.docker(command, { context, signal, timeoutMs: resource === 'disk' ? 30_000 : 20_000 })
513
+ } catch (error) {
514
+ if (resource !== 'compose') throw error
515
+ // Older Compose releases reject --format json; retry with the table.
516
+ result = await this.cli.docker(['compose', 'ls', '-a'], { context, signal, timeoutMs: 20_000 })
517
+ const parsed = parseComposeList(result.stdout)
518
+ return { fetchedAt: Date.now(), items: parsed.items, format: parsed.format, warnings: this.warningsOf(result.stderr) }
519
+ }
520
+ let items
521
+ let format = 'json'
522
+ if (resource === 'containers') items = parseNdjson(result.stdout).map(normalizeContainer)
523
+ else if (resource === 'images') {
524
+ items = parseNdjson(result.stdout).map(normalizeImage)
525
+ items = await this.withImageArchitectures(items, context, signal)
526
+ }
527
+ else if (resource === 'volumes') items = parseNdjson(result.stdout).map(normalizeVolume)
528
+ else if (resource === 'networks') items = parseNdjson(result.stdout).map(normalizeNetwork)
529
+ else if (resource === 'disk') items = parseSystemDf(result.stdout)
530
+ else {
531
+ const parsed = parseComposeList(result.stdout)
532
+ items = parsed.items
533
+ format = parsed.format
534
+ }
535
+ return { fetchedAt: Date.now(), items, format, warnings: this.warningsOf(result.stderr) }
536
+ })
537
+ }
538
+
539
+ /**
540
+ * `docker images` does not expose image architecture; inspect the listed IDs
541
+ * once and cache the stable platform result.
542
+ * @param {any[]} items
543
+ * @param {string | null} context
544
+ * @param {AbortSignal | undefined} signal
545
+ */
546
+ async withImageArchitectures(items, context, signal) {
547
+ if (items.length === 0) return items
548
+ const now = Date.now()
549
+ const keyFor = (id) => `${context ?? ''}\u0000${id}`
550
+ const missing = []
551
+ for (const item of items) {
552
+ const cached = this.imageArchCache.get(keyFor(item.id))
553
+ if (cached === undefined || now - cached.at > 5 * 60_000) missing.push(item.id)
554
+ }
555
+ if (missing.length > 0) {
556
+ try {
557
+ const result = await this.cli.docker(
558
+ ['image', 'inspect', '--format', '{{json .}}', ...missing.slice(0, 64)],
559
+ { context, signal, timeoutMs: 20_000, maxBytes: 4 * 1024 * 1024 },
560
+ )
561
+ const byId = new Map()
562
+ for (const line of result.stdout.split(/\r?\n/u)) {
563
+ if (line.trim() === '') continue
564
+ try {
565
+ const value = JSON.parse(line)
566
+ if (typeof value?.Id !== 'string') continue
567
+ const architecture = [value.Os, value.Architecture, value.Variant].filter(Boolean).join('/')
568
+ byId.set(value.Id, architecture)
569
+ byId.set(value.Id.replace(/^sha256:/u, ''), architecture)
570
+ } catch {
571
+ // Ignore malformed inspect output; architecture is optional metadata.
572
+ }
573
+ }
574
+ for (const id of missing) {
575
+ const full = [...byId.keys()].find((candidate) => candidate === id || candidate.startsWith(id) || id.startsWith(candidate))
576
+ const value = full === undefined ? '' : byId.get(full)
577
+ this.imageArchCache.set(keyFor(id), { at: now, value: value ?? '' })
578
+ }
579
+ } catch {
580
+ for (const id of missing) this.imageArchCache.set(keyFor(id), { at: 0, value: '' })
581
+ }
582
+ }
583
+ return items.map((item) => {
584
+ const cached = this.imageArchCache.get(keyFor(item.id))
585
+ return { ...item, architecture: cached?.value ?? '' }
586
+ })
587
+ }
588
+
589
+ /** @param {string} stderr */
590
+ warningsOf(stderr) {
591
+ const line = firstLine(stderr)
592
+ return line === '' ? [] : [line]
593
+ }
594
+
595
+ /**
596
+ * @param {Record<string, any>} payload
597
+ * @param {AbortSignal | undefined} signal
598
+ */
599
+ async inspect(payload, signal) {
600
+ const kind = requireString(payload.kind, 'kind')
601
+ if (!['container', 'image', 'volume', 'network'].includes(kind)) throw new CommandError('不支持的 inspect 类型')
602
+ const id = safeIdentifier(payload.id)
603
+ const resolved = await this.resolveContext(optionalString(payload.context, 'context'), signal)
604
+ const result = await this.cli.docker([kind, 'inspect', id], {
605
+ context: resolved.name,
606
+ signal,
607
+ timeoutMs: 20_000,
608
+ maxBytes: 4 * 1024 * 1024,
609
+ })
610
+ try {
611
+ const parsed = JSON.parse(result.stdout)
612
+ const value = Array.isArray(parsed) ? parsed[0] ?? null : parsed
613
+ return { value, raw: result.stdout, warnings: this.warningsOf(result.stderr) }
614
+ } catch (error) {
615
+ return { value: null, raw: result.stdout, parseError: messageOf(error), warnings: this.warningsOf(result.stderr) }
616
+ }
617
+ }
618
+
619
+ /**
620
+ * @param {Record<string, any>} payload
621
+ * @param {AbortSignal | undefined} signal
622
+ */
623
+ async run(payload, signal) {
624
+ const dockerPath = await this.cli.ensureDocker({ signal })
625
+ const resolved = await this.resolveContext(optionalString(payload.context, 'context'), signal)
626
+ let subargv
627
+ if (payload.argv !== undefined) {
628
+ if (payload.command !== undefined) throw new CommandError('command 和 argv 只能提供一个')
629
+ subargv = normalizeSubcommand(payload.argv, { dockerPath, platform: this.platform })
630
+ } else {
631
+ subargv = parseCommand(requireString(payload.command, 'command'), { dockerPath, platform: this.platform })
632
+ }
633
+ const context = resolved.name
634
+ const cwd = resolveCwd(payload.cwd, { fallback: this.home, statSync })
635
+ const displayCommand = describeCommand(subargv, context)
636
+ const destructive = detectDestructive(subargv)
637
+ if (destructive.dangerous && payload.confirm !== true) {
638
+ throw Object.assign(new Error(`危险操作需要确认: ${displayCommand}`), {
639
+ code: 'docker/confirmation-required',
640
+ details: { command: displayCommand, reason: destructive.reason },
641
+ })
642
+ }
643
+ const timeoutMs = optionalInteger(payload.timeoutMs, 'timeoutMs', { min: 5000, max: 30 * 60_000 }) ?? Number(this.config.defaultTimeoutMs ?? 120_000)
644
+ const argv = this.cli.argvFor(subargv, { context })
645
+ const run = this.jobs.start({
646
+ argv,
647
+ displayCommand,
648
+ context,
649
+ cwd,
650
+ title: optionalString(payload.title, 'title') ?? '',
651
+ timeoutMs,
652
+ })
653
+ this.invalidate()
654
+ return { run }
655
+ }
656
+
657
+ /**
658
+ * Start an interactive attach PTY. Docker attaches PID 1; Apple container has
659
+ * no attach verb, so it opens an exec shell in the running container.
660
+ * @param {'docker' | 'apple-container'} provider
661
+ * @param {Record<string, any>} payload
662
+ * @param {AbortSignal | undefined} signal
663
+ */
664
+ async attachStart(provider, payload, signal) {
665
+ const id = safeIdentifier(payload.id)
666
+ const name = optionalString(payload.name, 'name') ?? id
667
+ const mode = payload.mode === 'exec' ? 'exec' : 'attach'
668
+ const cols = optionalInteger(payload.cols, 'cols', { min: 20, max: 300 }) ?? 120
669
+ const rows = optionalInteger(payload.rows, 'rows', { min: 5, max: 120 }) ?? 30
670
+ if (provider === 'apple-container') {
671
+ const path = await this.apple.cli.ensureContainer({ signal })
672
+ let running = false
673
+ try {
674
+ const raw = await this.apple.cli.json(['list', '-a', '--format', 'json'], { signal, timeoutMs: 15_000 })
675
+ const found = (Array.isArray(raw) ? raw : []).find((entry) => entry?.id === id || entry?.configuration?.id === id)
676
+ running = found?.status?.state === 'running'
677
+ } catch (error) {
678
+ throw new CommandError(`无法读取 Apple container 状态: ${messageOf(error)}`, 'container/exec-failed')
679
+ }
680
+ if (!running) throw new CommandError(`容器未运行,无法 ${mode}`, 'container/not-running')
681
+ const argv = [path, 'exec', '-i', '-t', id, '/bin/sh']
682
+ return {
683
+ session: await this.attach.start({
684
+ argv,
685
+ cwd: this.home,
686
+ env: this.apple.cli.childEnv(),
687
+ provider,
688
+ containerId: id,
689
+ containerName: name,
690
+ command: `container exec -i -t ${id} /bin/sh`,
691
+ mode,
692
+ cols,
693
+ rows,
694
+ signal,
695
+ }),
696
+ }
697
+ }
698
+ await this.cli.ensureDocker({ signal })
699
+ const resolved = await this.resolveContext(optionalString(payload.context, 'context'), signal)
700
+ const context = resolved.name
701
+ const inspected = await this.cli.docker(['inspect', '--format', '{{.State.Running}}|{{.Os}}', id], {
702
+ context,
703
+ signal,
704
+ timeoutMs: 15_000,
705
+ })
706
+ const [isRunning, osType = ''] = inspected.stdout.trim().split('|')
707
+ if (isRunning !== 'true') throw new CommandError(`容器未运行,无法 ${mode}`, 'docker/not-running')
708
+ const shell = osType.toLowerCase() === 'windows' ? 'cmd.exe' : '/bin/sh'
709
+ const subargv = mode === 'exec' ? ['exec', '-i', '-t', id, shell] : ['attach', id]
710
+ return {
711
+ session: await this.attach.start({
712
+ argv: this.cli.argvFor(subargv, { context }),
713
+ cwd: this.home,
714
+ env: this.cli.childEnv(),
715
+ provider: 'docker',
716
+ containerId: id,
717
+ containerName: name,
718
+ command: describeCommand(subargv, context),
719
+ mode,
720
+ cols,
721
+ rows,
722
+ signal,
723
+ }),
724
+ }
725
+ }
726
+
727
+ /**
728
+ * Semantic quick action for Docker; provider-specific syntax is centralized here.
729
+ * @param {Record<string, any>} payload
730
+ * @param {AbortSignal | undefined} signal
731
+ */
732
+ async action(payload, signal) {
733
+ const kind = requireString(payload.kind, 'kind')
734
+ const action = requireString(payload.action, 'action')
735
+ if (kind === 'container' && action === 'run') {
736
+ const image = safeImageRef(payload.image)
737
+ const name = optionalString(payload.name, 'name')
738
+ if (name !== undefined) safeIdentifier(name)
739
+ const args = parseArguments(optionalString(payload.command, 'command') ?? '', { platform: this.platform })
740
+ const ports = stringList(payload.ports, 'ports').map(safePort)
741
+ const env = stringList(payload.env, 'env').map(safeEnv)
742
+ const argv = [
743
+ 'run',
744
+ '-d',
745
+ '-i',
746
+ '-t',
747
+ ...(name === undefined ? [] : ['--name', name]),
748
+ ...ports.flatMap((port) => ['-p', port]),
749
+ ...env.flatMap((entry) => ['-e', entry]),
750
+ image,
751
+ ...args,
752
+ ]
753
+ return this.run({
754
+ argv,
755
+ context: payload.context,
756
+ cwd: payload.cwd,
757
+ title: payload.title ?? `启动容器 ${image}`,
758
+ }, signal)
759
+ }
760
+ if (kind === 'image' && action === 'build') {
761
+ const spec = buildSpec(payload)
762
+ return this.run({
763
+ argv: buildArgv(spec),
764
+ context: payload.context,
765
+ cwd: spec.contextDir,
766
+ timeoutMs: LONG_JOB_MS,
767
+ title: payload.title ?? `构建镜像 ${spec.tag}`,
768
+ }, signal)
769
+ }
770
+ if (kind === 'image' && action === 'push') {
771
+ const { source, target } = pushSpec(payload)
772
+ if (target !== source) {
773
+ await this.cli.ensureDocker({ signal })
774
+ const resolved = await this.resolveContext(optionalString(payload.context, 'context'), signal)
775
+ await this.cli.docker(['tag', source, target], { context: resolved.name, signal, timeoutMs: 20_000 })
776
+ }
777
+ return this.run({
778
+ argv: ['push', target],
779
+ context: payload.context,
780
+ cwd: payload.cwd,
781
+ timeoutMs: LONG_JOB_MS,
782
+ title: payload.title ?? `推送镜像 ${target}`,
783
+ }, signal)
784
+ }
785
+ const id = safeIdentifier(payload.id ?? payload.reference)
786
+ let argv
787
+ if (kind === 'container') {
788
+ if (action === 'start') argv = ['start', id]
789
+ else if (action === 'stop') argv = ['stop', id]
790
+ else if (action === 'restart') argv = ['restart', id]
791
+ else if (action === 'delete') argv = ['rm', '-f', id]
792
+ else if (action === 'logs') argv = ['logs', '--tail', payload.follow === true ? '100' : '500', ...(payload.follow === true ? ['-f'] : []), id]
793
+ } else if (kind === 'image') {
794
+ if (action === 'pull') {
795
+ const platform = platformOf(payload.platform)
796
+ argv = ['pull', ...(platform === undefined ? [] : ['--platform', platform]), id]
797
+ return this.run({
798
+ argv,
799
+ context: payload.context,
800
+ cwd: payload.cwd,
801
+ timeoutMs: LONG_JOB_MS,
802
+ title: payload.title ?? `拉取镜像 ${id}`,
803
+ }, signal)
804
+ }
805
+ else if (action === 'delete') argv = ['rmi', id]
806
+ } else if (kind === 'volume' && action === 'delete') {
807
+ argv = ['volume', 'rm', id]
808
+ } else if (kind === 'network' && action === 'delete') {
809
+ argv = ['network', 'rm', id]
810
+ }
811
+ if (argv === undefined) throw new CommandError(`不支持的操作: ${kind}/${action}`)
812
+ return this.run({
813
+ argv,
814
+ context: payload.context,
815
+ cwd: payload.cwd,
816
+ confirm: payload.confirm,
817
+ timeoutMs: payload.timeoutMs,
818
+ title: payload.title ?? `${kind} ${action} ${id}`,
819
+ }, signal)
820
+ }
821
+
822
+ /**
823
+ * @param {Record<string, any>} payload
824
+ * @param {AbortSignal | undefined} signal
825
+ */
826
+ async runtimeAction(payload, signal) {
827
+ const action = requireString(payload.action, 'action')
828
+ if (!['start', 'stop', 'restart'].includes(action)) throw new CommandError('不支持的运行时操作')
829
+ if ((action === 'stop' || action === 'restart') && payload.confirm !== true) {
830
+ throw Object.assign(new Error(`停止/重启 Docker 运行时需要确认`), {
831
+ code: 'docker/confirmation-required',
832
+ details: { command: action === 'stop' ? '停止运行时' : '重启运行时', reason: 'runtime-stop' },
833
+ })
834
+ }
835
+ const status = await this.status({ context: payload.context }, signal)
836
+ const spec = this.runtime.actionSpec(action, status.runtime)
837
+ const run = this.jobs.start({
838
+ argv: spec.argv,
839
+ displayCommand: spec.displayCommand,
840
+ context: null,
841
+ cwd: this.home,
842
+ title: spec.title,
843
+ timeoutMs: spec.timeoutMs,
844
+ })
845
+ this.invalidate()
846
+ return { run, dispatched: true, message: spec.title }
847
+ }
848
+
849
+ /**
850
+ * Read container logs for a tool (not exposed as a UI RPC).
851
+ * @param {Record<string, any>} payload
852
+ * @param {AbortSignal | undefined} signal
853
+ */
854
+ async logs(payload, signal) {
855
+ const provider = payload.provider === 'apple-container' ? 'apple-container' : 'docker'
856
+ const id = safeIdentifier(payload.id)
857
+ const tail = optionalInteger(payload.tail ?? 200, 'tail', { min: 1, max: 500 })
858
+ const maxBytes = 256 * 1024
859
+ if (provider === 'apple-container') {
860
+ const path = await this.apple.cli.ensureContainer({ signal })
861
+ const result = await this.apple.cli.exec(['logs', '-n', String(tail), id], { signal, cwd: this.home, timeoutMs: 20_000, maxBytes })
862
+ const text = `${result.stdout}${result.stderr}`
863
+ if (result.timedOut) throw new CommandError('读取 Apple container 日志超时', 'container/timeout')
864
+ if (result.exitCode !== 0) {
865
+ throw Object.assign(new CommandError(text.trim() || `container logs 退出码 ${String(result.exitCode)}`, 'container/exec-failed'), { stderr: result.stderr })
866
+ }
867
+ return { provider, id, tail, text }
868
+ }
869
+ await this.cli.ensureDocker({ signal })
870
+ const resolved = await this.resolveContext(optionalString(payload.context, 'context'), signal)
871
+ const result = await this.cli.docker(['logs', '--tail', String(tail), id], {
872
+ context: resolved.name,
873
+ signal,
874
+ timeoutMs: 20_000,
875
+ maxBytes,
876
+ })
877
+ return { provider, id, tail, text: `${result.stdout}${result.stderr}` }
878
+ }
879
+
880
+ dispose() {
881
+ this.jobs.dispose()
882
+ this.attach.dispose().catch(() => {})
883
+ this.apple.dispose()
884
+ this.statusCache.clear()
885
+ this.valueCache.clear()
886
+ this.imageArchCache.clear()
887
+ }
888
+ }
889
+
890
+ export function createDockerService(options) {
891
+ return new DockerService(options)
892
+ }