@deepseek-ai/dsh-plugin-manager 0.2.2-alpha.3 → 0.2.2-rc.2
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.i18n.yaml +4 -4
- package/README.md +6 -5
- package/README.zh.md +6 -5
- package/lib/index.js +255 -68
- package/lib/typert.host.js +84 -66
- package/lib/typert.remote-client.d.ts.map +1 -0
- package/lib/typert.remote-client.js +77 -59
- package/lib/types/build-approval.d.ts.map +1 -0
- package/lib/types/build-approval.js.map +1 -0
- package/lib/types/bundle-detail.d.ts.map +1 -0
- package/lib/types/bundle-detail.js.map +1 -0
- package/lib/types/diagnostic.d.ts.map +1 -0
- package/lib/types/diagnostic.js +1 -0
- package/lib/types/diagnostic.js.map +1 -0
- package/lib/types/failure.d.ts.map +1 -0
- package/lib/types/failure.js.map +1 -0
- package/lib/types/git-transport.d.ts.map +1 -0
- package/lib/types/git-transport.js.map +1 -0
- package/lib/types/github-connection.d.ts +16 -5
- package/lib/types/github-connection.d.ts.map +1 -0
- package/lib/types/github-connection.js +18 -8
- package/lib/types/github-connection.js.map +1 -0
- package/lib/types/index.d.ts +39 -10
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +144 -46
- package/lib/types/index.js.map +1 -0
- package/lib/types/install-failure.d.ts.map +1 -0
- package/lib/types/install-failure.js.map +1 -0
- package/lib/types/install-spec.d.ts +13 -1
- package/lib/types/install-spec.d.ts.map +1 -0
- package/lib/types/install-spec.js +41 -1
- package/lib/types/install-spec.js.map +1 -0
- package/lib/types/official-install-target.d.ts.map +1 -0
- package/lib/types/official-install-target.js.map +1 -0
- package/lib/types/operations.d.ts +16 -4
- package/lib/types/operations.d.ts.map +1 -0
- package/lib/types/operations.js +38 -5
- package/lib/types/operations.js.map +1 -0
- package/lib/types/patch.d.ts.map +1 -0
- package/lib/types/patch.js.map +1 -0
- package/lib/types/registry.d.ts.map +1 -0
- package/lib/types/registry.js.map +1 -0
- package/lib/types/run-tree.d.ts.map +1 -0
- package/lib/types/run-tree.js.map +1 -0
- package/lib/types/tools.d.ts.map +1 -0
- package/lib/types/tools.js +2 -1
- package/lib/types/tools.js.map +1 -0
- package/lib/types/types.d.ts +31 -5
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js.map +1 -0
- package/lib/types/versions.d.ts.map +1 -0
- package/lib/types/versions.js.map +1 -0
- package/package.json +45 -41
- package/src/build-approval.ts +96 -0
- package/src/bundle-detail.ts +104 -0
- package/src/diagnostic.ts +86 -0
- package/src/failure.ts +29 -0
- package/src/git-transport.ts +72 -0
- package/src/github-connection.ts +102 -0
- package/src/index.ts +1458 -0
- package/src/install-failure.ts +44 -0
- package/src/install-spec.ts +159 -0
- package/src/official-install-target.ts +58 -0
- package/src/operations.ts +695 -0
- package/src/patch.ts +78 -0
- package/src/registry.ts +98 -0
- package/src/run-tree.ts +77 -0
- package/src/tools.ts +164 -0
- package/src/types.ts +477 -0
- package/src/versions.ts +80 -0
package/src/patch.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** Comment-preserving profile plugin enablement edits and the entry flattening they compare against. */
|
|
2
|
+
import { readFile } from 'node:fs/promises'
|
|
3
|
+
import { isMap, isNode, isScalar, isSeq, parseDocument } from 'yaml'
|
|
4
|
+
import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
|
|
5
|
+
import { composeEntries, loadOptionalPatches, readBundlePatches, type ProfileContext } from '@deepseek-ai/dsh-app-boot'
|
|
6
|
+
import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write'
|
|
7
|
+
|
|
8
|
+
/** Flatten only the groups addressable by the profile's patch composer.
|
|
9
|
+
* @param rows Composed top-level entries.
|
|
10
|
+
* @returns Entries in depth-first order.
|
|
11
|
+
*/
|
|
12
|
+
export function flatten(rows: EntryOptions[]): EntryOptions[] {
|
|
13
|
+
return rows.flatMap(row => [row, ...(row.group && Array.isArray(row.config) ? flatten(row.config as EntryOptions[]) : [])])
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Replace the last matching override or append one after existing insertions. An override that holds only `id` and
|
|
17
|
+
* `disabled`, without anchors, is removed, or not appended, when the bundle layers and the remaining profile patches
|
|
18
|
+
* already give the entry the requested literal `disabled` value; home patches and launch overlays are not consulted.
|
|
19
|
+
* @param profile Profile whose patch file is edited and whose selected bundles supply the compared composition.
|
|
20
|
+
* @param id Unique composition entry id.
|
|
21
|
+
* @param name Module name used to match name-qualified overrides.
|
|
22
|
+
* @param enabled Desired entry enablement.
|
|
23
|
+
* @returns Whether the file changed.
|
|
24
|
+
*/
|
|
25
|
+
export async function writePluginEnabled(profile: ProfileContext, id: string, name: string, enabled: boolean): Promise<boolean> {
|
|
26
|
+
const filename = profile.patchPath
|
|
27
|
+
let text: string
|
|
28
|
+
try {
|
|
29
|
+
text = await readFile(filename, 'utf8')
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
32
|
+
text = '[]\n'
|
|
33
|
+
}
|
|
34
|
+
const document = parseDocument(text, {
|
|
35
|
+
customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: (value: string) => value }],
|
|
36
|
+
})
|
|
37
|
+
const error = document.errors[0]
|
|
38
|
+
if (error !== undefined) throw error
|
|
39
|
+
if (!isSeq(document.contents)) throw new Error('Profile patch must be a YAML sequence')
|
|
40
|
+
const patches = loadOptionalPatches('dsh', filename) ?? []
|
|
41
|
+
const bundlePatches = readBundlePatches('dsh', profile)
|
|
42
|
+
const items = document.contents.items
|
|
43
|
+
const target = items.findLast((item, index) => {
|
|
44
|
+
if (!isMap(item) || document.getIn([index, 'id']) !== id || item.has('insert')) return false
|
|
45
|
+
const expectedName = document.getIn([index, 'name'])
|
|
46
|
+
return !expectedName || expectedName === name
|
|
47
|
+
})
|
|
48
|
+
// Compares the entry's own literal `disabled`; a `!!js` value never matches, so its override is kept.
|
|
49
|
+
const implied = (index: number): boolean => {
|
|
50
|
+
const row = flatten(composeEntries([[...bundlePatches, ...patches.toSpliced(index, 1)]])).findLast(entry => entry.id === id)
|
|
51
|
+
return row !== undefined && (row.disabled ?? false) === !enabled
|
|
52
|
+
}
|
|
53
|
+
if (isMap(target)) {
|
|
54
|
+
const index = items.indexOf(target)
|
|
55
|
+
// A removed anchor would leave later aliases unresolved.
|
|
56
|
+
const onlySwitch = target.anchor === undefined && target.items.every(pair => isScalar(pair.key) && isScalar(pair.value)
|
|
57
|
+
&& pair.key.anchor === undefined && pair.value.anchor === undefined && (pair.key.value === 'id' || pair.key.value === 'disabled'))
|
|
58
|
+
if (onlySwitch && implied(index)) {
|
|
59
|
+
document.deleteIn([index])
|
|
60
|
+
// The comment above the removed override can be the file header, so it moves to the following item, above an
|
|
61
|
+
// emptied sequence, or after the remaining items.
|
|
62
|
+
const comment = target.commentBefore
|
|
63
|
+
const next = items[index]
|
|
64
|
+
if (comment && isNode(next)) next.commentBefore = next.commentBefore ? `${comment}\n${next.commentBefore}` : comment
|
|
65
|
+
else if (comment && items.length === 0) document.contents.commentBefore = comment
|
|
66
|
+
else if (comment) document.comment = document.comment ? `${comment}\n${document.comment}` : comment
|
|
67
|
+
} else if (document.getIn([index, 'disabled']) === !enabled) {
|
|
68
|
+
return false
|
|
69
|
+
} else {
|
|
70
|
+
document.setIn([index, 'disabled'], !enabled)
|
|
71
|
+
}
|
|
72
|
+
} else {
|
|
73
|
+
if (implied(items.length)) return false
|
|
74
|
+
document.add({ id, disabled: !enabled })
|
|
75
|
+
}
|
|
76
|
+
await writeFileAtomic(filename, String(document), { mode: 0o600 })
|
|
77
|
+
return true
|
|
78
|
+
}
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which registries one package operation asks, in order, and what a failed
|
|
3
|
+
* attempt could not reach. A registry is asked with pnpm's `--registry`;
|
|
4
|
+
* `null` is the one pnpm's own configuration names. This module runs in the
|
|
5
|
+
* browser too, through the package's `./registry` entry, so the dialog and
|
|
6
|
+
* the Host follow one rule.
|
|
7
|
+
* @module @deepseek-ai/dsh-plugin-manager/registry
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ParsedInstallSpec } from './install-spec.ts'
|
|
11
|
+
import type { PluginInstallFailureKind, PluginRegistries, Registry } from './types.ts'
|
|
12
|
+
|
|
13
|
+
/** npm's own registry: what pnpm names without any configuration, and the one public registry a plan trusts as such. */
|
|
14
|
+
export const OFFICIAL_NPM_REGISTRY = 'https://registry.npmjs.org/'
|
|
15
|
+
|
|
16
|
+
/** Public npmmirror URL shared by the fallback configuration and public-registry comparison. */
|
|
17
|
+
export const NPMMIRROR_REGISTRY = 'https://registry.npmmirror.com/'
|
|
18
|
+
|
|
19
|
+
/** An http(s) URL, as pnpm's `--registry` takes it. */
|
|
20
|
+
export const REGISTRY_URL = /^https?:\/\/\S+$/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Parse a registry URL into the form pnpm compares registries in: lower-case host, trailing slash.
|
|
24
|
+
* @param url - the registry as configured or requested.
|
|
25
|
+
* @returns the normalized URL.
|
|
26
|
+
* @throws {Error} for anything but an http(s) URL.
|
|
27
|
+
*/
|
|
28
|
+
export function normalizeRegistry(url: string): string {
|
|
29
|
+
let parsed: URL | undefined
|
|
30
|
+
try { parsed = new URL(url) }
|
|
31
|
+
catch { /* named below: only an http(s) URL is a registry */ }
|
|
32
|
+
if (parsed === undefined || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
|
|
33
|
+
throw new Error(`a registry must be an http(s) URL: ${url}`)
|
|
34
|
+
}
|
|
35
|
+
if (!parsed.pathname.endsWith('/')) parsed.pathname += '/'
|
|
36
|
+
return parsed.href
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The registries one operation asks, first to last.
|
|
41
|
+
*
|
|
42
|
+
* The configured set is the configured first registry and the fallbacks; a
|
|
43
|
+
* requested registry is asked first when it is one of them, alone otherwise,
|
|
44
|
+
* so a private registry never falls through to a public one. pnpm's own
|
|
45
|
+
* registry (`null`) belongs to the set only when what it names is known to
|
|
46
|
+
* be public: npm's own registry or one of the configured fallbacks. While it
|
|
47
|
+
* names anything else, or is unknown, it is asked alone, and a public
|
|
48
|
+
* registry asked instead never falls back into it. A registry pnpm's own
|
|
49
|
+
* configuration already names is asked once.
|
|
50
|
+
* @param requested - the caller's registry; undefined defers to the configured first one.
|
|
51
|
+
* @param configured - the configured first registry, the fallbacks after it, and what pnpm's own configuration names.
|
|
52
|
+
* @returns the registries to ask, in order; never empty.
|
|
53
|
+
*/
|
|
54
|
+
export function registryPlan(requested: Registry | undefined, configured: PluginRegistries): Registry[] {
|
|
55
|
+
const own = configured.resolved === null ? null : normalizeRegistry(configured.resolved)
|
|
56
|
+
const fallbacks = configured.fallbackRegistries.map(normalizeRegistry)
|
|
57
|
+
const ownIsPublic = own !== null && (own === OFFICIAL_NPM_REGISTRY || fallbacks.includes(own))
|
|
58
|
+
// What a registry is compared as: pnpm's own registry stands for the URL it names, once that is known.
|
|
59
|
+
const keyOf = (registry: Registry): string | null => registry === null ? own : normalizeRegistry(registry)
|
|
60
|
+
const known: Registry[] = []
|
|
61
|
+
const keys: (string | null)[] = []
|
|
62
|
+
for (const registry of [configured.registry, ...configured.fallbackRegistries]) {
|
|
63
|
+
if (registry === null && !ownIsPublic) continue
|
|
64
|
+
const key = keyOf(registry)
|
|
65
|
+
if (keys.includes(key)) continue
|
|
66
|
+
known.push(registry === null ? null : normalizeRegistry(registry))
|
|
67
|
+
keys.push(key)
|
|
68
|
+
}
|
|
69
|
+
const first = requested === undefined ? configured.registry : requested
|
|
70
|
+
const firstKey = keyOf(first)
|
|
71
|
+
const normalizedFirst = first === null ? null : normalizeRegistry(first)
|
|
72
|
+
// A private or unknown registry of pnpm's own, whichever way it was asked for, is asked alone.
|
|
73
|
+
if ((first === null || firstKey === own) && !ownIsPublic) return [normalizedFirst]
|
|
74
|
+
if (!keys.includes(firstKey)) return [normalizedFirst]
|
|
75
|
+
return [normalizedFirst, ...known.filter((_registry, index) => keys[index] !== firstKey)]
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The failures after which another registry can answer differently: this one was unreachable, or its copy may be stale. */
|
|
79
|
+
const NEXT_REGISTRY_KINDS: ReadonlySet<PluginInstallFailureKind> = new Set(['network', 'timeout', 'not-found', 'no-matching-version'])
|
|
80
|
+
|
|
81
|
+
/** A line of pnpm or git output that reports a failure, as opposed to a warning or progress line. */
|
|
82
|
+
const ERROR_LINE = /ERR_|ERROR|\berror\b|fatal:|Could not resolve|unable to access|ssh:|\bE[A-Z]{4,}\b/
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* What a failed attempt could not reach or get an answer from.
|
|
86
|
+
* @param kind - how the attempt failed.
|
|
87
|
+
* @param log - what the attempt printed.
|
|
88
|
+
* @param spec - the spec the attempt installed.
|
|
89
|
+
* @returns `registry` for a failure another registry can change; `spec-host` when an error line names the host a git
|
|
90
|
+
* or tarball spec is fetched from, which no registry stands in for; `other` for a failure neither explains.
|
|
91
|
+
*/
|
|
92
|
+
export function attributeFailure(kind: PluginInstallFailureKind, log: string, spec: ParsedInstallSpec): 'registry' | 'spec-host' | 'other' {
|
|
93
|
+
if (!NEXT_REGISTRY_KINDS.has(kind)) return 'other'
|
|
94
|
+
const host = spec.kind === 'git' || spec.kind === 'tarball' ? spec.host?.toLowerCase() : undefined
|
|
95
|
+
if (host === undefined) return 'registry'
|
|
96
|
+
const named = log.split('\n').some(line => ERROR_LINE.test(line) && line.toLowerCase().includes(host))
|
|
97
|
+
return named ? 'spec-host' : 'registry'
|
|
98
|
+
}
|
package/src/run-tree.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/** Waiting for one package run's process tree to disappear before its caller touches the profile. */
|
|
2
|
+
|
|
3
|
+
/** How long a terminated tree may take to disappear before the caller stops waiting. */
|
|
4
|
+
const TREE_WAIT_MS = 5_000
|
|
5
|
+
|
|
6
|
+
/** Poll cadence while waiting for a terminated tree to disappear. */
|
|
7
|
+
const TREE_POLL_MS = 15
|
|
8
|
+
|
|
9
|
+
/** The process (or process group) one run occupies. */
|
|
10
|
+
export interface RunTree {
|
|
11
|
+
/** The run's process id, when its spawn published one. */
|
|
12
|
+
pid: number | undefined
|
|
13
|
+
/** Whether the run leads its own process group, which is what a POSIX group probe addresses. */
|
|
14
|
+
grouped: boolean
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Injectable process operations, so every platform's probing is testable on any host. */
|
|
18
|
+
export interface RunTreeInternals {
|
|
19
|
+
/** Host platform override for target decisions. */
|
|
20
|
+
platform?: NodeJS.Platform
|
|
21
|
+
/** Liveness probe override, defaulting to `process.kill(target, 0)`. */
|
|
22
|
+
alive?: (target: number) => boolean
|
|
23
|
+
/** Wait bound override, defaulting to the tree wait constant. */
|
|
24
|
+
waitMs?: number
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Whether one run leads its own process group, which is the target a POSIX
|
|
29
|
+
* liveness probe addresses for the whole tree. A run that captures output is
|
|
30
|
+
* spawned as its own group leader, because its tree is terminated as a unit; a
|
|
31
|
+
* run that inherits the caller's descriptors keeps the caller's group, so an
|
|
32
|
+
* interrupt still reaches it.
|
|
33
|
+
* @param execution Whether the run captures output or inherits the caller's descriptors.
|
|
34
|
+
* @param platform Host platform deciding how a tree is addressed.
|
|
35
|
+
* @returns True when the run leads its own process group.
|
|
36
|
+
*/
|
|
37
|
+
export function leadsOwnGroup(execution: 'cli' | 'service', platform: NodeJS.Platform = process.platform): boolean {
|
|
38
|
+
return execution === 'service' && platform !== 'win32'
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The target a tree probe addresses: a POSIX group when the run leads one, else the process itself. */
|
|
42
|
+
function targetOf(pid: number, grouped: boolean, platform: NodeJS.Platform): number {
|
|
43
|
+
return platform !== 'win32' && grouped ? -pid : pid
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Whether any member of a run's tree is still alive.
|
|
48
|
+
* @param tree The run's process id and whether it leads its own group.
|
|
49
|
+
* @param internals Injectable process operations.
|
|
50
|
+
* @returns True while the probe finds the process or a group member.
|
|
51
|
+
*/
|
|
52
|
+
export function treeAlive(tree: RunTree, internals: RunTreeInternals = {}): boolean {
|
|
53
|
+
const pid = tree.pid
|
|
54
|
+
if (pid === undefined) return false
|
|
55
|
+
const platform = internals.platform ?? process.platform
|
|
56
|
+
const alive = internals.alive ?? ((target: number) => { process.kill(target, 0); return true })
|
|
57
|
+
try {
|
|
58
|
+
return alive(targetOf(pid, tree.grouped, platform))
|
|
59
|
+
} catch {
|
|
60
|
+
return false
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Wait until a terminated run's tree is gone, so the caller restores and
|
|
66
|
+
* unlocks the profile only after the scripts it started stopped writing.
|
|
67
|
+
* @param tree The run's process id and whether it leads its own group.
|
|
68
|
+
* @param internals Injectable process operations.
|
|
69
|
+
* @returns Fulfillment once no member remains, or the wait bound elapsed.
|
|
70
|
+
*/
|
|
71
|
+
export async function awaitTreeGone(tree: RunTree, internals: RunTreeInternals = {}): Promise<void> {
|
|
72
|
+
const deadline = Date.now() + (internals.waitMs ?? TREE_WAIT_MS)
|
|
73
|
+
while (treeAlive(tree, internals)) {
|
|
74
|
+
if (Date.now() >= deadline) return
|
|
75
|
+
await new Promise(resolve => setTimeout(resolve, TREE_POLL_MS))
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/tools.ts
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/** Agent-facing current-profile management using the same service as Web controls. */
|
|
2
|
+
import { assertNever } from '@deepseek-ai/dsh-util-values'
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import type {} from './index.ts'
|
|
5
|
+
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
|
6
|
+
import type {} from '@deepseek-ai/dsh-user-approval'
|
|
7
|
+
import { approveEscalation } from '@deepseek-ai/dsh-sandbox'
|
|
8
|
+
import type { ChangeResult, ManagementError, PluginEntryId, PluginInstallFailureKind, RestartReason } from './types.ts'
|
|
9
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
10
|
+
import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
|
|
11
|
+
|
|
12
|
+
/** What the model does next for each refusal the manager reports. */
|
|
13
|
+
const ERROR_STEPS: Record<ManagementError['code'], string> = {
|
|
14
|
+
'management-required': 'This entry belongs to plugin management itself and cannot be changed.',
|
|
15
|
+
'unaddressable': 'This entry has no unique profile patch target; tell the user to edit the profile patch file directly.',
|
|
16
|
+
'unknown-plugin': 'Call list_plugins and retry with an exact entryId.',
|
|
17
|
+
'invalid-spec': 'Retry with an npm package name, a git URL, a tarball URL, or an absolute local directory.',
|
|
18
|
+
'already-installed': 'The package is already installed; to install another version, call remove_bundle first, then install_bundle again.',
|
|
19
|
+
'ambiguous-install': 'The dependency change named no single package; call list_bundles to see what was installed.',
|
|
20
|
+
'not-bundle': 'The package declares no dsh.bundle and cannot be managed as a plugin; install a DSH plugin bundle instead.',
|
|
21
|
+
'not-removable': 'Call list_bundles; only bundles marked removable can be removed.',
|
|
22
|
+
'stop-profile': 'This profile runs without HMR; tell the user to stop DSH and run `dsh plugin --profile <profile> remove <bundle>`.',
|
|
23
|
+
'bundle-in-use': 'Call list_plugins, disable the entries from other layers that still use this bundle, then retry.',
|
|
24
|
+
'stale-approval': 'Call install_bundle again without approvedBuilds to read the current pendingBuilds.',
|
|
25
|
+
'incompatible-version': 'Install a version compatible with the running DSH. A version exemption needs the user\'s explicit acceptance of crash and data-loss risk.',
|
|
26
|
+
'unsupported-platform': 'This bundle cannot run on the current Host platform; ask the user to use a supported Host.',
|
|
27
|
+
'unexpected-package': 'The source installed another package or version than requested and was rolled back; report this to the user.',
|
|
28
|
+
'operation-error': 'Report the diagnostic to the user; retry only after its cause is addressed.',
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** What the model does next for each package-manager failure. */
|
|
32
|
+
const FAILURE_STEPS: Partial<Record<PluginInstallFailureKind, string>> = {
|
|
33
|
+
'pnpm-missing': 'pnpm is not available to DSH; tell the user to install pnpm.',
|
|
34
|
+
'timeout': 'Retry, or retry with another registry.',
|
|
35
|
+
'not-found': 'Check the package name and version with the user, then retry.',
|
|
36
|
+
'no-matching-version': 'Retry with a published version.',
|
|
37
|
+
'network': 'Retry later or pass another registry.',
|
|
38
|
+
'disk-full': 'Tell the user to free disk space, then retry.',
|
|
39
|
+
'permission': 'Tell the user DSH cannot write the profile directory; retry after they fix its permissions.',
|
|
40
|
+
'build-blocked': 'Ask the user whether to allow the install scripts of the packages in pendingBuilds; if they approve, retry with approvedBuilds.',
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Why a change waits for a restart, as the model tells the user. */
|
|
44
|
+
const RESTART_STEPS: Record<RestartReason, string> = {
|
|
45
|
+
'no-hmr': 'this profile applies changes only at startup',
|
|
46
|
+
'package-moved': 'an installed package now resolves to another directory, or the change replaces a package the DSH installation provides; remove a package before installing it from another location',
|
|
47
|
+
'host-module': 'the change reaches modules DSH itself loaded',
|
|
48
|
+
'unmanaged-plugin': 'the change reaches a plugin running outside the plugin list',
|
|
49
|
+
'module-comparison': 'DSH could not compare loaded plugins with their files',
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The model-facing result of a change: the manager's result plus the next step its outcome calls for.
|
|
54
|
+
* @param result The manager's result.
|
|
55
|
+
* @returns The result with `nextStep` when it is not plainly applied.
|
|
56
|
+
*/
|
|
57
|
+
function withNextStep(result: ChangeResult): ChangeResult & { nextStep?: string } {
|
|
58
|
+
switch (result.application) {
|
|
59
|
+
case 'applied':
|
|
60
|
+
return result
|
|
61
|
+
case 'cancelled':
|
|
62
|
+
return { ...result, nextStep: 'The installation was cancelled and its files restored; nothing changed.' }
|
|
63
|
+
case 'overridden':
|
|
64
|
+
return { ...result, nextStep: 'Saved, but a higher-priority layer such as the agent preset overrides it; tell the user it is not in effect.' }
|
|
65
|
+
case 'restart-required': {
|
|
66
|
+
const reason = result.restartReason === undefined ? '' : `: ${RESTART_STEPS[result.restartReason]}`
|
|
67
|
+
return { ...result, nextStep: `Tell the user to restart DSH to apply this change${reason}.` }
|
|
68
|
+
}
|
|
69
|
+
case 'failed': {
|
|
70
|
+
const code = result.error?.code ?? 'operation-error'
|
|
71
|
+
// A refusal code is more specific than the package manager's failure kind.
|
|
72
|
+
const kind = code === 'operation-error' ? result.packageResult?.kind : undefined
|
|
73
|
+
return { ...result, nextStep: (kind === undefined ? undefined : FAILURE_STEPS[kind]) ?? ERROR_STEPS[code] }
|
|
74
|
+
}
|
|
75
|
+
/* v8 ignore next -- ChangeResult.application is a closed union */
|
|
76
|
+
default: return assertNever(result.application)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Required services for the management tool. */
|
|
81
|
+
export const inject = ['tools', 'pluginManager', 'sandboxPolicy']
|
|
82
|
+
|
|
83
|
+
/** Register one management tool for discovery and the four persistent actions.
|
|
84
|
+
* @param ctx Agent-scoped tool registration context.
|
|
85
|
+
*/
|
|
86
|
+
export function apply(ctx: Context): void {
|
|
87
|
+
ctx.tools.register(defineTool({
|
|
88
|
+
name: 'plugin_manager',
|
|
89
|
+
description: 'List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.',
|
|
90
|
+
parameters: {
|
|
91
|
+
action: { type: 'string', required: true, enum: ['list_plugins', 'list_bundles', 'set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'list_version_exemptions', 'set_version_exemption'], description: 'Management operation.' },
|
|
92
|
+
target: { type: 'string', description: 'Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle.' },
|
|
93
|
+
enabled: { type: 'boolean', description: 'Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes.' },
|
|
94
|
+
runtimeVersion: { type: 'string', description: 'For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range.' },
|
|
95
|
+
acceptRisk: { type: 'boolean', description: 'For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough.' },
|
|
96
|
+
approvedBuilds: { type: 'array', items: { type: 'string' }, description: 'For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile.' },
|
|
97
|
+
registry: { type: 'string', description: 'For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable.' },
|
|
98
|
+
offset: { type: 'number', description: 'Zero-based list offset; defaults to 0.' },
|
|
99
|
+
limit: { type: 'number', description: 'List page size, from 1 to 100; defaults to 25.' },
|
|
100
|
+
},
|
|
101
|
+
output: {
|
|
102
|
+
schema: { type: 'string' },
|
|
103
|
+
render: (_args, value) => [{ type: 'text', text: value }],
|
|
104
|
+
},
|
|
105
|
+
async execute(args, exec) {
|
|
106
|
+
const policy = ctx.sandboxPolicy.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
|
|
107
|
+
await approveEscalation({
|
|
108
|
+
requestedMode: 'danger-full-access', effectiveMode: policy.mode, subject: 'plugin management operation',
|
|
109
|
+
justification: `plugin_manager ${JSON.stringify(args)}. Profile changes persist across sessions; installed Host code runs outside the workspace sandbox.`,
|
|
110
|
+
}, { approver: ctx.get('approval'), agent: exec.agent, callId: exec.callId,
|
|
111
|
+
toolName: 'plugin_manager', signal: exec.signal })
|
|
112
|
+
exec.signal.throwIfAborted()
|
|
113
|
+
const manager = ctx.pluginManager
|
|
114
|
+
switch (args.action) {
|
|
115
|
+
case 'list_version_exemptions':
|
|
116
|
+
return JSON.stringify({ runtimeVersion: getDshRuntimeVersion(), ...manager.listVersionExemptions() })
|
|
117
|
+
case 'set_version_exemption':
|
|
118
|
+
if (args.target === undefined || args.runtimeVersion === undefined || args.enabled === undefined) {
|
|
119
|
+
throw new Error('target package-name@version, runtimeVersion, and enabled are required')
|
|
120
|
+
}
|
|
121
|
+
return JSON.stringify(withNextStep(
|
|
122
|
+
await manager.setVersionExemption(args.target, args.runtimeVersion, args.enabled, args.acceptRisk)))
|
|
123
|
+
case 'list_plugins':
|
|
124
|
+
case 'list_bundles': {
|
|
125
|
+
const offset = args.offset ?? 0
|
|
126
|
+
const limit = args.limit ?? 25
|
|
127
|
+
if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) {
|
|
128
|
+
throw new Error('offset must be a non-negative integer and limit must be an integer from 1 to 100')
|
|
129
|
+
}
|
|
130
|
+
const rows = args.action === 'list_plugins' ? await manager.listPlugins() : await manager.listBundles()
|
|
131
|
+
const entries = rows.slice(offset, offset + limit).map(({ meta: _meta, ...row }) =>
|
|
132
|
+
'rows' in row
|
|
133
|
+
// GUI listing and update eligibility do not change the tool's management operations.
|
|
134
|
+
? (({ update: _update, listedByDefault: _listedByDefault, ...bundle }) => ({
|
|
135
|
+
...bundle, rows: bundle.rows.map(({ meta: _rowMeta, ...declared }) => declared),
|
|
136
|
+
}))(row)
|
|
137
|
+
: row)
|
|
138
|
+
return JSON.stringify({ entries, total: rows.length,
|
|
139
|
+
nextOffset: offset + entries.length < rows.length ? offset + entries.length : null })
|
|
140
|
+
}
|
|
141
|
+
case 'set_plugin':
|
|
142
|
+
case 'set_bundle': {
|
|
143
|
+
if (args.target === undefined || args.enabled === undefined) throw new Error('target and enabled are required')
|
|
144
|
+
return JSON.stringify(withNextStep(await (args.action === 'set_plugin'
|
|
145
|
+
? manager.setPluginEnabled(args.target as PluginEntryId, args.enabled)
|
|
146
|
+
: manager.setBundleEnabled(args.target, args.enabled))))
|
|
147
|
+
}
|
|
148
|
+
case 'install_bundle':
|
|
149
|
+
if (args.target === undefined) throw new Error('target package spec is required')
|
|
150
|
+
return JSON.stringify(withNextStep(await manager.installBundle(args.target, {
|
|
151
|
+
...args.enabled === undefined ? {} : { enabled: args.enabled },
|
|
152
|
+
...args.approvedBuilds === undefined ? {} : { approvedBuilds: args.approvedBuilds },
|
|
153
|
+
...args.registry === undefined ? {} : { registry: args.registry },
|
|
154
|
+
})))
|
|
155
|
+
case 'remove_bundle':
|
|
156
|
+
if (args.target === undefined) throw new Error('target bundle name is required')
|
|
157
|
+
return JSON.stringify(withNextStep(await manager.removeBundle(args.target)))
|
|
158
|
+
/* v8 ignore next -- tool JSON validation rejects actions outside the declared enum */
|
|
159
|
+
default: return assertNever(args.action)
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
presentCall: args => ({ card: 'generic', title: 'Manage profile plugins', kind: args.action.startsWith('list_') ? 'read' : 'other', rawInput: args }),
|
|
163
|
+
}))
|
|
164
|
+
}
|