@acryldev/harness-runtime 0.0.0-stage → 0.2.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +49 -0
- package/lib/index.mjs +5693 -0
- package/lib/index.mjs.map +1 -0
- package/lib/types/acryl-home.d.ts +81 -0
- package/lib/types/app/new-app.d.ts +65 -0
- package/lib/types/app/start-source.d.ts +47 -0
- package/lib/types/blueprint/blueprint.d.ts +74 -0
- package/lib/types/blueprint/brand-identity.d.ts +26 -0
- package/lib/types/blueprint/compose.d.ts +53 -0
- package/lib/types/blueprint/definition.d.ts +22 -0
- package/lib/types/blueprint/index.d.ts +7 -0
- package/lib/types/blueprint/manifest.d.ts +35 -0
- package/lib/types/blueprint/selection.d.ts +19 -0
- package/lib/types/cli-market-install.d.ts +97 -0
- package/lib/types/cli-market-plugins.d.ts +81 -0
- package/lib/types/coding-capabilities.d.ts +29 -0
- package/lib/types/durable-message.d.ts +18 -0
- package/lib/types/engine-dsh.d.ts +181 -0
- package/lib/types/engine-files.d.ts +8 -0
- package/lib/types/engine-host.d.ts +32 -0
- package/lib/types/engine-tools.d.ts +11 -0
- package/lib/types/index.d.ts +67 -0
- package/lib/types/instance/announce-self.d.ts +38 -0
- package/lib/types/instance/app-instance.d.ts +125 -0
- package/lib/types/instance/index.d.ts +6 -0
- package/lib/types/instance/offline-lock.d.ts +29 -0
- package/lib/types/instance/online-secret.d.ts +29 -0
- package/lib/types/instance/registry.d.ts +26 -0
- package/lib/types/instance/select.d.ts +43 -0
- package/lib/types/module-hooks.d.ts +19 -0
- package/lib/types/module-resolution.d.ts +31 -0
- package/lib/types/package-overlay.d.ts +41 -0
- package/lib/types/pinned-pnpm.d.ts +15 -0
- package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
- package/lib/types/plugin-doctor.d.ts +49 -0
- package/lib/types/plugin-lifecycle-state.d.ts +92 -0
- package/lib/types/plugin-lifecycle.d.ts +87 -0
- package/lib/types/profile-layout.d.ts +17 -0
- package/lib/types/profile-owner.d.ts +25 -0
- package/lib/types/profile-repair/backup.d.ts +37 -0
- package/lib/types/profile-repair/findings.d.ts +29 -0
- package/lib/types/profile-repair/index.d.ts +9 -0
- package/lib/types/profile-repair/inspector.d.ts +11 -0
- package/lib/types/profile-repair/repair.d.ts +38 -0
- package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
- package/lib/types/profile-resolution/resolver.d.ts +41 -0
- package/lib/types/profile-resolution/service.d.ts +22 -0
- package/lib/types/prompt-budget.d.ts +44 -0
- package/lib/types/session-bridge.d.ts +57 -0
- package/lib/types/session-log-exporter.d.ts +31 -0
- package/lib/types/system-prompt-capture.d.ts +29 -0
- package/lib/types/web-favicon-data.d.ts +5 -0
- package/lib/types/web-favicon.d.ts +23 -0
- package/lib/types/web-market-install.d.ts +114 -0
- package/lib/types/web-market-plugins.d.ts +106 -0
- package/lib/types/web-port.d.ts +15 -0
- package/package.json +211 -3
- package/src/acryl-home.ts +103 -0
- package/src/app/new-app.ts +239 -0
- package/src/app/start-source.ts +110 -0
- package/src/blueprint/blueprint.ts +141 -0
- package/src/blueprint/brand-identity.ts +75 -0
- package/src/blueprint/compose.ts +222 -0
- package/src/blueprint/definition.ts +92 -0
- package/src/blueprint/index.ts +20 -0
- package/src/blueprint/manifest.ts +145 -0
- package/src/blueprint/selection.ts +74 -0
- package/src/cli-market-install.ts +181 -0
- package/src/cli-market-plugins.ts +176 -0
- package/src/coding-capabilities.ts +61 -0
- package/src/durable-message.ts +23 -0
- package/src/engine-dsh.ts +856 -0
- package/src/engine-files.ts +9 -0
- package/src/engine-host.ts +128 -0
- package/src/engine-tools.ts +26 -0
- package/src/index.ts +436 -0
- package/src/instance/announce-self.ts +88 -0
- package/src/instance/app-instance.ts +240 -0
- package/src/instance/index.ts +45 -0
- package/src/instance/offline-lock.ts +71 -0
- package/src/instance/online-secret.ts +55 -0
- package/src/instance/registry.ts +53 -0
- package/src/instance/select.ts +134 -0
- package/src/module-hooks.ts +41 -0
- package/src/module-resolution.ts +187 -0
- package/src/package-overlay.ts +160 -0
- package/src/pinned-pnpm.ts +67 -0
- package/src/plugin-acryl-workspace-status.ts +99 -0
- package/src/plugin-doctor.ts +141 -0
- package/src/plugin-lifecycle-state.ts +347 -0
- package/src/plugin-lifecycle.ts +223 -0
- package/src/profile-layout.ts +97 -0
- package/src/profile-owner.ts +52 -0
- package/src/profile-repair/backup.ts +119 -0
- package/src/profile-repair/findings.ts +43 -0
- package/src/profile-repair/index.ts +10 -0
- package/src/profile-repair/inspector.ts +156 -0
- package/src/profile-repair/repair.ts +137 -0
- package/src/profile-resolution/moved-framework.ts +64 -0
- package/src/profile-resolution/resolver.ts +876 -0
- package/src/profile-resolution/service.ts +99 -0
- package/src/prompt-budget.ts +118 -0
- package/src/session-bridge.ts +350 -0
- package/src/session-log-exporter.ts +68 -0
- package/src/system-prompt-capture.ts +99 -0
- package/src/web-favicon-data.ts +6 -0
- package/src/web-favicon.ts +43 -0
- package/src/web-market-install.ts +206 -0
- package/src/web-market-plugins.ts +215 -0
- package/src/web-port.ts +39 -0
- package/tests/account-callback.spec.ts +173 -0
- package/tests/acryl-home.spec.ts +39 -0
- package/tests/agent-self-hosting.spec.ts +101 -0
- package/tests/announce-self.spec.ts +84 -0
- package/tests/app-lifecycle.spec.ts +99 -0
- package/tests/blank-blueprint.spec.ts +110 -0
- package/tests/blueprint-definition.spec.ts +128 -0
- package/tests/blueprint.spec.ts +138 -0
- package/tests/bulkhead.spec.ts +187 -0
- package/tests/coding-vocabulary.spec.ts +15 -0
- package/tests/dump-system-prompt.spec.ts +65 -0
- package/tests/e2e-real-model.spec.ts +71 -0
- package/tests/e2e-restart-real-model.spec.ts +77 -0
- package/tests/engine-dsh.spec.ts +340 -0
- package/tests/engine-host-mount-root-include.spec.ts +118 -0
- package/tests/engine-host.spec.ts +176 -0
- package/tests/engine-optional.spec.ts +81 -0
- package/tests/extension-examples.spec.ts +261 -0
- package/tests/hooks-thread-stack.ts +27 -0
- package/tests/instance-patches.spec.ts +25 -0
- package/tests/instance.spec.ts +235 -0
- package/tests/live/community-plugins.spec.ts +83 -0
- package/tests/module-hooks.spec.ts +35 -0
- package/tests/module-resolution.spec.ts +265 -0
- package/tests/moved-framework.spec.ts +61 -0
- package/tests/new-app.spec.ts +132 -0
- package/tests/organizer-growth.spec.ts +117 -0
- package/tests/pinned-pnpm.spec.ts +34 -0
- package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
- package/tests/plugin-context.spec.ts +640 -0
- package/tests/plugin-doctor.spec.ts +183 -0
- package/tests/plugin-enablement-one-store.spec.ts +130 -0
- package/tests/plugin-lifecycle-state.spec.ts +169 -0
- package/tests/profile-layout.spec.ts +58 -0
- package/tests/profile-owner.spec.ts +38 -0
- package/tests/profile-repair/profile-repair.spec.ts +231 -0
- package/tests/profile-resolution-port.spec.ts +30 -0
- package/tests/profile-resolution-service.spec.ts +273 -0
- package/tests/profile-resolution-swap.spec.ts +69 -0
- package/tests/profile-resolution.spec.ts +2535 -0
- package/tests/profile.spec.ts +70 -0
- package/tests/project-registry.spec.ts +81 -0
- package/tests/prompt-budget.spec.ts +58 -0
- package/tests/real-home-guard.spec.ts +178 -0
- package/tests/session-bridge.spec.ts +316 -0
- package/tests/start-source.spec.ts +65 -0
- package/tests/system-prompt-shape.spec.ts +95 -0
- package/tests/three-levels.spec.ts +84 -0
- package/tests/tool-gateway.spec.ts +116 -0
- package/tests/tool-schemas.spec.ts +41 -0
- package/tests/web-favicon.spec.ts +42 -0
- package/tests/web-port.spec.ts +38 -0
- package/tests/web-startup-hold.spec.ts +79 -0
- package/tsconfig.json +24 -0
- package/tsdown.config.ts +2 -0
- package/vitest.config.ts +18 -0
- package/README.md +0 -3
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AppInstance: everything one running ACRYL app owns on this machine, as one consistent family (spec 036, "Self-containment").
|
|
3
|
+
*
|
|
4
|
+
* Patterns, by the books in the repo's engineering rules:
|
|
5
|
+
* - **Bulkhead** (Release It!): each app is a sealed compartment; nothing it owns is reachable from another app.
|
|
6
|
+
* - **Abstract Factory** (refactoring.guru): the factories below produce a whole family of resources (home, engine home, port, Electron user data, run lock,
|
|
7
|
+
* project scope) that always belong together; a caller cannot mix one app's home with another app's port.
|
|
8
|
+
* - **Deep module / information hiding** (A Philosophy of Software Design): "where an app keeps things" is decided here and nowhere else.
|
|
9
|
+
* - The instance is chosen once, in the composition root (Clean Architecture's Main), by `select.ts`, the only code that reads the environment or the OS home.
|
|
10
|
+
*
|
|
11
|
+
* Pure: no I/O. Paths are built, never checked; `select.ts` does the few filesystem checks that choose a factory.
|
|
12
|
+
*
|
|
13
|
+
* @module @acryldev/harness-runtime/instance/app-instance
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createHash } from 'node:crypto'
|
|
17
|
+
import { basename, join } from 'node:path'
|
|
18
|
+
|
|
19
|
+
/** How the instance was chosen. Only `default` may use the shared `~/.acryl`. */
|
|
20
|
+
export type AppInstanceKind = 'default' | 'development' | 'worktree' | 'app' | 'managed' | 'pinned'
|
|
21
|
+
|
|
22
|
+
export interface AppInstance {
|
|
23
|
+
readonly kind: AppInstanceKind
|
|
24
|
+
/** Unique on this machine: it seeds the port, names the Electron user data and namespaces project folders. */
|
|
25
|
+
readonly id: string
|
|
26
|
+
/** Human name (the folder name for an app). */
|
|
27
|
+
readonly name: string
|
|
28
|
+
/** The ACRYL home: settings, sessions, profiles (under `dshHome`), global extensions, runtime state. */
|
|
29
|
+
readonly home: string
|
|
30
|
+
/** The DSH engine home the pinned harness reads (`DSH_HOME`). */
|
|
31
|
+
readonly dshHome: string
|
|
32
|
+
/** First Web port to try, and whether to move to the next free one when it is taken. */
|
|
33
|
+
readonly webPort: { readonly start: number, readonly scan: boolean }
|
|
34
|
+
/**
|
|
35
|
+
* Who may reach the Web server: the address it listens on (loopback unless a caller such as a container entry point asks for `0.0.0.0`) and the extra
|
|
36
|
+
* names a browser reaches it by (a proxy's public host). Non-loopback names must be listed, or DSH's connection refuses the request.
|
|
37
|
+
*/
|
|
38
|
+
readonly webAccess: WebAccess
|
|
39
|
+
/** Electron's product name for this instance, and the name of its user-data folder before it moved into the home (read once, to carry that data over). */
|
|
40
|
+
readonly userDataName: string
|
|
41
|
+
/**
|
|
42
|
+
* Electron's user data (window state, storage, logs, crash evidence, the single-instance lock), inside the app's own home like everything else it keeps,
|
|
43
|
+
* never in an OS application-data folder: one predictable place on every OS (`~/.acryl/desktop-data` for the installed app).
|
|
44
|
+
*/
|
|
45
|
+
readonly userDataDir: string
|
|
46
|
+
/** Namespace for folders this app writes inside a project it opens; undefined keeps the classic shared locations. */
|
|
47
|
+
readonly projectScope?: string
|
|
48
|
+
/**
|
|
49
|
+
* Where the chat creates its first workspace, when this app must not use the OS user's Documents folder. DSH asks the operating system for that folder
|
|
50
|
+
* (not `$HOME`), so an isolated app would otherwise write its first project into the real one. Only the default instance, which is the user's installed
|
|
51
|
+
* app, uses the OS Documents folder; every other instance keeps it inside its own home.
|
|
52
|
+
*/
|
|
53
|
+
readonly documentsDirectory?: string
|
|
54
|
+
/** The app definition (`blend.yaml`) when this is an app folder. */
|
|
55
|
+
readonly definitionFile?: string
|
|
56
|
+
/** The pessimistic offline lock that makes one live process per instance. */
|
|
57
|
+
readonly runLockFile: string
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** See {@link AppInstance.webAccess}. */
|
|
61
|
+
export interface WebAccess {
|
|
62
|
+
readonly host: string
|
|
63
|
+
readonly trustedHosts: readonly string[]
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const LOOPBACK_WEB_HOST = '127.0.0.1'
|
|
67
|
+
/** Bind addresses a caller may choose: loopback, or every interface (a container, where the network boundary is the container's own). */
|
|
68
|
+
export const WEB_HOSTS: readonly string[] = Object.freeze([LOOPBACK_WEB_HOST, '0.0.0.0', '::1', '::'])
|
|
69
|
+
export const DEFAULT_WEB_PORT = 3080
|
|
70
|
+
export const WORKTREE_WEB_PORT = 3081
|
|
71
|
+
export const APP_PORT_BASE = 3100
|
|
72
|
+
export const APP_PORT_SPAN = 900
|
|
73
|
+
export const APP_DEFINITION_FILE = 'blend.yaml'
|
|
74
|
+
export const RUN_LOCK_FILE = 'instance.json'
|
|
75
|
+
export const USER_DATA_DIR_NAME = 'desktop-data'
|
|
76
|
+
export const ENGINE_DIR_NAME = '.dsh'
|
|
77
|
+
export const DEFAULT_HOME_DIR_NAME = '.acryl'
|
|
78
|
+
export const DEVELOPMENT_HOME_DIR_NAME = '.acryl-dev'
|
|
79
|
+
export const WORKTREE_HOMES_DIR_NAME = '.acryl-worktrees'
|
|
80
|
+
export const MANAGED_HOMES_DIR_NAME = '.acryl-instances'
|
|
81
|
+
|
|
82
|
+
const NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u
|
|
83
|
+
/** A project-scope id (the extension pack validates the same shape before building a path from it). */
|
|
84
|
+
export const PROJECT_SCOPE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u
|
|
85
|
+
export const PROJECT_SCOPE_MAX = 64
|
|
86
|
+
const TRUSTED_HOST = /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?$/u
|
|
87
|
+
const LOOPBACK_ACCESS: WebAccess = Object.freeze({ host: LOOPBACK_WEB_HOST, trustedHosts: Object.freeze([]) })
|
|
88
|
+
|
|
89
|
+
export class AppInstanceError extends Error {
|
|
90
|
+
constructor(message: string) {
|
|
91
|
+
super(message)
|
|
92
|
+
this.name = 'AppInstanceError'
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A plain app name: lowercase letters, digits and dashes, at most 32. It becomes a folder, an app name and a port seed. */
|
|
97
|
+
export function appName(value: unknown): string {
|
|
98
|
+
if (typeof value !== 'string' || !NAME.test(value) || value.length > 32) throw new AppInstanceError(`an app name is lowercase letters, digits and dashes (at most 32), got ${JSON.stringify(value)}`)
|
|
99
|
+
return value
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** FNV-1a over the id: stable across runs and platforms, spreads ids over the app port range. */
|
|
103
|
+
export function stablePort(id: string): number {
|
|
104
|
+
let hash = 0x811c9dc5
|
|
105
|
+
for (const character of id) {
|
|
106
|
+
hash ^= character.codePointAt(0) ?? 0
|
|
107
|
+
hash = Math.imul(hash, 0x01000193) >>> 0
|
|
108
|
+
}
|
|
109
|
+
return APP_PORT_BASE + (hash % APP_PORT_SPAN)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function family(input: {
|
|
113
|
+
kind: AppInstanceKind
|
|
114
|
+
id: string
|
|
115
|
+
name: string
|
|
116
|
+
home: string
|
|
117
|
+
dshHome?: string
|
|
118
|
+
webPort: AppInstance['webPort']
|
|
119
|
+
userDataName: string
|
|
120
|
+
projectScope?: string
|
|
121
|
+
definitionFile?: string
|
|
122
|
+
}): AppInstance {
|
|
123
|
+
return Object.freeze({
|
|
124
|
+
kind: input.kind,
|
|
125
|
+
id: input.id,
|
|
126
|
+
name: input.name,
|
|
127
|
+
home: input.home,
|
|
128
|
+
dshHome: input.dshHome ?? join(input.home, ENGINE_DIR_NAME),
|
|
129
|
+
webPort: Object.freeze({ ...input.webPort }),
|
|
130
|
+
webAccess: LOOPBACK_ACCESS,
|
|
131
|
+
userDataName: input.userDataName,
|
|
132
|
+
userDataDir: join(input.home, USER_DATA_DIR_NAME),
|
|
133
|
+
...(input.projectScope === undefined ? {} : { projectScope: input.projectScope }),
|
|
134
|
+
...(input.kind === 'default' ? {} : { documentsDirectory: join(input.home, 'documents') }),
|
|
135
|
+
...(input.definitionFile === undefined ? {} : { definitionFile: input.definitionFile }),
|
|
136
|
+
runLockFile: join(input.home, RUN_LOCK_FILE),
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Plain ACRYL, nothing configured: the one instance allowed to use the shared `~/.acryl`. */
|
|
141
|
+
export function defaultInstance(osHome: string): AppInstance {
|
|
142
|
+
return family({ kind: 'default', id: 'acryl', name: 'acryl', home: join(osHome, DEFAULT_HOME_DIR_NAME), webPort: { start: DEFAULT_WEB_PORT, scan: false }, userDataName: 'ACRYL' })
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The isolated local development app of the main checkout (`pnpm run dev`). */
|
|
146
|
+
export function developmentInstance(osHome: string): AppInstance {
|
|
147
|
+
return family({ kind: 'development', id: 'acryl-dev', name: 'acryl-dev', home: join(osHome, DEVELOPMENT_HOME_DIR_NAME), webPort: { start: DEFAULT_WEB_PORT, scan: true }, userDataName: 'ACRYL Development' })
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** A second checkout (a git worktree): never the main checkout's home, port or Electron app. */
|
|
151
|
+
export function worktreeInstance(osHome: string, checkoutRoot: string): AppInstance {
|
|
152
|
+
const folder = basename(checkoutRoot).replace(/[^A-Za-z0-9._-]+/gu, '-')
|
|
153
|
+
const scope = `worktree-${folder.toLowerCase().replace(/[^a-z0-9]+/gu, '-').replace(/^-+|-+$/gu, '')}`.slice(0, PROJECT_SCOPE_MAX).replace(/-+$/u, '')
|
|
154
|
+
return family({ kind: 'worktree', id: scope, name: folder, home: join(osHome, WORKTREE_HOMES_DIR_NAME, folder), webPort: { start: WORKTREE_WEB_PORT, scan: true }, userDataName: `ACRYL Development ${folder}`, projectScope: scope })
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* An app folder (`acryl new`): the folder is the home. Two folders may share a name, so a folder's id carries a short digest of its real path; a managed app
|
|
159
|
+
* (kept under `~/.acryl-instances/<name>`) is unique by name.
|
|
160
|
+
*/
|
|
161
|
+
export function appFolderInstance(realFolder: string, managed: boolean): AppInstance {
|
|
162
|
+
const name = appName(basename(realFolder))
|
|
163
|
+
const id = managed ? name : `${name}-${createHash('sha1').update(realFolder).digest('hex').slice(0, 4)}`
|
|
164
|
+
return family({ kind: managed ? 'managed' : 'app', id, name, home: realFolder, webPort: { start: stablePort(id), scan: true }, userDataName: `ACRYL ${id}`, projectScope: id, definitionFile: join(realFolder, APP_DEFINITION_FILE) })
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** A home a caller pinned explicitly (ACRYL_HOME without an app definition, or a legacy DSH_HOME): honoured as given. */
|
|
168
|
+
export function pinnedInstance(home: string, dshHome?: string): AppInstance {
|
|
169
|
+
const name = basename(home).replace(/^\.+/u, '') || 'acryl'
|
|
170
|
+
return family({ kind: 'pinned', id: `pinned-${createHash('sha1').update(home).digest('hex').slice(0, 6)}`, name, home, ...(dshHome === undefined ? {} : { dshHome }), webPort: { start: DEFAULT_WEB_PORT, scan: false }, userDataName: 'ACRYL' })
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The same family with an explicit port preference (ACRYL_WEB_PORT). Explicit always scans: the caller asked for a start, not a fight. */
|
|
174
|
+
export function withWebPort(instance: AppInstance, start: number): AppInstance {
|
|
175
|
+
if (!Number.isInteger(start) || start < 1024 || start > 65_535) throw new AppInstanceError(`the web port must be a port number from 1024 to 65535, got ${String(start)}`)
|
|
176
|
+
return Object.freeze({ ...instance, webPort: Object.freeze({ start, scan: true }) })
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The same family reachable beyond loopback (ACRYL_WEB_HOST, ACRYL_WEB_TRUSTED_HOSTS). The trusted names are checked again, strictly, by DSH's connection
|
|
181
|
+
* plugin at load; this only refuses what is plainly not a host name so the mistake surfaces at selection, with the variable's name.
|
|
182
|
+
*/
|
|
183
|
+
export function withWebAccess(instance: AppInstance, host: string, trustedHosts: readonly string[]): AppInstance {
|
|
184
|
+
if (!WEB_HOSTS.includes(host)) throw new AppInstanceError(`the web host must be one of ${WEB_HOSTS.join(', ')}, got ${JSON.stringify(host)}`)
|
|
185
|
+
for (const name of trustedHosts) {
|
|
186
|
+
if (!TRUSTED_HOST.test(name)) throw new AppInstanceError(`a trusted web host is a host name with an optional port (such as ws-1.example.com or ws-1.example.com:443), got ${JSON.stringify(name)}`)
|
|
187
|
+
}
|
|
188
|
+
return Object.freeze({ ...instance, webAccess: Object.freeze({ host, trustedHosts: Object.freeze([...trustedHosts]) }) })
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** A project-scope override (ACRYL_INSTANCE) for a pinned home. */
|
|
192
|
+
export function withProjectScope(instance: AppInstance, scope: string): AppInstance {
|
|
193
|
+
if (!PROJECT_SCOPE.test(scope) || scope.length > PROJECT_SCOPE_MAX) throw new AppInstanceError(`a project scope is lowercase letters, digits and dashes (at most ${String(PROJECT_SCOPE_MAX)}), got ${JSON.stringify(scope)}`)
|
|
194
|
+
return Object.freeze({ ...instance, projectScope: scope })
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* The environment contract that hands an instance to a child process or to the pinned harness. It is the ONLY way an instance crosses a process
|
|
199
|
+
* boundary: the child's `select.ts` reads these exact values back into the same family.
|
|
200
|
+
*/
|
|
201
|
+
export function instanceEnvironment(instance: AppInstance): Record<string, string> {
|
|
202
|
+
// The default instance is what a child derives with nothing set, so it adds nothing (and never pins the shared home by accident).
|
|
203
|
+
if (instance.kind === 'default') return {}
|
|
204
|
+
// A home pinned only through a legacy DSH_HOME round-trips as DSH_HOME alone: an ACRYL_HOME would outrank it and nest a different engine home.
|
|
205
|
+
const engineOnly = instance.kind === 'pinned' && instance.dshHome !== join(instance.home, ENGINE_DIR_NAME)
|
|
206
|
+
return {
|
|
207
|
+
...(engineOnly ? {} : { ACRYL_HOME: instance.home }),
|
|
208
|
+
DSH_HOME: instance.dshHome,
|
|
209
|
+
...(instance.webPort.scan ? { ACRYL_WEB_PORT: String(instance.webPort.start) } : {}),
|
|
210
|
+
...(instance.webAccess.host === LOOPBACK_WEB_HOST ? {} : { ACRYL_WEB_HOST: instance.webAccess.host }),
|
|
211
|
+
...(instance.webAccess.trustedHosts.length === 0 ? {} : { ACRYL_WEB_TRUSTED_HOSTS: instance.webAccess.trustedHosts.join(',') }),
|
|
212
|
+
ACRYL_LOCAL_PRODUCT_NAME: instance.userDataName,
|
|
213
|
+
...(instance.projectScope === undefined ? {} : { ACRYL_INSTANCE: instance.projectScope }),
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export function profileDir(instance: AppInstance, profileName: string): string {
|
|
218
|
+
return join(instance.dshHome, 'profiles', profileName)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The run lock file that owns a given engine home, for a caller that was handed a `dshHome` directly (the CLI
|
|
223
|
+
* rescue tools, `--home`) rather than a full `AppInstance`. Inverts `family()`'s default nesting
|
|
224
|
+
* (`dshHome = join(home, ENGINE_DIR_NAME)`): when `dshHome`'s last segment is `.dsh`, its app home is the parent;
|
|
225
|
+
* otherwise `dshHome` was handed in as the home itself (a pinned instance may point `dshHome` anywhere), so it is
|
|
226
|
+
* its own app home. Pure path math, no I/O: it does not choose an instance, only locates the lock file for one
|
|
227
|
+
* a caller already resolved, so it does not compete with `select.ts` for "the one place an app is chosen".
|
|
228
|
+
*/
|
|
229
|
+
export function runLockFileForDshHome(dshHome: string): string {
|
|
230
|
+
const home = basename(dshHome) === ENGINE_DIR_NAME ? join(dshHome, '..') : dshHome
|
|
231
|
+
return join(home, RUN_LOCK_FILE)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const USER_DATA_NAME = /^[A-Za-z0-9.][A-Za-z0-9._ -]{0,63}$/u
|
|
235
|
+
|
|
236
|
+
/** The Electron user-data name (ACRYL_LOCAL_PRODUCT_NAME): a plain folder name, never a path, so it cannot escape the user-data root. */
|
|
237
|
+
export function withUserDataName(instance: AppInstance, name: string): AppInstance {
|
|
238
|
+
if (!USER_DATA_NAME.test(name) || name.includes('..')) throw new AppInstanceError(`the Electron user-data name must be a plain folder name, got ${JSON.stringify(name)}`)
|
|
239
|
+
return Object.freeze({ ...instance, userDataName: name })
|
|
240
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export {
|
|
2
|
+
announceSelf,
|
|
3
|
+
InstanceAnnounceError,
|
|
4
|
+
type SelfAnnouncement,
|
|
5
|
+
type SelfAnnouncementInfo,
|
|
6
|
+
} from './announce-self.ts'
|
|
7
|
+
export {
|
|
8
|
+
APP_DEFINITION_FILE,
|
|
9
|
+
AppInstanceError,
|
|
10
|
+
DEFAULT_WEB_PORT,
|
|
11
|
+
LOOPBACK_WEB_HOST,
|
|
12
|
+
MANAGED_HOMES_DIR_NAME,
|
|
13
|
+
PROJECT_SCOPE,
|
|
14
|
+
PROJECT_SCOPE_MAX,
|
|
15
|
+
RUN_LOCK_FILE,
|
|
16
|
+
WEB_HOSTS,
|
|
17
|
+
WORKTREE_WEB_PORT,
|
|
18
|
+
appFolderInstance,
|
|
19
|
+
appName,
|
|
20
|
+
defaultInstance,
|
|
21
|
+
developmentInstance,
|
|
22
|
+
instanceEnvironment,
|
|
23
|
+
pinnedInstance,
|
|
24
|
+
profileDir,
|
|
25
|
+
runLockFileForDshHome,
|
|
26
|
+
stablePort,
|
|
27
|
+
withProjectScope,
|
|
28
|
+
withUserDataName,
|
|
29
|
+
withWebAccess,
|
|
30
|
+
withWebPort,
|
|
31
|
+
worktreeInstance,
|
|
32
|
+
type AppInstance,
|
|
33
|
+
type AppInstanceKind,
|
|
34
|
+
type WebAccess,
|
|
35
|
+
} from './app-instance.ts'
|
|
36
|
+
export { LockHeldError, acquireLock, processIsAlive, readLock, releaseLock, type LockHolder } from './offline-lock.ts'
|
|
37
|
+
export {
|
|
38
|
+
ONLINE_SECRET_FILE_NAME,
|
|
39
|
+
onlineSecretPath,
|
|
40
|
+
readOnlineSecret,
|
|
41
|
+
removeOnlineSecret,
|
|
42
|
+
writeOnlineSecret,
|
|
43
|
+
} from './online-secret.ts'
|
|
44
|
+
export { announce, listRunning, registryDir, withdraw, type RunningApp } from './registry.ts'
|
|
45
|
+
export { IsolationRequiredError, REQUIRE_ISOLATED_HOME_ENV, appFolder, isGitWorktree, managedApp, osHomeDirectory, selectInstance, type SelectInstanceOptions } from './select.ts'
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pessimistic Offline Lock (Patterns of Enterprise Application Architecture), with the book's conditions met: ownership is visible (the file says who
|
|
3
|
+
* holds it), and a stale lock (its holder's process is gone) is taken over instead of blocking forever. Used for "one live process per app" and "one live
|
|
4
|
+
* installation per profile".
|
|
5
|
+
*
|
|
6
|
+
* @module @acryldev/harness-runtime/instance/offline-lock
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
10
|
+
import { dirname } from 'node:path'
|
|
11
|
+
|
|
12
|
+
export interface LockHolder {
|
|
13
|
+
readonly pid: number
|
|
14
|
+
readonly since: string
|
|
15
|
+
readonly [detail: string]: unknown
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class LockHeldError extends Error {
|
|
19
|
+
readonly holder: LockHolder
|
|
20
|
+
constructor(message: string, holder: LockHolder) {
|
|
21
|
+
super(message)
|
|
22
|
+
this.name = 'LockHeldError'
|
|
23
|
+
this.holder = holder
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function processIsAlive(pid: number): boolean {
|
|
28
|
+
try {
|
|
29
|
+
process.kill(pid, 0)
|
|
30
|
+
return true
|
|
31
|
+
} catch (error) {
|
|
32
|
+
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function readLock(file: string): LockHolder | undefined {
|
|
37
|
+
if (!existsSync(file)) return undefined
|
|
38
|
+
try {
|
|
39
|
+
const value = JSON.parse(readFileSync(file, 'utf8')) as Partial<LockHolder>
|
|
40
|
+
return Number.isInteger(value.pid) ? value as LockHolder : undefined
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Take the lock for `pid`. Refused (LockHeldError, with a message built by `describe`) when a live holder exists that `compatible` does not accept.
|
|
48
|
+
* `compatible` lets a lock admit its own kind (the same installation, the same process).
|
|
49
|
+
*/
|
|
50
|
+
export function acquireLock(
|
|
51
|
+
file: string,
|
|
52
|
+
holder: Omit<LockHolder, 'since'>,
|
|
53
|
+
options: {
|
|
54
|
+
readonly alive?: (pid: number) => boolean
|
|
55
|
+
readonly compatible?: (current: LockHolder) => boolean
|
|
56
|
+
readonly describe?: (current: LockHolder) => string
|
|
57
|
+
} = {},
|
|
58
|
+
): void {
|
|
59
|
+
const alive = options.alive ?? processIsAlive
|
|
60
|
+
const current = readLock(file)
|
|
61
|
+
if (current !== undefined && current.pid !== holder.pid && alive(current.pid) && options.compatible?.(current) !== true) {
|
|
62
|
+
throw new LockHeldError(options.describe?.(current) ?? `${file} is held by pid ${String(current.pid)}`, current)
|
|
63
|
+
}
|
|
64
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
|
|
65
|
+
writeFileSync(file, `${JSON.stringify({ ...holder, since: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 })
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Release only our own hold: never remove a lock a newer holder took after ours went stale. */
|
|
69
|
+
export function releaseLock(file: string, pid: number = process.pid): void {
|
|
70
|
+
if (readLock(file)?.pid === pid) rmSync(file, { force: true })
|
|
71
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The online channel's per-instance secret (spec 041 TB30, following TB03's threat model): a random token
|
|
3
|
+
* written next to the instance's own run lock, readable only by the OS user that started the app (`0o600`,
|
|
4
|
+
* the same directory mode the Registry and the offline lock already use). An external CLI operator on the
|
|
5
|
+
* same machine, as the same OS user, can simply read it - no handshake, matching how Docker's own CLI trusts
|
|
6
|
+
* a local socket it can open, and how Jupyter's own token file works. A different OS user is refused by
|
|
7
|
+
* filesystem permissions alone; this adds no stronger boundary than that on purpose (TB03).
|
|
8
|
+
*
|
|
9
|
+
* Lives beside `offline-lock.ts` and `registry.ts` (not in `@acryldev/agent-control`) so both the Host plugin that
|
|
10
|
+
* writes it and the CLI that reads it depend on the same shared package, neither on the other.
|
|
11
|
+
*
|
|
12
|
+
* @module @acryldev/harness-runtime/instance/online-secret
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { randomBytes } from 'node:crypto'
|
|
16
|
+
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
17
|
+
import { dirname, join } from 'node:path'
|
|
18
|
+
|
|
19
|
+
/** Plain file name, next to the run lock in the instance's own home. */
|
|
20
|
+
export const ONLINE_SECRET_FILE_NAME = 'agent-control-secret'
|
|
21
|
+
|
|
22
|
+
export function onlineSecretPath(appHome: string): string {
|
|
23
|
+
return join(appHome, ONLINE_SECRET_FILE_NAME)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Write a fresh secret for this run. Tied to the process, not persisted across restarts (a crashed app's
|
|
28
|
+
* secret is orphaned the same way its run lock is; a fresh start writes a fresh one - TB03's rotation note).
|
|
29
|
+
* @returns the secret, hex-encoded.
|
|
30
|
+
*/
|
|
31
|
+
export function writeOnlineSecret(appHome: string): string {
|
|
32
|
+
const path = onlineSecretPath(appHome)
|
|
33
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
34
|
+
const secret = randomBytes(24).toString('hex')
|
|
35
|
+
writeFileSync(path, secret, { mode: 0o600 })
|
|
36
|
+
chmodSync(path, 0o600)
|
|
37
|
+
return secret
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Remove this run's secret; a caller can no longer authenticate to an instance that has shut down. */
|
|
41
|
+
export function removeOnlineSecret(appHome: string): void {
|
|
42
|
+
rmSync(onlineSecretPath(appHome), { force: true })
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Read a running instance's secret (the CLI's own side, TB31): same OS user, so a plain read, no handshake.
|
|
47
|
+
* @returns the secret, or undefined when the instance has no online channel (older version, or not yet started).
|
|
48
|
+
*/
|
|
49
|
+
export function readOnlineSecret(appHome: string): string | undefined {
|
|
50
|
+
try {
|
|
51
|
+
return readFileSync(onlineSecretPath(appHome), 'utf8').trim()
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registry (Patterns of Enterprise Application Architecture) of running apps: each running app announces itself with one small file, so `ps` finds apps
|
|
3
|
+
* wherever their folders are. An announcement whose process is gone is dropped when read. The registry lives in the OS user's `~/.acryl-instances/.running`
|
|
4
|
+
* and holds only pointers (id, folder, pid, surface, port), never app data.
|
|
5
|
+
*
|
|
6
|
+
* @module @acryldev/harness-runtime/instance/registry
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { MANAGED_HOMES_DIR_NAME, type AppInstance } from './app-instance.ts'
|
|
12
|
+
import { processIsAlive, readLock } from './offline-lock.ts'
|
|
13
|
+
|
|
14
|
+
export interface RunningApp {
|
|
15
|
+
readonly id: string
|
|
16
|
+
readonly name: string
|
|
17
|
+
readonly home: string
|
|
18
|
+
readonly pid: number
|
|
19
|
+
readonly surface?: string
|
|
20
|
+
readonly definition?: string
|
|
21
|
+
readonly port?: number
|
|
22
|
+
readonly since?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function registryDir(osHome: string): string {
|
|
26
|
+
return join(osHome, MANAGED_HOMES_DIR_NAME, '.running')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function announce(osHome: string, instance: AppInstance, info: { readonly pid: number, readonly surface?: string, readonly port?: number }): void {
|
|
30
|
+
const dir = registryDir(osHome)
|
|
31
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
32
|
+
const entry = { id: instance.id, name: instance.name, home: instance.home, ...(instance.definitionFile === undefined ? {} : { definition: instance.definitionFile }), ...info, since: new Date().toISOString() }
|
|
33
|
+
writeFileSync(join(dir, `${instance.id}.json`), `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600 })
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function withdraw(osHome: string, instance: AppInstance, pid: number = process.pid): void {
|
|
37
|
+
const file = join(registryDir(osHome), `${instance.id}.json`)
|
|
38
|
+
if (readLock(file)?.pid === pid) rmSync(file, { force: true })
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function listRunning(osHome: string, alive: (pid: number) => boolean = processIsAlive): readonly RunningApp[] {
|
|
42
|
+
const dir = registryDir(osHome)
|
|
43
|
+
if (!existsSync(dir)) return []
|
|
44
|
+
const running: RunningApp[] = []
|
|
45
|
+
for (const entry of readdirSync(dir)) {
|
|
46
|
+
const file = join(dir, entry)
|
|
47
|
+
const value = readLock(file) as unknown as RunningApp | undefined
|
|
48
|
+
if (value === undefined) continue
|
|
49
|
+
if (!alive(value.pid)) { rmSync(file, { force: true }); continue }
|
|
50
|
+
running.push(value)
|
|
51
|
+
}
|
|
52
|
+
return running.sort((a, b) => a.id.localeCompare(b.id))
|
|
53
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The composition-root selector: the ONLY code in ACRYL that reads the environment or the OS home to decide where an app lives (a test enforces it).
|
|
3
|
+
* Everything else receives an `AppInstance`, or reads it from the `appInstance` Cordis service.
|
|
4
|
+
*
|
|
5
|
+
* Precedence, highest first:
|
|
6
|
+
* ACRYL_HOME with a `blend.yaml` an app folder (managed when it sits in ~/.acryl-instances)
|
|
7
|
+
* ACRYL_HOME a pinned home
|
|
8
|
+
* DSH_HOME (legacy) a pinned engine home; the ACRYL home is its parent when it is named `.dsh`
|
|
9
|
+
* checkout is a git worktree the worktree's own home
|
|
10
|
+
* development requested ~/.acryl-dev (the main checkout's `pnpm run dev`)
|
|
11
|
+
* nothing the default ~/.acryl
|
|
12
|
+
* then ACRYL_WEB_PORT (explicit start port), ACRYL_WEB_HOST and ACRYL_WEB_TRUSTED_HOSTS (reachable beyond loopback, comma-separated names), ACRYL_INSTANCE (explicit project scope) and ACRYL_LOCAL_PRODUCT_NAME (Electron user data) refine the
|
|
13
|
+
* chosen family: they are how `instanceEnvironment` hands a family to a child process.
|
|
14
|
+
*
|
|
15
|
+
* @module @acryldev/harness-runtime/instance/select
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { existsSync, realpathSync, statSync } from 'node:fs'
|
|
19
|
+
import { homedir } from 'node:os'
|
|
20
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
21
|
+
import {
|
|
22
|
+
APP_DEFINITION_FILE,
|
|
23
|
+
DEFAULT_HOME_DIR_NAME,
|
|
24
|
+
DEVELOPMENT_HOME_DIR_NAME,
|
|
25
|
+
ENGINE_DIR_NAME,
|
|
26
|
+
MANAGED_HOMES_DIR_NAME,
|
|
27
|
+
WORKTREE_HOMES_DIR_NAME,
|
|
28
|
+
appFolderInstance,
|
|
29
|
+
appName,
|
|
30
|
+
defaultInstance,
|
|
31
|
+
withWebAccess,
|
|
32
|
+
developmentInstance,
|
|
33
|
+
pinnedInstance,
|
|
34
|
+
withProjectScope,
|
|
35
|
+
withUserDataName,
|
|
36
|
+
withWebPort,
|
|
37
|
+
worktreeInstance,
|
|
38
|
+
type AppInstance,
|
|
39
|
+
} from './app-instance.ts'
|
|
40
|
+
|
|
41
|
+
export interface SelectInstanceOptions {
|
|
42
|
+
readonly env?: Readonly<Record<string, string | undefined>>
|
|
43
|
+
readonly osHome?: string
|
|
44
|
+
/** The checkout a development launcher runs from; a git worktree gets its own instance. */
|
|
45
|
+
readonly checkout?: string
|
|
46
|
+
/** The main checkout's isolated development app (`pnpm run dev`) rather than the default. */
|
|
47
|
+
readonly development?: boolean
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Set by a gate, a smoke or a live-run launcher: this process tree must run in an explicitly isolated home. With it set, `selectInstance` refuses (fails
|
|
52
|
+
* closed) to choose a home that is not pinned by the caller or that lies inside a real ACRYL or DSH home of the OS user, so a forgotten override ends in an
|
|
53
|
+
* error naming the fix, never in a write to the installed app's data.
|
|
54
|
+
*/
|
|
55
|
+
export const REQUIRE_ISOLATED_HOME_ENV = 'ACRYL_REQUIRE_ISOLATED_HOME'
|
|
56
|
+
|
|
57
|
+
export class IsolationRequiredError extends Error {
|
|
58
|
+
constructor(detail: string) {
|
|
59
|
+
super(`${REQUIRE_ISOLATED_HOME_ENV} is set, so this run needs an explicitly isolated home: ${detail}. Pin ACRYL_HOME (and DSH_HOME) to a throwaway folder outside the OS user's real ACRYL and DSH homes.`)
|
|
60
|
+
this.name = 'IsolationRequiredError'
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const REAL_HOME_FOLDERS = [DEFAULT_HOME_DIR_NAME, DEVELOPMENT_HOME_DIR_NAME, WORKTREE_HOMES_DIR_NAME, MANAGED_HOMES_DIR_NAME, ENGINE_DIR_NAME]
|
|
65
|
+
|
|
66
|
+
const inside = (path: string, folder: string): boolean => path === folder || path.startsWith(`${folder}/`) || path.startsWith(`${folder}\\`)
|
|
67
|
+
|
|
68
|
+
function assertIsolated(instance: AppInstance, osHome: string): void {
|
|
69
|
+
if (instance.kind !== 'pinned' && instance.kind !== 'app') throw new IsolationRequiredError(`the ${instance.kind} instance would use ${instance.home}`)
|
|
70
|
+
const realHomes = REAL_HOME_FOLDERS.map(folder => real(join(osHome, folder)))
|
|
71
|
+
for (const [label, path] of [['home', instance.home], ['engine home', instance.dshHome]] as const) {
|
|
72
|
+
const resolved = real(path)
|
|
73
|
+
const hit = realHomes.find(folder => inside(resolved, folder))
|
|
74
|
+
if (hit !== undefined) throw new IsolationRequiredError(`the ${label} ${resolved} lies inside the real ${hit}`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const set = (value: string | undefined): value is string => value !== undefined && value.trim() !== ''
|
|
79
|
+
|
|
80
|
+
function real(path: string): string {
|
|
81
|
+
try { return realpathSync(path) } catch { return resolve(path) }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Is this checkout a git worktree (its `.git` is a file pointing at the main repository)? */
|
|
85
|
+
export function isGitWorktree(checkoutRoot: string): boolean {
|
|
86
|
+
const git = join(checkoutRoot, '.git')
|
|
87
|
+
return existsSync(git) && statSync(git).isFile()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The OS user's home directory: exported only so the dev launchers need not read it themselves. */
|
|
91
|
+
export function osHomeDirectory(): string {
|
|
92
|
+
return homedir()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** An app folder given by path (`bin/acryl`, `--dir`), whether or not it is the environment's choice. */
|
|
96
|
+
export function appFolder(folder: string, osHome: string = homedir()): AppInstance {
|
|
97
|
+
const root = real(folder)
|
|
98
|
+
const managedRoot = real(join(osHome, MANAGED_HOMES_DIR_NAME))
|
|
99
|
+
return appFolderInstance(root, dirname(root) === managedRoot)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A managed app by name: `~/.acryl-instances/<name>`. */
|
|
103
|
+
export function managedApp(name: string, osHome: string = homedir()): AppInstance {
|
|
104
|
+
// Validate before building a path: a name such as `../x` must never reach outside the managed root.
|
|
105
|
+
return appFolderInstance(join(osHome, MANAGED_HOMES_DIR_NAME, appName(name)), true)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function selectInstance(options: SelectInstanceOptions = {}): AppInstance {
|
|
109
|
+
const env = options.env ?? process.env
|
|
110
|
+
const osHome = options.osHome ?? homedir()
|
|
111
|
+
let chosen: AppInstance
|
|
112
|
+
if (set(env.ACRYL_HOME)) {
|
|
113
|
+
const home = resolve(env.ACRYL_HOME.trim())
|
|
114
|
+
chosen = existsSync(join(home, APP_DEFINITION_FILE)) ? appFolder(home, osHome) : pinnedInstance(home)
|
|
115
|
+
} else if (set(env.DSH_HOME)) {
|
|
116
|
+
const dshHome = resolve(env.DSH_HOME.trim())
|
|
117
|
+
chosen = pinnedInstance(basename(dshHome) === ENGINE_DIR_NAME ? dirname(dshHome) : dshHome, dshHome)
|
|
118
|
+
} else if (options.checkout !== undefined && isGitWorktree(options.checkout)) {
|
|
119
|
+
chosen = worktreeInstance(osHome, options.checkout)
|
|
120
|
+
} else if (options.development === true) {
|
|
121
|
+
chosen = developmentInstance(osHome)
|
|
122
|
+
} else {
|
|
123
|
+
chosen = defaultInstance(osHome)
|
|
124
|
+
}
|
|
125
|
+
if (set(env.ACRYL_WEB_PORT)) chosen = withWebPort(chosen, Number(env.ACRYL_WEB_PORT.trim()))
|
|
126
|
+
if (set(env.ACRYL_WEB_HOST) || set(env.ACRYL_WEB_TRUSTED_HOSTS)) {
|
|
127
|
+
const trusted = (env.ACRYL_WEB_TRUSTED_HOSTS ?? '').split(',').map(name => name.trim()).filter(name => name.length > 0)
|
|
128
|
+
chosen = withWebAccess(chosen, set(env.ACRYL_WEB_HOST) ? env.ACRYL_WEB_HOST.trim() : chosen.webAccess.host, trusted)
|
|
129
|
+
}
|
|
130
|
+
if (set(env.ACRYL_INSTANCE) && chosen.kind === 'pinned') chosen = withProjectScope(chosen, env.ACRYL_INSTANCE.trim())
|
|
131
|
+
if (set(env.ACRYL_LOCAL_PRODUCT_NAME)) chosen = withUserDataName(chosen, env.ACRYL_LOCAL_PRODUCT_NAME.trim())
|
|
132
|
+
if (set(env[REQUIRE_ISOLATED_HOME_ENV])) assertIsolated(chosen, osHome)
|
|
133
|
+
return chosen
|
|
134
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one way this runtime registers Node module hooks. Profile package routing (the overlay resolver and the DSH engine's profile
|
|
3
|
+
* resolution) needs the public `module.registerHooks`; a Node or Electron build without it fails here with a message that names the
|
|
4
|
+
* runtime, instead of a bare TypeError deep inside a boot.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import Module, { type ModuleHooks, type RegisterHooksOptions } from 'node:module'
|
|
8
|
+
|
|
9
|
+
export class ModuleHooksUnavailableError extends Error {
|
|
10
|
+
override readonly name = 'ModuleHooksUnavailableError'
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The running Node, and the Electron around it when there is one, for a message. */
|
|
14
|
+
function runtimeName(): string {
|
|
15
|
+
const electron = process.versions.electron
|
|
16
|
+
return electron === undefined ? `Node ${process.versions.node}` : `Electron ${electron} (Node ${process.versions.node})`
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The public `module.registerHooks`, checked before a caller patches anything it would have to undo.
|
|
21
|
+
* @throws {ModuleHooksUnavailableError} when this Node has none (it needs Node 22.15, 23.5 or newer).
|
|
22
|
+
*/
|
|
23
|
+
export function requireModuleHooks(): (options: RegisterHooksOptions) => ModuleHooks {
|
|
24
|
+
// Read from the default export at call time, so a test can remove it and an older runtime reaches the message below.
|
|
25
|
+
const register = (Module as { registerHooks?: (options: RegisterHooksOptions) => ModuleHooks }).registerHooks
|
|
26
|
+
if (typeof register !== 'function') {
|
|
27
|
+
throw new ModuleHooksUnavailableError(
|
|
28
|
+
`DSH provider unavailable on ${runtimeName()}: profile packages load through module.registerHooks, which this runtime lacks `
|
|
29
|
+
+ '(Node 22.15, 23.5 or newer has it)',
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
return register
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Register synchronous module hooks on Node's default loaders.
|
|
37
|
+
* @throws {ModuleHooksUnavailableError} when this Node has no `module.registerHooks`.
|
|
38
|
+
*/
|
|
39
|
+
export function registerModuleHooks(options: RegisterHooksOptions): ModuleHooks {
|
|
40
|
+
return requireModuleHooks()(options)
|
|
41
|
+
}
|