@acryldev/harness-runtime 0.0.0-stage → 0.2.12

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 (167) hide show
  1. package/LICENSE +49 -0
  2. package/README.md +14 -2
  3. package/lib/index.mjs +5693 -0
  4. package/lib/index.mjs.map +1 -0
  5. package/lib/types/acryl-home.d.ts +81 -0
  6. package/lib/types/app/new-app.d.ts +65 -0
  7. package/lib/types/app/start-source.d.ts +47 -0
  8. package/lib/types/blueprint/blueprint.d.ts +74 -0
  9. package/lib/types/blueprint/brand-identity.d.ts +26 -0
  10. package/lib/types/blueprint/compose.d.ts +53 -0
  11. package/lib/types/blueprint/definition.d.ts +22 -0
  12. package/lib/types/blueprint/index.d.ts +7 -0
  13. package/lib/types/blueprint/manifest.d.ts +35 -0
  14. package/lib/types/blueprint/selection.d.ts +19 -0
  15. package/lib/types/cli-market-install.d.ts +97 -0
  16. package/lib/types/cli-market-plugins.d.ts +81 -0
  17. package/lib/types/coding-capabilities.d.ts +29 -0
  18. package/lib/types/durable-message.d.ts +18 -0
  19. package/lib/types/engine-dsh.d.ts +181 -0
  20. package/lib/types/engine-files.d.ts +8 -0
  21. package/lib/types/engine-host.d.ts +32 -0
  22. package/lib/types/engine-tools.d.ts +11 -0
  23. package/lib/types/index.d.ts +67 -0
  24. package/lib/types/instance/announce-self.d.ts +38 -0
  25. package/lib/types/instance/app-instance.d.ts +125 -0
  26. package/lib/types/instance/index.d.ts +6 -0
  27. package/lib/types/instance/offline-lock.d.ts +29 -0
  28. package/lib/types/instance/online-secret.d.ts +29 -0
  29. package/lib/types/instance/registry.d.ts +26 -0
  30. package/lib/types/instance/select.d.ts +43 -0
  31. package/lib/types/module-hooks.d.ts +19 -0
  32. package/lib/types/module-resolution.d.ts +31 -0
  33. package/lib/types/package-overlay.d.ts +41 -0
  34. package/lib/types/pinned-pnpm.d.ts +15 -0
  35. package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
  36. package/lib/types/plugin-doctor.d.ts +49 -0
  37. package/lib/types/plugin-lifecycle-state.d.ts +92 -0
  38. package/lib/types/plugin-lifecycle.d.ts +87 -0
  39. package/lib/types/profile-layout.d.ts +17 -0
  40. package/lib/types/profile-owner.d.ts +25 -0
  41. package/lib/types/profile-repair/backup.d.ts +37 -0
  42. package/lib/types/profile-repair/findings.d.ts +29 -0
  43. package/lib/types/profile-repair/index.d.ts +9 -0
  44. package/lib/types/profile-repair/inspector.d.ts +11 -0
  45. package/lib/types/profile-repair/repair.d.ts +38 -0
  46. package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
  47. package/lib/types/profile-resolution/resolver.d.ts +41 -0
  48. package/lib/types/profile-resolution/service.d.ts +22 -0
  49. package/lib/types/prompt-budget.d.ts +44 -0
  50. package/lib/types/session-bridge.d.ts +57 -0
  51. package/lib/types/session-log-exporter.d.ts +31 -0
  52. package/lib/types/system-prompt-capture.d.ts +29 -0
  53. package/lib/types/web-favicon-data.d.ts +5 -0
  54. package/lib/types/web-favicon.d.ts +23 -0
  55. package/lib/types/web-market-install.d.ts +114 -0
  56. package/lib/types/web-market-plugins.d.ts +106 -0
  57. package/lib/types/web-port.d.ts +15 -0
  58. package/package.json +211 -3
  59. package/src/acryl-home.ts +103 -0
  60. package/src/app/new-app.ts +239 -0
  61. package/src/app/start-source.ts +110 -0
  62. package/src/blueprint/blueprint.ts +141 -0
  63. package/src/blueprint/brand-identity.ts +75 -0
  64. package/src/blueprint/compose.ts +222 -0
  65. package/src/blueprint/definition.ts +92 -0
  66. package/src/blueprint/index.ts +20 -0
  67. package/src/blueprint/manifest.ts +145 -0
  68. package/src/blueprint/selection.ts +74 -0
  69. package/src/cli-market-install.ts +181 -0
  70. package/src/cli-market-plugins.ts +176 -0
  71. package/src/coding-capabilities.ts +61 -0
  72. package/src/durable-message.ts +23 -0
  73. package/src/engine-dsh.ts +856 -0
  74. package/src/engine-files.ts +9 -0
  75. package/src/engine-host.ts +128 -0
  76. package/src/engine-tools.ts +26 -0
  77. package/src/index.ts +436 -0
  78. package/src/instance/announce-self.ts +88 -0
  79. package/src/instance/app-instance.ts +240 -0
  80. package/src/instance/index.ts +45 -0
  81. package/src/instance/offline-lock.ts +71 -0
  82. package/src/instance/online-secret.ts +55 -0
  83. package/src/instance/registry.ts +53 -0
  84. package/src/instance/select.ts +134 -0
  85. package/src/module-hooks.ts +41 -0
  86. package/src/module-resolution.ts +187 -0
  87. package/src/package-overlay.ts +160 -0
  88. package/src/pinned-pnpm.ts +67 -0
  89. package/src/plugin-acryl-workspace-status.ts +99 -0
  90. package/src/plugin-doctor.ts +141 -0
  91. package/src/plugin-lifecycle-state.ts +347 -0
  92. package/src/plugin-lifecycle.ts +223 -0
  93. package/src/profile-layout.ts +97 -0
  94. package/src/profile-owner.ts +52 -0
  95. package/src/profile-repair/backup.ts +119 -0
  96. package/src/profile-repair/findings.ts +43 -0
  97. package/src/profile-repair/index.ts +10 -0
  98. package/src/profile-repair/inspector.ts +156 -0
  99. package/src/profile-repair/repair.ts +137 -0
  100. package/src/profile-resolution/moved-framework.ts +64 -0
  101. package/src/profile-resolution/resolver.ts +876 -0
  102. package/src/profile-resolution/service.ts +99 -0
  103. package/src/prompt-budget.ts +118 -0
  104. package/src/session-bridge.ts +350 -0
  105. package/src/session-log-exporter.ts +68 -0
  106. package/src/system-prompt-capture.ts +99 -0
  107. package/src/web-favicon-data.ts +6 -0
  108. package/src/web-favicon.ts +43 -0
  109. package/src/web-market-install.ts +206 -0
  110. package/src/web-market-plugins.ts +215 -0
  111. package/src/web-port.ts +39 -0
  112. package/tests/account-callback.spec.ts +173 -0
  113. package/tests/acryl-home.spec.ts +39 -0
  114. package/tests/agent-self-hosting.spec.ts +101 -0
  115. package/tests/announce-self.spec.ts +84 -0
  116. package/tests/app-lifecycle.spec.ts +99 -0
  117. package/tests/blank-blueprint.spec.ts +110 -0
  118. package/tests/blueprint-definition.spec.ts +128 -0
  119. package/tests/blueprint.spec.ts +138 -0
  120. package/tests/bulkhead.spec.ts +187 -0
  121. package/tests/coding-vocabulary.spec.ts +15 -0
  122. package/tests/dump-system-prompt.spec.ts +65 -0
  123. package/tests/e2e-real-model.spec.ts +71 -0
  124. package/tests/e2e-restart-real-model.spec.ts +77 -0
  125. package/tests/engine-dsh.spec.ts +340 -0
  126. package/tests/engine-host-mount-root-include.spec.ts +118 -0
  127. package/tests/engine-host.spec.ts +176 -0
  128. package/tests/engine-optional.spec.ts +81 -0
  129. package/tests/extension-examples.spec.ts +261 -0
  130. package/tests/hooks-thread-stack.ts +27 -0
  131. package/tests/instance-patches.spec.ts +25 -0
  132. package/tests/instance.spec.ts +235 -0
  133. package/tests/live/community-plugins.spec.ts +83 -0
  134. package/tests/module-hooks.spec.ts +35 -0
  135. package/tests/module-resolution.spec.ts +265 -0
  136. package/tests/moved-framework.spec.ts +61 -0
  137. package/tests/new-app.spec.ts +132 -0
  138. package/tests/organizer-growth.spec.ts +117 -0
  139. package/tests/pinned-pnpm.spec.ts +34 -0
  140. package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
  141. package/tests/plugin-context.spec.ts +640 -0
  142. package/tests/plugin-doctor.spec.ts +183 -0
  143. package/tests/plugin-enablement-one-store.spec.ts +130 -0
  144. package/tests/plugin-lifecycle-state.spec.ts +169 -0
  145. package/tests/profile-layout.spec.ts +58 -0
  146. package/tests/profile-owner.spec.ts +38 -0
  147. package/tests/profile-repair/profile-repair.spec.ts +231 -0
  148. package/tests/profile-resolution-port.spec.ts +30 -0
  149. package/tests/profile-resolution-service.spec.ts +273 -0
  150. package/tests/profile-resolution-swap.spec.ts +69 -0
  151. package/tests/profile-resolution.spec.ts +2535 -0
  152. package/tests/profile.spec.ts +70 -0
  153. package/tests/project-registry.spec.ts +81 -0
  154. package/tests/prompt-budget.spec.ts +58 -0
  155. package/tests/real-home-guard.spec.ts +178 -0
  156. package/tests/session-bridge.spec.ts +316 -0
  157. package/tests/start-source.spec.ts +65 -0
  158. package/tests/system-prompt-shape.spec.ts +95 -0
  159. package/tests/three-levels.spec.ts +84 -0
  160. package/tests/tool-gateway.spec.ts +116 -0
  161. package/tests/tool-schemas.spec.ts +41 -0
  162. package/tests/web-favicon.spec.ts +42 -0
  163. package/tests/web-port.spec.ts +38 -0
  164. package/tests/web-startup-hold.spec.ts +79 -0
  165. package/tsconfig.json +24 -0
  166. package/tsdown.config.ts +2 -0
  167. package/vitest.config.ts +18 -0
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Profile-relative package resolution for a Node runtime with a persistent,
3
+ * user-mutable profile directory.
4
+ *
5
+ * Extracted verbatim from acryl-desktop's own module-resolution.ts (first
6
+ * built and proven there against Electron's restricted runtime) - the two
7
+ * anchors that varied per surface (the calling installation's own entry
8
+ * module and its own package.json) are now parameters
9
+ * ({@link InstallProfilePackageResolverOptions}) instead of hardcoded
10
+ * Desktop paths; every other line, including the two-layer CJS/ESM hook
11
+ * strategy and its comments, is unchanged. Desktop's own module-resolution.ts
12
+ * is now a thin wrapper supplying its Electron-specific anchors (unpacked
13
+ * ASAR paths) to this function - its own behavior is unaffected.
14
+ */
15
+
16
+ import Module, { isBuiltin } from 'node:module'
17
+ import { basename, dirname, isAbsolute, join } from 'node:path'
18
+ import { fileURLToPath, pathToFileURL } from 'node:url'
19
+ import { requireModuleHooks } from './module-hooks.ts'
20
+ import {
21
+ findOverlayPackage,
22
+ packageNameFromSpecifier,
23
+ resolveOverlayPackage,
24
+ } from './package-overlay.ts'
25
+
26
+ interface CommonJsModuleResolver {
27
+ _resolveFilename(
28
+ request: string,
29
+ parent: { filename?: string } | null | undefined,
30
+ isMain: boolean | undefined,
31
+ options?: unknown,
32
+ ): string
33
+ }
34
+
35
+ /** Node's CommonJS package lookup list for a directory: every ancestor's node_modules, nearest first. */
36
+ function nodeModulePaths(directory: string): string[] {
37
+ const paths: string[] = []
38
+ for (let current = directory; ; current = dirname(current)) {
39
+ if (basename(current) !== 'node_modules') paths.push(join(current, 'node_modules'))
40
+ if (dirname(current) === current) return paths
41
+ }
42
+ }
43
+
44
+ function packageNameFromManifestSpecifier(specifier: string): string | undefined {
45
+ const suffix = '/package.json'
46
+ if (!specifier.endsWith(suffix)) return undefined
47
+ const packageName = specifier.slice(0, -suffix.length)
48
+ return packageNameFromSpecifier(packageName) === packageName ? packageName : undefined
49
+ }
50
+
51
+ /** Return whether a Loader request needs Node package resolution. */
52
+ function isBareSpecifier(specifier: string): boolean {
53
+ return !specifier.startsWith('.') && !specifier.startsWith('/') && !URL.canParse(specifier)
54
+ }
55
+
56
+ export interface InstallProfilePackageResolverOptions {
57
+ /** Diagnostic prefix on thrown errors - the calling surface's own bin name. */
58
+ readonly binName: string
59
+ /** File URL of the calling installation's own package.json. */
60
+ readonly installPackageUrl: string
61
+ /** File URL of the calling installation's own compiled entry module. */
62
+ readonly installEntryUrl: string
63
+ /** File URL resolved by `import.meta.resolve('@deepseek-ai/cordis-plugin-loader')`. */
64
+ readonly loaderEntryUrl: string
65
+ }
66
+
67
+ /**
68
+ * Resolve Cordis Loader bare imports from the selected persistent profile.
69
+ * @param profileBaseUrl - file URL inside the profile that owns plugin dependencies.
70
+ * @param options - the calling installation's own resolution anchors.
71
+ * @returns an idempotent hook disposer.
72
+ */
73
+ export function installProfilePackageResolver(
74
+ profileBaseUrl: string,
75
+ options: InstallProfilePackageResolverOptions,
76
+ ): () => void {
77
+ // Before `_resolveFilename` is wrapped, so a runtime without module hooks leaves nothing behind.
78
+ const registerHooks = requireModuleHooks()
79
+ const { binName, installPackageUrl, installEntryUrl, loaderEntryUrl } = options
80
+ const profileManifestPath = fileURLToPath(profileBaseUrl)
81
+ // Directory-derived `createRequire` bases (e.g. `new URL('.', profileBaseUrl)`)
82
+ // yield a synthetic `noop.js` module as the require parent; the manifest
83
+ // anchor yields the manifest path itself. Both live inside the profile
84
+ // directory, so treat any parent anchored there as profile-owned.
85
+ const profileDirPath = fileURLToPath(new URL('.', profileBaseUrl))
86
+
87
+ // ClientModuleRegistry intentionally uses createRequire(ctx.baseUrl) to
88
+ // resolve each browser bundle from the config tree. Node's ESM resolve hook
89
+ // does not observe that CommonJS manifest lookup, so without this narrow
90
+ // bridge the Loader can activate the installation's own copy while the
91
+ // browser receives an older Profile copy of the same package. Intercept
92
+ // only package manifests requested from a parent anchored in this Profile
93
+ // (the manifest itself or a synthetic module under the profile directory);
94
+ // every other CJS resolution remains untouched.
95
+ // Track the module graph rooted at every overlay-selected Loader package.
96
+ const overlayModuleUrls = new Set<string>()
97
+ const commonJsModule = Module as unknown as CommonJsModuleResolver
98
+ const previousResolveFilename = commonJsModule._resolveFilename
99
+ // The parent an installation-selected package resolves from: the installation's own manifest, with Node's node_modules lookup
100
+ // list from its directory upwards (what `Module._nodeModulePaths` computes). Made on first use, so installing the resolver converts no path.
101
+ let installParent: { filename: string, id: string, paths: string[] } | undefined
102
+ const installParentModule = () => {
103
+ if (installParent !== undefined) return installParent
104
+ const installManifestPath = fileURLToPath(installPackageUrl)
105
+ installParent = { filename: installManifestPath, id: installManifestPath, paths: nodeModulePaths(dirname(installManifestPath)) }
106
+ return installParent
107
+ }
108
+ const overlayResolveFilename: CommonJsModuleResolver['_resolveFilename'] = function (
109
+ this: CommonJsModuleResolver,
110
+ request,
111
+ parent,
112
+ isMain,
113
+ resolveOptions,
114
+ ) {
115
+ const profileAnchored = parent?.filename !== undefined
116
+ && (parent.filename === profileManifestPath || parent.filename.startsWith(profileDirPath))
117
+ const manifestPackage = profileAnchored ? packageNameFromManifestSpecifier(request) : undefined
118
+ // A bare plugin import from the Profile anchor (dsh-app-boot's root Include resolves every Loader row this way) takes the
119
+ // same overlay: a package the Profile does not hold, or holds at an older version, comes from the installation. Without
120
+ // this, a fresh Profile (no node_modules since DSH 0.2 removed the link projections) resolved no plugin at all.
121
+ const packageName = manifestPackage
122
+ ?? (profileAnchored && isBareSpecifier(request) && !isBuiltin(request) ? packageNameFromSpecifier(request) : undefined)
123
+ if (packageName !== undefined) {
124
+ const overlay = findOverlayPackage(packageName, {
125
+ binName,
126
+ installPackageUrl,
127
+ profilePackageUrl: profileBaseUrl,
128
+ })
129
+ if (overlay !== undefined) {
130
+ if (manifestPackage !== undefined) return overlay.selected.manifestPath
131
+ const target = previousResolveFilename.call(
132
+ this, request, overlay.selected.source === 'install' ? installParentModule() : parent, isMain, resolveOptions)
133
+ // The Loader imports this file next: its graph gets the Profile fallback for dependencies, as a Loader import through the ESM hook does.
134
+ if (isAbsolute(target)) overlayModuleUrls.add(pathToFileURL(target).href)
135
+ return target
136
+ }
137
+ }
138
+ return previousResolveFilename.call(this, request, parent, isMain, resolveOptions)
139
+ }
140
+ commonJsModule._resolveFilename = overlayResolveFilename
141
+ const hooks = registerHooks({
142
+ resolve(specifier, context, nextResolve) {
143
+ const fromLoader = context.parentURL === loaderEntryUrl
144
+ const packageName = fromLoader ? packageNameFromSpecifier(specifier) : undefined
145
+ if (packageName !== undefined) {
146
+ const overlay = resolveOverlayPackage(packageName, {
147
+ binName,
148
+ installPackageUrl,
149
+ profilePackageUrl: profileBaseUrl,
150
+ })
151
+ const resolved = nextResolve(specifier, {
152
+ ...context,
153
+ parentURL: overlay.selected.source === 'profile' ? profileBaseUrl : installEntryUrl,
154
+ })
155
+ overlayModuleUrls.add(resolved.url)
156
+ return resolved
157
+ }
158
+ if (context.parentURL === undefined || !overlayModuleUrls.has(context.parentURL)) {
159
+ return nextResolve(specifier, context)
160
+ }
161
+ if (!isBareSpecifier(specifier)) {
162
+ const resolved = nextResolve(specifier, context)
163
+ if (specifier.startsWith('.')) overlayModuleUrls.add(resolved.url)
164
+ return resolved
165
+ }
166
+ try {
167
+ const resolved = nextResolve(specifier, context)
168
+ overlayModuleUrls.add(resolved.url)
169
+ return resolved
170
+ } catch (cause) {
171
+ if ((cause as NodeJS.ErrnoException).code !== 'ERR_MODULE_NOT_FOUND') throw cause
172
+ const resolved = nextResolve(specifier, { ...context, parentURL: profileBaseUrl })
173
+ overlayModuleUrls.add(resolved.url)
174
+ return resolved
175
+ }
176
+ },
177
+ })
178
+ let active = true
179
+ return () => {
180
+ if (!active) return
181
+ active = false
182
+ hooks.deregister()
183
+ if (commonJsModule._resolveFilename === overlayResolveFilename) {
184
+ commonJsModule._resolveFilename = previousResolveFilename
185
+ }
186
+ }
187
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Deterministic package selection between one surface's own installation and
3
+ * one Profile - shared by every surface with a persistent, user-mutable
4
+ * profile directory (Desktop's Market-installed plugins, or any surface's
5
+ * own ACRYL-only packages a shipped DSH profile has no dependency path to).
6
+ * Extracted verbatim from acryl-desktop's own package-overlay.ts (first
7
+ * built and proven there); `binName` is the one parameter that varies per
8
+ * caller, keeping every message and this module's own behavior otherwise
9
+ * identical to what Desktop already shipped.
10
+ */
11
+
12
+ import { findPackageJSON } from 'node:module'
13
+ import { readFileSync, statSync } from 'node:fs'
14
+ import { dirname } from 'node:path'
15
+ import { compare, valid } from 'semver'
16
+
17
+ const MAX_MANIFEST_BYTES = 1024 * 1024
18
+ const MAX_VERSION_LENGTH = 128
19
+
20
+ export type PackageOverlaySource = 'install' | 'profile'
21
+
22
+ export interface PackageOverlayCandidate {
23
+ readonly packageName: string
24
+ readonly packageDir: string
25
+ readonly manifestPath: string
26
+ readonly version?: string
27
+ readonly source: PackageOverlaySource
28
+ }
29
+
30
+ export interface PackageOverlaySelection {
31
+ readonly packageName: string
32
+ readonly selected: PackageOverlayCandidate
33
+ readonly install?: PackageOverlayCandidate
34
+ readonly profile?: PackageOverlayCandidate
35
+ }
36
+
37
+ export interface PackageOverlayOptions {
38
+ /** Diagnostic prefix on thrown errors - the calling surface's own bin name. */
39
+ readonly binName: string
40
+ /** File URL inside the exact calling surface's own installation dependency graph. */
41
+ readonly installPackageUrl: string
42
+ /** File URL for the active Profile package.json. */
43
+ readonly profilePackageUrl: string
44
+ }
45
+
46
+ export class PackageOverlayNotFoundError extends Error {
47
+ constructor(binName: string, packageName: string) {
48
+ super(`${binName}: cannot resolve package ${JSON.stringify(packageName)} from the ${binName} installation or active Profile`)
49
+ this.name = 'PackageOverlayNotFoundError'
50
+ }
51
+ }
52
+
53
+ function missingPackage(cause: unknown): boolean {
54
+ return (cause as NodeJS.ErrnoException | null)?.code === 'ERR_MODULE_NOT_FOUND'
55
+ }
56
+
57
+ function readCandidate(
58
+ binName: string,
59
+ packageName: string,
60
+ packageUrl: string,
61
+ source: PackageOverlaySource,
62
+ ): PackageOverlayCandidate | undefined {
63
+ let manifestPath: string | undefined
64
+ try {
65
+ manifestPath = findPackageJSON(packageName, packageUrl)
66
+ } catch (cause) {
67
+ if (missingPackage(cause)) return undefined
68
+ throw cause
69
+ }
70
+ if (manifestPath === undefined) return undefined
71
+ const size = statSync(manifestPath).size
72
+ if (size > MAX_MANIFEST_BYTES) {
73
+ throw new Error(`${binName}: ${source} package manifest is too large for ${packageName}`)
74
+ }
75
+ let manifest: unknown
76
+ try {
77
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as unknown
78
+ } catch (cause) {
79
+ throw new Error(
80
+ `${binName}: cannot read ${source} package manifest for ${packageName}: ${cause instanceof Error ? cause.message : String(cause)}`,
81
+ )
82
+ }
83
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)
84
+ || (manifest as { name?: unknown }).name !== packageName) {
85
+ throw new Error(`${binName}: ${source} package identity is invalid for ${packageName}`)
86
+ }
87
+ const version = (manifest as { version?: unknown }).version
88
+ const comparableVersion = typeof version === 'string' && version.length > 0
89
+ && version.length <= MAX_VERSION_LENGTH && valid(version) !== null
90
+ ? version
91
+ : undefined
92
+ return {
93
+ packageName,
94
+ packageDir: dirname(manifestPath),
95
+ manifestPath,
96
+ source,
97
+ ...(comparableVersion === undefined ? {} : { version: comparableVersion }),
98
+ }
99
+ }
100
+
101
+ /** Extract an npm package root from one Loader bare specifier. */
102
+ export function packageNameFromSpecifier(specifier: string): string | undefined {
103
+ if (specifier.length === 0 || specifier.startsWith('.') || specifier.startsWith('/')
104
+ || specifier.startsWith('#') || URL.canParse(specifier)) return undefined
105
+ const parts = specifier.split('/')
106
+ if (specifier.startsWith('@')) {
107
+ if (parts.length < 2 || parts[0]?.length === 0 || parts[1]?.length === 0) return undefined
108
+ return `${parts[0]}/${parts[1]}`
109
+ }
110
+ return parts[0]?.length === 0 ? undefined : parts[0]
111
+ }
112
+
113
+ /** Find one package root using the installation/Profile overlay rule. */
114
+ export function findOverlayPackage(
115
+ packageName: string,
116
+ options: PackageOverlayOptions,
117
+ ): PackageOverlaySelection | undefined {
118
+ if (packageNameFromSpecifier(packageName) !== packageName) {
119
+ throw new Error(`${options.binName}: package overlay requires one exact npm package name`)
120
+ }
121
+ const install = readCandidate(options.binName, packageName, options.installPackageUrl, 'install')
122
+ let profile: PackageOverlayCandidate | undefined
123
+ try {
124
+ profile = readCandidate(options.binName, packageName, options.profilePackageUrl, 'profile')
125
+ } catch (cause) {
126
+ // A valid installation package is the stable fallback when a stale
127
+ // Profile copy has unreadable identity/version metadata. Invalid
128
+ // installation metadata still fails before this branch and is never
129
+ // hidden by the Profile.
130
+ if (install === undefined) throw cause
131
+ return { packageName, selected: install, install }
132
+ }
133
+ if (install === undefined && profile === undefined) return
134
+ const selected = install === undefined
135
+ ? profile!
136
+ : profile === undefined
137
+ ? install
138
+ // Equal SemVer precedence, including build-only differences, keeps the
139
+ // installation copy as the deterministic tie-break. A missing or
140
+ // non-SemVer version on either side is not comparable and also keeps
141
+ // the installation copy.
142
+ : profile.version !== undefined && install.version !== undefined
143
+ && compare(profile.version, install.version) > 0 ? profile : install
144
+ return {
145
+ packageName,
146
+ selected,
147
+ ...(install === undefined ? {} : { install }),
148
+ ...(profile === undefined ? {} : { profile }),
149
+ }
150
+ }
151
+
152
+ /** Resolve one package root, failing when neither overlay side provides it. */
153
+ export function resolveOverlayPackage(
154
+ packageName: string,
155
+ options: PackageOverlayOptions,
156
+ ): PackageOverlaySelection {
157
+ const selection = findOverlayPackage(packageName, options)
158
+ if (selection === undefined) throw new PackageOverlayNotFoundError(options.binName, packageName)
159
+ return selection
160
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * One pnpm for every surface. `dsh plugin add` shells out to a bare `pnpm` found on PATH, so the Web and CLI surfaces used whatever pnpm
3
+ * the user's machine had (measured: 12.4.2 against a repository pinned to 11.8.0 and a profile created by pnpm 9), and a different major
4
+ * refuses an existing modules directory (ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF). Desktop already bundles the pinned pnpm behind its own PATH
5
+ * shim; this gives Web and CLI the same: the `pnpm` package this runtime depends on, exposed as a `pnpm` shim first on the PATH of the
6
+ * spawned `dsh plugin` process. When the package cannot be resolved the environment is returned unchanged, so a broken install degrades to
7
+ * the previous behavior instead of failing.
8
+ */
9
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
10
+ import { createRequire } from 'node:module'
11
+ import { delimiter, dirname, join } from 'node:path'
12
+ import { resolveAcrylHome } from './acryl-home.ts'
13
+
14
+ const require = createRequire(import.meta.url)
15
+
16
+ export interface PinnedPnpm {
17
+ /** Absolute path of the pinned pnpm entry (`bin/pnpm.mjs`). */
18
+ readonly entry: string
19
+ /** The pinned version (`package.json` of the resolved `pnpm` package). */
20
+ readonly version: string
21
+ }
22
+
23
+ /** The pnpm this runtime depends on, or undefined when it is not installed. */
24
+ export function resolvePinnedPnpm(): PinnedPnpm | undefined {
25
+ try {
26
+ // The package exports only `.` (its package.json), so resolving the bare name yields the manifest path.
27
+ const manifestPath = require.resolve('pnpm')
28
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { version?: string }
29
+ const entry = join(dirname(manifestPath), 'bin', 'pnpm.mjs')
30
+ return existsSync(entry) && typeof manifest.version === 'string' ? { entry, version: manifest.version } : undefined
31
+ } catch {
32
+ return undefined
33
+ }
34
+ }
35
+
36
+ function writeIfChanged(path: string, content: string, mode: number): void {
37
+ if (existsSync(path) && readFileSync(path, 'utf8') === content) return
38
+ writeFileSync(path, content, { mode })
39
+ chmodSync(path, mode)
40
+ }
41
+
42
+ /**
43
+ * Environment for a spawned `dsh plugin` process with the pinned pnpm first on PATH.
44
+ * @param env - the parent environment.
45
+ * @param binDir - where the shim lives (default: `<acryl home>/runtime/pnpm-bin`).
46
+ * @param platform - target platform (tests).
47
+ */
48
+ export function pinnedPnpmEnv(
49
+ env: NodeJS.ProcessEnv = process.env,
50
+ binDir: string = join(resolveAcrylHome(env), 'runtime', 'pnpm-bin'),
51
+ platform: NodeJS.Platform = process.platform,
52
+ ): NodeJS.ProcessEnv {
53
+ const pinned = resolvePinnedPnpm()
54
+ if (pinned === undefined) return env
55
+ try {
56
+ mkdirSync(binDir, { recursive: true, mode: 0o700 })
57
+ if (platform === 'win32') {
58
+ writeIfChanged(join(binDir, 'pnpm.cmd'), `@echo off\r\n"${process.execPath}" "${pinned.entry}" %*\r\n`, 0o600)
59
+ } else {
60
+ writeIfChanged(join(binDir, 'pnpm'), `#!/bin/sh\nexec "${process.execPath}" "${pinned.entry}" "$@"\n`, 0o755)
61
+ }
62
+ } catch {
63
+ return env
64
+ }
65
+ const pathKey = platform === 'win32' ? (Object.keys(env).find(key => key.toLowerCase() === 'path') ?? 'Path') : 'PATH'
66
+ return { ...env, [pathKey]: [binDir, env[pathKey]].filter(Boolean).join(delimiter) }
67
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * ACRYL's first real model-facing tool, registered as an ordinary Cordis plugin
3
+ * on the native `ctx.tools` seam.
4
+ *
5
+ * @module @acryldev/harness-runtime/acryl-workspace-status
6
+ *
7
+ * This is the ACRYL hard gate: a genuine model-facing Tool that injects `tools`,
8
+ * registers via `ctx.tools.register(defineTool(...))`, declares a canonical
9
+ * typed `output.schema` and a separate `render(...)` for model-facing content,
10
+ * honours `exec.signal`, and disposes cleanly when its owning Fiber unloads.
11
+ * It is ACRYL-owned context (the workspace/profile the agent is running in) and
12
+ * deliberately does NOT re-implement a DSH file/shell/web tool.
13
+ */
14
+
15
+ import type { Context } from '@deepseek-ai/cordis'
16
+ import { defineTool } from '@deepseek-ai/dsh-tools'
17
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
18
+ import { selectInstance } from './instance/index.ts'
19
+
20
+ /** Cordis plugin name used by loader diagnostics. */
21
+ export const name = 'acryl-workspace-status'
22
+
23
+ /** Services required: the tool registry. */
24
+ export const inject = ['tools']
25
+
26
+ /** Canonical tool name exposed to the model. */
27
+ export const TOOL_NAME = 'acryl_workspace_status'
28
+
29
+ interface AcrylWorkspaceContext {
30
+ readonly cwd: string
31
+ readonly dshHome: string
32
+ readonly profile: string
33
+ readonly surface: string
34
+ }
35
+
36
+ /** Read the ACRYL workspace/profile context the agent is running under. */
37
+ function readWorkspaceContext(): AcrylWorkspaceContext {
38
+ return {
39
+ cwd: process.cwd(),
40
+ dshHome: selectInstance().dshHome,
41
+ profile: process.env.ACRYL_PROFILE ?? '',
42
+ surface: process.env.ACRYL_SURFACE ?? '',
43
+ }
44
+ }
45
+
46
+ /** Render one line of the model-facing text from the canonical context value. */
47
+ function fmt(
48
+ label: string,
49
+ value: string,
50
+ prefix: string,
51
+ ): string {
52
+ return `${prefix} ${label}: ${value}`
53
+ }
54
+
55
+ /** Register the `acryl_workspace_status` tool on `ctx.tools`. Returns a disposer. */
56
+ export function installAcrylWorkspaceStatusTool(ctx: Context): () => void {
57
+ const tool = defineTool({
58
+ name: TOOL_NAME,
59
+ description:
60
+ 'Report the ACRYL workspace context the agent is operating in: current working '
61
+ + 'directory, DSH home, active ACRYL profile, and presentation surface. Use it to '
62
+ + 'confirm which project/profile a session is bound to before acting.',
63
+ parameters: {},
64
+ output: {
65
+ schema: {
66
+ type: 'object',
67
+ additionalProperties: false,
68
+ properties: {
69
+ cwd: { type: 'string', required: true },
70
+ dshHome: { type: 'string', required: true },
71
+ profile: { type: 'string', required: true },
72
+ surface: { type: 'string', required: true },
73
+ },
74
+ },
75
+ render(_args: unknown, value: unknown): ContentBlock[] {
76
+ const v = value as AcrylWorkspaceContext
77
+ const head = 'ACRYL workspace context:'
78
+ const lines = [
79
+ fmt('cwd', v.cwd, '-'),
80
+ fmt('dshHome', v.dshHome || '<unset>', '-'),
81
+ fmt('profile', v.profile || '<default>', '-'),
82
+ fmt('surface', v.surface || '<unknown>', '-'),
83
+ ]
84
+ return [{ type: 'text', text: [head, ...lines].join('\n') }]
85
+ },
86
+ },
87
+ async execute(_args: unknown, _exec): Promise<AcrylWorkspaceContext> {
88
+ // Same-process, zero-resource: no async work beyond a microtask so the
89
+ // tool still honours the call/cancellation pipeline and quiesces.
90
+ return readWorkspaceContext()
91
+ },
92
+ })
93
+ return ctx.tools.register(tool)
94
+ }
95
+
96
+ /** Cordis plugin entry point for idiomatic composition via a Loader row. */
97
+ export function apply(ctx: Context): void {
98
+ installAcrylWorkspaceStatusTool(ctx)
99
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Read-only health of one profile's plugin layer (spec 034, FR-001).
3
+ *
4
+ * `acryl plugin doctor` prints this and the Web panel can render the same
5
+ * report; the diagnosis itself is neither surface's code, because "why is my
6
+ * plugin missing" has the same answers everywhere: the override file does not
7
+ * parse, an override outlived the row it names, a bundle is installed but
8
+ * composes nothing, or a bundle the profile lists cannot be resolved at all.
9
+ *
10
+ * Nothing here mutates: the caller passes the live snapshot it already has and
11
+ * gets findings back.
12
+ *
13
+ * @module @acryldev/harness-runtime/plugin-doctor
14
+ */
15
+
16
+ import type { PluginLifecycleSnapshot } from '@acryldev/control'
17
+ import {
18
+ entryPatchId,
19
+ readDisabledPluginLifecycleEntries,
20
+ readUserMutableBundleNames,
21
+ type PluginLifecycleStatePersistence,
22
+ } from './plugin-lifecycle-state.ts'
23
+
24
+ export type PluginHealthSeverity = 'error' | 'warning'
25
+
26
+ export type PluginHealthCode =
27
+ | 'state-unreadable'
28
+ | 'stale-override'
29
+ | 'unmanaged-override'
30
+ | 'bundle-not-composed'
31
+ | 'bundle-missing'
32
+
33
+ export interface PluginHealthFinding {
34
+ /** `error` means the profile is broken; `warning` means it is surprising. */
35
+ readonly severity: PluginHealthSeverity
36
+ readonly code: PluginHealthCode
37
+ readonly message: string
38
+ /** The entry or package a finding is about, when it names one. */
39
+ readonly entryId?: string
40
+ }
41
+
42
+ export interface PluginHealthReport {
43
+ readonly profileName: string
44
+ readonly profileDir: string
45
+ readonly statePath: string
46
+ /** Composed Loader rows in the snapshot, mutable and protected alike. */
47
+ readonly pluginCount: number
48
+ readonly findings: readonly PluginHealthFinding[]
49
+ }
50
+
51
+ export interface PluginHealthInput extends PluginLifecycleStatePersistence {
52
+ readonly profileDir: string
53
+ readonly snapshot: PluginLifecycleSnapshot
54
+ /**
55
+ * Resolves an installed package's manifest path, or throws when it is not
56
+ * resolvable from this profile. Omitted when the caller has no resolution
57
+ * base (the bundle is then only checked for a composed row).
58
+ */
59
+ readonly resolvePackageJson?: (packageName: string) => string
60
+ }
61
+
62
+ function describe(cause: unknown): string {
63
+ return cause instanceof Error ? cause.message : String(cause)
64
+ }
65
+
66
+ /**
67
+ * Diagnose one profile against its own snapshot and override file. Returns
68
+ * findings in a stable order: state, then overrides, then bundles.
69
+ */
70
+ export function diagnosePluginLifecycle(input: PluginHealthInput): PluginHealthReport {
71
+ const findings: PluginHealthFinding[] = []
72
+ let disabled: ReadonlySet<string> = new Set()
73
+ try {
74
+ disabled = readDisabledPluginLifecycleEntries(input)
75
+ } catch (cause) {
76
+ findings.push({
77
+ severity: 'error',
78
+ code: 'state-unreadable',
79
+ message: `plugin override file ${input.statePath} could not be read: ${describe(cause)}`,
80
+ })
81
+ }
82
+
83
+ const byEntryId = new Map(input.snapshot.entries.map(entry => [entry.entryId, entry]))
84
+ const byPatchId = new Map(input.snapshot.entries.map(entry => [entryPatchId(entry.entryId), entry]))
85
+ for (const overrideId of [...disabled].sort()) {
86
+ const entry = byEntryId.get(overrideId) ?? byPatchId.get(entryPatchId(overrideId))
87
+ if (entry === undefined) {
88
+ findings.push({
89
+ severity: 'warning',
90
+ code: 'stale-override',
91
+ entryId: overrideId,
92
+ message: `${overrideId} is recorded as disabled, but this profile composes no such entry`,
93
+ })
94
+ continue
95
+ }
96
+ if (!entry.mutable) {
97
+ findings.push({
98
+ severity: 'warning',
99
+ code: 'unmanaged-override',
100
+ entryId: overrideId,
101
+ message: `${overrideId} is disabled by the override file but is not a user-controlled plugin`,
102
+ })
103
+ }
104
+ }
105
+
106
+ const bundles = readUserMutableBundleNames(input.profileDir)
107
+ const composesPackage = (packageName: string): boolean =>
108
+ input.snapshot.entries.some(entry =>
109
+ entry.moduleName === packageName || entry.moduleName.startsWith(`${packageName}/`))
110
+ for (const bundle of [...bundles].sort()) {
111
+ if (input.resolvePackageJson !== undefined) {
112
+ try {
113
+ input.resolvePackageJson(bundle)
114
+ } catch (cause) {
115
+ findings.push({
116
+ severity: 'error',
117
+ code: 'bundle-missing',
118
+ entryId: bundle,
119
+ message: `profile bundle ${bundle} is listed in dsh.profile.bundles but does not resolve from this profile: ${describe(cause)}`,
120
+ })
121
+ continue
122
+ }
123
+ }
124
+ if (!composesPackage(bundle)) {
125
+ findings.push({
126
+ severity: 'warning',
127
+ code: 'bundle-not-composed',
128
+ entryId: bundle,
129
+ message: `profile bundle ${bundle} is installed but composes no entry in this process; a restart applies a freshly installed bundle`,
130
+ })
131
+ }
132
+ }
133
+
134
+ return Object.freeze({
135
+ profileName: input.profileName,
136
+ profileDir: input.profileDir,
137
+ statePath: input.statePath,
138
+ pluginCount: input.snapshot.entries.length,
139
+ findings: Object.freeze(findings),
140
+ })
141
+ }