@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,9 @@
1
+ /**
2
+ * The file primitives ACRYL's own code writes state with, through the engine seam: an atomic replace (a reader sees the old or the new complete content,
3
+ * with the stated permission bits) and a cross-process writer lock (a stale holder is taken over). Today they are DeepSeek Harness's; consumers import
4
+ * them from `@acryldev/harness-runtime`, never from the DSH package, so replacing the implementation is a change to this file and nothing else.
5
+ *
6
+ * @module @acryldev/harness-runtime/engine-files
7
+ */
8
+
9
+ export { withFileLock, writeFileAtomic, type FileLockOptions, type WriteFileAtomicOptions } from '@deepseek-ai/dsh-atomic-write'
@@ -0,0 +1,128 @@
1
+ import { dirname } from 'node:path'
2
+ import { fileURLToPath, pathToFileURL } from 'node:url'
3
+ import { Context } from '@deepseek-ai/cordis'
4
+ import { Group, Loader } from '@deepseek-ai/cordis-plugin-loader'
5
+ import { selectInstance } from './instance/index.ts'
6
+
7
+ const ENGINE_ENTRY_ID = 'acryl-engine'
8
+
9
+ /**
10
+ * Fallback resolution base for the host root's own Loader entries (the
11
+ * "acryl-engine-<id>" row and mountRootInclude's sibling "cordis:include"
12
+ * row - see the `ctx.baseUrl` assignment below for why). Never read for a
13
+ * real client bundle - `dsh-client-modules` finds no client export at this
14
+ * location and skips, exactly as it does for any other non-client entry -
15
+ * so its value need not track a specific engine's own profile location.
16
+ */
17
+ const HOST_ROOT_BASE_URL = pathToFileURL(dirname(fileURLToPath(import.meta.url))).href + '/'
18
+
19
+ type CordisPlugin = Parameters<Context['plugin']>[0]
20
+
21
+ export interface AcrylEngineDefinition {
22
+ readonly id: string
23
+ readonly plugin: CordisPlugin
24
+ readonly config?: Record<string, unknown>
25
+ }
26
+
27
+ export interface AcrylEngineHost {
28
+ readonly ctx: Context
29
+ currentEngine(): string
30
+ select(id: string): Promise<void>
31
+ dispose(): Promise<void>
32
+ }
33
+
34
+ /**
35
+ * Own the one Cordis root that selects an engine provider. Individual engines
36
+ * are Loader entries beneath this host, so replacing a provider keeps the host
37
+ * and its consumers alive while Cordis performs ordinary dependency rebinding.
38
+ */
39
+ export async function createAcrylEngineHost(input: {
40
+ readonly engines: readonly AcrylEngineDefinition[]
41
+ readonly initialEngine: string
42
+ /**
43
+ * Register surface-owned services on the bare root before any engine
44
+ * mounts - mirrors `boot()`'s own `prepare` timing exactly (Loader is
45
+ * plugged, no config-tree entry has mounted yet), so a surface with its
46
+ * own non-engine capabilities (e.g. Desktop's profile/market/plugin-
47
+ * lifecycle services) can provide them ahead of an engine's Loader entries
48
+ * that `ctx.inject`/`ctx.get` them.
49
+ */
50
+ readonly prepare?: (ctx: Context) => Promise<void> | void
51
+ }): Promise<AcrylEngineHost> {
52
+ const engines = new Map<string, AcrylEngineDefinition>()
53
+ for (const engine of input.engines) {
54
+ if (engine.id.trim() === '') throw new Error('ACRYL engine id must not be empty')
55
+ if (engines.has(engine.id)) throw new Error(`duplicate ACRYL engine: ${engine.id}`)
56
+ engines.set(engine.id, engine)
57
+ }
58
+ const initial = engines.get(input.initialEngine)
59
+ if (initial === undefined) throw new Error(`unknown ACRYL engine: ${input.initialEngine}`)
60
+ // Choose the app instance before anything mounts. Engines resolve their home inside plugin fibers, where a refusal (an invalid port, or the
61
+ // isolation a gate or live run requires: `IsolationRequiredError`) would only fail that plugin and leave an app that boots without its profile and
62
+ // exits 0. Here it stops the host, for every surface.
63
+ selectInstance()
64
+
65
+ const ctx = new Context()
66
+ // `EntryTree`'s constructor snapshots `ctx.baseUrl` once, as an own
67
+ // property (`ctx.extend({ baseUrl: ctx.baseUrl })`) - not a live read - at
68
+ // the moment the Loader plugin constructs its root tree, i.e. exactly this
69
+ // `ctx.plugin(Loader)` call below. Every entry created directly on this
70
+ // root (the "acryl-engine-<id>" row this function creates, and
71
+ // mountRootInclude's sibling "cordis:include" row - see engine-dsh.ts)
72
+ // permanently inherits whatever `ctx.baseUrl` was at this line; setting it
73
+ // later (inside an engine's own plugin, or even inside `prepare` below,
74
+ // which also runs after this line) cannot reach that already-taken
75
+ // snapshot. Reproduced directly: Desktop's real composition failed with
76
+ // "loader entry cordis:acryl-engine-dsh has no resolution base URL" from
77
+ // `dsh-client-modules` (Desktop composes client bundles; CLI/TUI does not,
78
+ // which is why no automated test caught this) before this assignment
79
+ // existed - confirmed via `entry.parent.tree.ctx.baseUrl` reading
80
+ // `undefined` for exactly these two entries, and every entry nested one
81
+ // level deeper (inside the profile's own composed tree, constructed later
82
+ // from a ctx that does have baseUrl set) reading correctly.
83
+ ctx.baseUrl = HOST_ROOT_BASE_URL
84
+ await ctx.plugin(Loader)
85
+ const entryFor = (engine: AcrylEngineDefinition) => ({
86
+ id: ENGINE_ENTRY_ID,
87
+ name: `cordis:acryl-engine-${engine.id}`,
88
+ ...(engine.config === undefined ? {} : { config: engine.config }),
89
+ })
90
+ try {
91
+ await input.prepare?.(ctx)
92
+ ctx.loader.builtins.group = Group
93
+ for (const engine of engines.values()) ctx.loader.builtins[`acryl-engine-${engine.id}`] = engine.plugin
94
+ await ctx.loader.create(entryFor(initial))
95
+ await ctx.loader.await()
96
+ } catch (error) {
97
+ await ctx.fiber.dispose()
98
+ throw error
99
+ }
100
+
101
+ let active = initial.id
102
+ let disposed = false
103
+
104
+ return Object.freeze({
105
+ ctx,
106
+ currentEngine: () => active,
107
+ async select(id: string): Promise<void> {
108
+ if (disposed) throw new Error('ACRYL engine host is disposed')
109
+ const next = engines.get(id)
110
+ if (next === undefined) throw new Error(`unknown ACRYL engine: ${id}`)
111
+ if (next.id === active) return
112
+ // Loader 1.0.5 (Cordis family of DSH 0.2) re-imports a row only when it is created: `Entry.update` on a running row applies a
113
+ // changed `config` but ignores a changed plugin `name`. So a swap removes the row (waiting for its fiber to finish
114
+ // disposing, so the old engine's effects stop before the new one's start) and creates it again under the same stable id.
115
+ const previous = ctx.loader.resolve(ENGINE_ENTRY_ID).fiber
116
+ ctx.loader.remove(ENGINE_ENTRY_ID)
117
+ await previous?.dispose()
118
+ await ctx.loader.create(entryFor(next))
119
+ await ctx.loader.await()
120
+ active = next.id
121
+ },
122
+ async dispose(): Promise<void> {
123
+ if (disposed) return
124
+ disposed = true
125
+ await ctx.fiber.dispose()
126
+ },
127
+ })
128
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The `acrylTools` provider: ACRYL's tools port (`@acryldev/control`) answered by DeepSeek Harness's tool registry today. A thin delegate: a tool defined
3
+ * through the port is an ordinary Harness tool (same `defineTool`, same registry), a call through `execute` runs the registry's whole pipeline, and a
4
+ * policy registered through `policy` is a `tools/pre-execute` hook like any other. When the registry is replaced the adapter and its consumers unload
5
+ * together and register again.
6
+ *
7
+ * @module @acryldev/harness-runtime/engine-tools
8
+ */
9
+
10
+ import type { Context } from '@deepseek-ai/cordis'
11
+ import { defineTool } from '@deepseek-ai/dsh-tools'
12
+ import type { AcrylTools } from '@acryldev/control'
13
+
14
+ /** Provide `acrylTools` on `ctx`, which must be able to see `tools` (call it inside `ctx.inject(['tools'], ...)`). */
15
+ export function provideAcrylTools(ctx: Context): void {
16
+ const port: AcrylTools = {
17
+ register: definition => ctx.tools.register(defineTool(definition as never)),
18
+ get: name => ctx.tools.get(name) as ReturnType<AcrylTools['get']>,
19
+ execute: input => ctx.tools.execute(input as never) as Promise<Awaited<ReturnType<AcrylTools['execute']>>>,
20
+ policy: handler => ctx.on('tools/pre-execute', handler as never),
21
+ }
22
+ ctx.effect(() => {
23
+ const dispose = ctx.reflect.provide('acrylTools', port)
24
+ return () => { void dispose() }
25
+ }, '@acryldev/harness-runtime: acrylTools')
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,436 @@
1
+ export {
2
+ ACRYL_CODING_CAPABILITIES,
3
+ type AcrylCodingCapabilityDeclaration,
4
+ type AcrylCodingCapabilityId,
5
+ type AcrylShellMode,
6
+ type AcrylSurface,
7
+ } from './coding-capabilities.ts'
8
+ export type { CodingCapabilities } from './engine-dsh.ts'
9
+ export type {
10
+ DurableSessionMessage,
11
+ DurableSessionMessagePort,
12
+ DurableSessionMessageReceipt,
13
+ } from './durable-message.ts'
14
+ export {
15
+ createAcrylSessionBridge,
16
+ type AcrylSessionBridge,
17
+ type AcrylSessionBridgeOptions,
18
+ } from './session-bridge.ts'
19
+ export {
20
+ installSessionLogExporter,
21
+ type InstallSessionLogExporterOptions,
22
+ } from './session-log-exporter.ts'
23
+ export {
24
+ ACRYL_DEV_HOME_DIR_NAME,
25
+ ACRYL_DSH_ENGINE_DIR_NAME,
26
+ ACRYL_HOME_DIR_NAME,
27
+ applyIsolatedDevHomeDefault,
28
+ resolveAcrylDevDshHome,
29
+ resolveAcrylDshHome,
30
+ resolveAcrylHome,
31
+ } from './acryl-home.ts'
32
+ export {
33
+ createAcrylEngineHost,
34
+ type AcrylEngineDefinition,
35
+ type AcrylEngineHost,
36
+ } from './engine-host.ts'
37
+ export {
38
+ createDshEngineDefinition,
39
+ createDshEngineDefinitionFromComposition,
40
+ createProfileContext,
41
+ createProfileRuntimeResolution,
42
+ createWebEngineDefinition,
43
+ pluginRequiredFrameworkPackages,
44
+ profileRequiredFrameworkModules,
45
+ materializeProfilePackage,
46
+ UPSTREAM_PRODUCT_ANALYTICS_OFF,
47
+ type AcrylFrameworkPackages,
48
+ type DshEngineComposition,
49
+ } from './engine-dsh.ts'
50
+ export {
51
+ PackageOverlayNotFoundError,
52
+ findOverlayPackage,
53
+ packageNameFromSpecifier,
54
+ resolveOverlayPackage,
55
+ type PackageOverlayCandidate,
56
+ type PackageOverlayOptions,
57
+ type PackageOverlaySelection,
58
+ type PackageOverlaySource,
59
+ } from './package-overlay.ts'
60
+ export {
61
+ installProfilePackageResolver,
62
+ type InstallProfilePackageResolverOptions,
63
+ } from './module-resolution.ts'
64
+ export {
65
+ provideWebMarketInstall,
66
+ WebPnpmService,
67
+ WebProfilesService,
68
+ type WebMarketPnpm,
69
+ type WebMarketPnpmHandle,
70
+ type WebMarketPnpmOutcome,
71
+ type WebMarketProfile,
72
+ } from './web-market-install.ts'
73
+ export {
74
+ provideWebMarketPlugins,
75
+ WebLiveActivationService,
76
+ WebPluginsService,
77
+ type WebMarketPluginBundle,
78
+ } from './web-market-plugins.ts'
79
+ export {
80
+ provideCliMarketInstall,
81
+ CliPnpmService,
82
+ CliProfilesService,
83
+ type CliMarketPnpm,
84
+ type CliMarketPnpmHandle,
85
+ type CliMarketPnpmOutcome,
86
+ type CliMarketProfile,
87
+ } from './cli-market-install.ts'
88
+ export {
89
+ provideCliMarketPlugins,
90
+ CliLiveActivationService,
91
+ CliPluginsService,
92
+ type CliMarketPluginBundle,
93
+ } from './cli-market-plugins.ts'
94
+ export {
95
+ createAcrylPluginLifecycle,
96
+ createDshPluginLifecycleHost,
97
+ mountAcrylPluginLifecycle,
98
+ type DshPluginLifecycleOptions,
99
+ } from './plugin-lifecycle.ts'
100
+ export {
101
+ BASE_TEMPLATE_BUNDLE_NAMES,
102
+ assertProfileName,
103
+ entryPatchId,
104
+ isPluginLifecycleEntryId,
105
+ pluginLifecyclePatches,
106
+ readDisabledPluginLifecycleEntries,
107
+ readUserMutableBundleNames,
108
+ resolvePluginLifecycleStatePath,
109
+ setPluginLifecycleEntryEnabled,
110
+ type PluginLifecycleStatePersistence,
111
+ type ProfileNameValidator,
112
+ } from './plugin-lifecycle-state.ts'
113
+ export {
114
+ diagnosePluginLifecycle,
115
+ type PluginHealthCode,
116
+ type PluginHealthFinding,
117
+ type PluginHealthInput,
118
+ type PluginHealthReport,
119
+ type PluginHealthSeverity,
120
+ } from './plugin-doctor.ts'
121
+ // The lifecycle vocabulary itself belongs to `@acryldev/control`, the domain
122
+ // package. Surfaces depend on this runtime, not on the domain package, so the
123
+ // shared contract is re-exported here rather than duplicated per surface; one
124
+ // `PluginLifecycleError` class has to be the one every surface throws and
125
+ // catches, or its `code` stops crossing a route boundary.
126
+ export {
127
+ AcrPluginLifecycleService,
128
+ PROTECTED_PLUGIN_ENTRY_REASON,
129
+ PluginLifecycleError,
130
+ type AcrPluginLifecycle,
131
+ type AcrPluginLifecycleController,
132
+ type PluginLifecycleAction,
133
+ type PluginLifecycleEntryRef,
134
+ type PluginLifecycleEntryView,
135
+ type PluginLifecycleErrorCode,
136
+ type PluginLifecycleFiberPhase,
137
+ type PluginLifecycleHost,
138
+ type PluginLifecycleMountedStatus,
139
+ type PluginLifecycleReceipt,
140
+ type PluginLifecycleSnapshot,
141
+ } from '@acryldev/control'
142
+
143
+ import { writeFileSync } from 'node:fs'
144
+ import { createRequire } from 'node:module'
145
+ import { join } from 'node:path'
146
+ import type { Context } from '@deepseek-ai/cordis'
147
+ import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
148
+ import {
149
+ DEFAULT_PROFILE_BUNDLES,
150
+ PROFILE_TEMPLATES,
151
+ boot,
152
+ composeEntries,
153
+ initProfile,
154
+ loadProfile,
155
+ removeLinkProjections,
156
+ resolveProfileDir,
157
+ type RuntimeResolution,
158
+ } from '@deepseek-ai/dsh-app-boot'
159
+
160
+ import { createProfileRuntimeResolution } from './engine-dsh.ts'
161
+ import { selectInstance, type AppInstance } from './instance/index.ts'
162
+ import { materializeProfilePackage, type CodingCapabilities } from './engine-dsh.ts'
163
+ import { installAcrylWorkspaceStatusTool } from './plugin-acryl-workspace-status.ts'
164
+ import { ProfilePluginPackages } from './profile-resolution/service.ts'
165
+ import { installSessionLogExporter } from './session-log-exporter.ts'
166
+
167
+ const require = createRequire(import.meta.url)
168
+ const dshInstallAnchor = require.resolve('@deepseek-ai/dsh/package.json')
169
+ const profileRoot = '[]\n'
170
+
171
+ export interface BootAcrylHarnessProfileOptions {
172
+ readonly profile: string
173
+ /** The surface's capability composition (`@acryldev/coding-capabilities`); without it only the profile's own rows compose. */
174
+ readonly capabilities?: CodingCapabilities
175
+ readonly prepare?: (ctx: Context) => Promise<void> | void
176
+ }
177
+
178
+ /**
179
+ * Provide the chosen app instance and the profile's package table (DSH 0.2 answers every bare-package import from it, as stock
180
+ * `dsh` mounts it in its own boot step) before any profile entry mounts, then run the caller's own host setup.
181
+ */
182
+ function withAppInstance(
183
+ instance: AppInstance,
184
+ resolution: RuntimeResolution,
185
+ prepare?: (ctx: Context) => Promise<void> | void,
186
+ ): (ctx: Context) => Promise<void> {
187
+ return async ctx => {
188
+ ctx.provide('appInstance', instance)
189
+ await ctx.plugin(ProfilePluginPackages, { resolution })
190
+ await prepare?.(ctx)
191
+ }
192
+ }
193
+
194
+ export interface AcrylHarnessRuntime {
195
+ readonly ctx: Context
196
+ readonly profileDirectory: string
197
+ dispose(): Promise<void>
198
+ }
199
+
200
+ /** Boot one normal pinned-Harness ACRYL profile in a single Cordis root. */
201
+ export async function bootAcrylHarnessProfile(
202
+ options: BootAcrylHarnessProfileOptions,
203
+ ): Promise<AcrylHarnessRuntime> {
204
+ if (options.profile.trim() === '') throw new Error('ACRYL Harness profile must not be empty')
205
+ // This boot is its own composition root: it chooses the app instance once and provides it to plugins (runtime instance/).
206
+ const instance = selectInstance()
207
+ process.env.DSH_HOME = instance.dshHome
208
+ const profileDirectory = resolveProfileDir(options.profile)
209
+ initProfile(profileDirectory, DEFAULT_PROFILE_BUNDLES)
210
+ removeLinkProjections(profileDirectory)
211
+ const profile = loadProfile('acryl', options.profile, dshInstallAnchor)
212
+ const rootConfig = join(profile.dir, 'cordis.yml')
213
+ writeFileSync(rootConfig, profileRoot)
214
+ // The terminal capabilities' ACRYL packages, resolvable from this profile as the CLI and Web boots make them; without it their rows
215
+ // fail to import (`@acryldev/settings`, the account sign-in callback).
216
+ const tuiSurfaces = new Set(['tui'] as const)
217
+ for (const packageName of options.capabilities?.packages(tuiSurfaces, new Set()) ?? [])
218
+ materializeProfilePackage(profile.dir, packageName, options.capabilities?.anchors[0] ?? import.meta.url)
219
+ const patches = structuredClone([
220
+ ...profile.layers.flatMap(layer => layer.patches),
221
+ ...(options.capabilities?.patches(tuiSurfaces, new Set(), new Set()) ?? []),
222
+ ...profile.patches,
223
+ ])
224
+ const hmr = composeEntries([patches]).find(entry => entry.id === 'hmr')
225
+ if (hmr?.disabled !== true && !process.execArgv.includes('--expose-internals')) {
226
+ throw new Error(
227
+ 'ACRYL profile enables Cordis HMR and must be launched with Node --expose-internals',
228
+ )
229
+ }
230
+ const ctx = await boot('acryl', rootConfig, patches, withAppInstance(instance, await createProfileRuntimeResolution(profile), options.prepare))
231
+ if ((ctx as { tools?: unknown }).tools) installAcrylWorkspaceStatusTool(ctx)
232
+ installSessionLogExporter(ctx, { surface: 'tui', dshHome: instance.dshHome })
233
+ let disposed = false
234
+ return Object.freeze({
235
+ ctx,
236
+ profileDirectory: profile.dir,
237
+ async dispose() {
238
+ if (disposed) return
239
+ disposed = true
240
+ await ctx.fiber.dispose()
241
+ },
242
+ })
243
+ }
244
+
245
+ export interface BootAcrylWebProfileOptions {
246
+ /** Inner arguments handed to the web-startup provider (e.g. `['--port', '4000']`). Defaults to no flags. */
247
+ readonly cmdlineArgs?: readonly string[]
248
+ /** The surface's capability composition (`@acryldev/coding-capabilities`); without it only the profile's own rows compose. */
249
+ readonly capabilities?: CodingCapabilities
250
+ /** Host setup run after Loader installation and before any config-tree entry mounts. */
251
+ readonly prepare?: (ctx: Context) => Promise<void> | void
252
+ }
253
+
254
+ export interface AcrylWebRuntime {
255
+ readonly ctx: Context
256
+ /** The canonical bind URL, e.g. `http://127.0.0.1:3080`. */
257
+ readonly url: string
258
+ readonly profileDirectory: string
259
+ dispose(): Promise<void>
260
+ }
261
+
262
+ /**
263
+ * Boot the DSH browser surface (the `web` profile: `dsh-base` + `dsh-web-app`)
264
+ * as one normal ACRYL runtime, so `pnpm acryl-web` serves the same DSH
265
+ * HTTP/WebSocket seam the web surface always uses. The shipped Web profile
266
+ * already owns its system prompt, agent-preset roster, and session stats, so
267
+ * the shared factory contributes only the missing authorization seam here.
268
+ */
269
+ export async function bootAcrylWebProfile(
270
+ options: BootAcrylWebProfileOptions = {},
271
+ ): Promise<AcrylWebRuntime> {
272
+ const profileName = 'web'
273
+ // This boot is its own composition root: it chooses the app instance once and provides it to plugins (runtime instance/).
274
+ const instance = selectInstance()
275
+ process.env.DSH_HOME = instance.dshHome
276
+ const profileDirectory = resolveProfileDir(profileName)
277
+ // See engine-dsh.ts's resolveWebEngineComposition for the full rationale:
278
+ // DEFAULT_PROFILE_BUNDLES (dsh-base only) pre-empts loadProfile()'s own
279
+ // correct PROFILE_TEMPLATES.web-based auto-init (dsh-base + dsh-web-app),
280
+ // leaving a fresh 'web' profile with no dsh-client-connection/webStartup -
281
+ // ctx.get('connection') and ctx.get('webStartup') are never defined, and
282
+ // the served index falls back to its own "authentication required" message.
283
+ const webTemplate = PROFILE_TEMPLATES.web
284
+ initProfile(profileDirectory, webTemplate?.bundles ?? DEFAULT_PROFILE_BUNDLES)
285
+ removeLinkProjections(profileDirectory)
286
+ const profile = loadProfile('web', profileName, dshInstallAnchor)
287
+ const rootConfig = join(profile.dir, 'cordis.yml')
288
+ writeFileSync(rootConfig, profileRoot)
289
+ // Same composition as the engine-host Web path: the shared workspace and shell declarations, with the ACRYL
290
+ // packages they name made resolvable from this profile.
291
+ const webSurfaces = new Set(['web'] as const)
292
+ for (const packageName of options.capabilities?.packages(webSurfaces, new Set()) ?? []) {
293
+ materializeProfilePackage(profile.dir, packageName, options.capabilities?.anchors[0] ?? import.meta.url)
294
+ }
295
+ const patches = structuredClone([
296
+ ...profile.layers.flatMap(layer => layer.patches),
297
+ ...(options.capabilities?.patches(webSurfaces, new Set(), new Set()) ?? []),
298
+ ...(options.capabilities?.shellPatches(webSurfaces, 'advanced', new Set(), new Set()) ?? []),
299
+ ...profile.patches,
300
+ ])
301
+ const cmdlineArgs = options.cmdlineArgs ?? []
302
+ const ctx = await boot('web', rootConfig, patches, withAppInstance(instance, await createProfileRuntimeResolution(profile), hostCtx => {
303
+ provideCmdline(hostCtx, { args: [...cmdlineArgs], exit: code => { process.exitCode = code } })
304
+ return options.prepare?.(hostCtx)
305
+ }))
306
+ if ((ctx as { tools?: unknown }).tools) installAcrylWorkspaceStatusTool(ctx)
307
+ installSessionLogExporter(ctx, { surface: 'web', dshHome: instance.dshHome })
308
+ const startup = ctx.get('webStartup') as { host?: string; port?: number } | undefined
309
+ const host = startup?.host ?? '127.0.0.1'
310
+ const port = startup?.port ?? instance.webPort.start
311
+ const url = `http://${host}:${port}`
312
+ let disposed = false
313
+ return Object.freeze({
314
+ ctx,
315
+ url,
316
+ profileDirectory: profile.dir,
317
+ async dispose() {
318
+ if (disposed) return
319
+ disposed = true
320
+ await ctx.fiber.dispose()
321
+ },
322
+ })
323
+ }
324
+ export {
325
+ captureSystemPrompt,
326
+ renderSystemPromptDoc,
327
+ type CaptureSystemPromptOptions,
328
+ type CapturedSystemPrompt,
329
+ } from './system-prompt-capture.ts'
330
+ export { pinnedPnpmEnv, resolvePinnedPnpm, type PinnedPnpm } from './pinned-pnpm.ts'
331
+ export { reconcileProfileLayout, type LayoutChange } from './profile-layout.ts'
332
+ export {
333
+ AGENTS_BLUEPRINT,
334
+ BLANK_BLUEPRINT,
335
+ DSH_CHAT_ROW_IDS,
336
+ DSH_PLUGIN_MANAGER_ROW_ID,
337
+ PLUGIN_MANAGER_ROW_ID,
338
+ IDE_BLUEPRINT,
339
+ BLUEPRINT_ROW_IDS,
340
+ InvalidBlueprintError,
341
+ InvalidBrandIdentityError,
342
+ UnknownBlueprintError,
343
+ appManifest,
344
+ blueprintFromManifest,
345
+ catalogWithStarters,
346
+ isBlendsManifest,
347
+ parseBlueprint,
348
+ readBlueprintFile,
349
+ readStarters,
350
+ blueprintFromEnvironment,
351
+ brandIdentity,
352
+ builtInCatalog,
353
+ composeBlueprintRows,
354
+ currentModule,
355
+ identityLine,
356
+ packageOfModule,
357
+ selectBlueprint,
358
+ withBrand,
359
+ type Blueprint,
360
+ type BlueprintBrand,
361
+ type BlueprintCatalog,
362
+ type BlueprintComposition,
363
+ type BlueprintRowId,
364
+ type BrandIdentity,
365
+ } from './blueprint/index.ts'
366
+ export {
367
+ SAFE_RECIPES,
368
+ applyRepairPlan,
369
+ backupsDir,
370
+ createBackup,
371
+ describePlan,
372
+ inspectProfile,
373
+ isSafeRecipe,
374
+ listBackups,
375
+ planRepairs,
376
+ restoreBackup,
377
+ undoRepair,
378
+ } from './profile-repair/index.ts'
379
+ export type {
380
+ BackupEntry,
381
+ BackupManifest,
382
+ InspectOptions,
383
+ ProfileDiagnosis,
384
+ ProfileFinding,
385
+ ProfileFindingCode,
386
+ RecipeId,
387
+ RepairPlan,
388
+ RepairResult,
389
+ RepairStep,
390
+ } from './profile-repair/index.ts'
391
+ export { WEB_PORT_ATTEMPTS, findFreeWebPort, loopbackPortIsFree, webPortPatch } from './web-port.ts'
392
+ export { APP_MANIFEST_FILE, APP_PLUGINS_DIR, NewAppError, planNewApp, writeNewApp, type LauncherFile, type NewAppOptions, type PlannedApp } from './app/new-app.ts'
393
+ export { PROFILE_OWNER_FILE, ProfileInUseError, claimProfile, type ProfileOwner } from './profile-owner.ts'
394
+ export {
395
+ APP_DEFINITION_FILE,
396
+ AppInstanceError,
397
+ LockHeldError,
398
+ acquireLock,
399
+ announce,
400
+ announceSelf,
401
+ appFolder,
402
+ appFolderInstance,
403
+ appName,
404
+ defaultInstance,
405
+ developmentInstance,
406
+ instanceEnvironment,
407
+ IsolationRequiredError,
408
+ isGitWorktree,
409
+ listRunning,
410
+ managedApp,
411
+ ONLINE_SECRET_FILE_NAME,
412
+ onlineSecretPath,
413
+ osHomeDirectory,
414
+ pinnedInstance,
415
+ processIsAlive,
416
+ profileDir,
417
+ readLock,
418
+ readOnlineSecret,
419
+ releaseLock,
420
+ removeOnlineSecret,
421
+ REQUIRE_ISOLATED_HOME_ENV,
422
+ runLockFileForDshHome,
423
+ selectInstance,
424
+ stablePort,
425
+ withdraw,
426
+ worktreeInstance,
427
+ writeOnlineSecret,
428
+ InstanceAnnounceError,
429
+ type AppInstance,
430
+ type AppInstanceKind,
431
+ type LockHolder,
432
+ type RunningApp,
433
+ type SelfAnnouncement,
434
+ type SelectInstanceOptions,
435
+ } from './instance/index.ts'
436
+ export { PUBLIC_REGISTRY, StartSourceError, classifyStartSource, gitClone, resolveStartSource, type GitClone, type ResolvedStartSource, type StartSource } from './app/start-source.ts'
@@ -0,0 +1,88 @@
1
+ /**
2
+ * A composition root's own claim and announcement (spec 048 T011). The process that serves an app takes the app's run lock and writes its Registry entry
3
+ * once it knows the address it really listens on, and gives both back when it exits; `acryl control list` then finds every running app, whichever launcher
4
+ * started it. A launcher that only spawns the app (scripts/blank.mjs, the dev runners) no longer holds the lock: the process that serves the app does, so a
5
+ * stop signal reaches it directly and the port in the Registry is the bound one, not the one that was asked for.
6
+ *
7
+ * @module @acryldev/harness-runtime/instance/announce-self
8
+ */
9
+
10
+ import type { AppInstance } from './app-instance.ts'
11
+ import { acquireLock, LockHeldError, releaseLock } from './offline-lock.ts'
12
+ import { announce, withdraw } from './registry.ts'
13
+ import { osHomeDirectory } from './select.ts'
14
+
15
+ /** What the running process tells the Registry about itself. */
16
+ export interface SelfAnnouncementInfo {
17
+ /** The surface serving the app: `web`, `desktop` or `cli`. */
18
+ readonly surface: string
19
+ /** The port it is listening on, when the surface serves one. */
20
+ readonly port?: number
21
+ /** The announcing process; defaults to this one. */
22
+ readonly pid?: number
23
+ /** The OS user's home holding the Registry; defaults to the real one (the selector is the only reader of it). */
24
+ readonly osHome?: string
25
+ /** How to tell whether a holder is still alive; defaults to the process table. */
26
+ readonly alive?: (pid: number) => boolean
27
+ }
28
+
29
+ /** The claim and announcement this process holds, and the one call that gives them back. */
30
+ export interface SelfAnnouncement {
31
+ readonly id: string
32
+ readonly port?: number
33
+ /** Take the announcement and the lock back. Idempotent, and it never removes another process's claim. */
34
+ release(): void
35
+ }
36
+
37
+ /** Refused because another live process already runs this app. */
38
+ export class InstanceAnnounceError extends Error {
39
+ constructor(message: string) {
40
+ super(message)
41
+ this.name = 'InstanceAnnounceError'
42
+ }
43
+ }
44
+
45
+ function describeHolder(instance: AppInstance, holder: { readonly pid: number, readonly [key: string]: unknown }): string {
46
+ const surface = typeof holder.surface === 'string' ? `, ${holder.surface}` : ''
47
+ const port = typeof holder.port === 'number' ? `, port ${String(holder.port)}` : ''
48
+ return `app "${instance.id}" is already running (pid ${String(holder.pid)}${surface}${port}). Stop it (node scripts/instances.mjs stop ${instance.id}) or start another app.`
49
+ }
50
+
51
+ /**
52
+ * Claim `instance` for this process and announce it, with the real port. Throws {@link InstanceAnnounceError} when a different live process already holds
53
+ * the app; a stale lock (its holder is gone) is taken over, as everywhere else in the instance module.
54
+ */
55
+ export function announceSelf(instance: AppInstance, info: SelfAnnouncementInfo): SelfAnnouncement {
56
+ const pid = info.pid ?? process.pid
57
+ const osHome = info.osHome ?? osHomeDirectory()
58
+ const entry = {
59
+ id: instance.id,
60
+ home: instance.home,
61
+ pid,
62
+ surface: info.surface,
63
+ ...(info.port === undefined ? {} : { port: info.port }),
64
+ }
65
+ try {
66
+ acquireLock(instance.runLockFile, entry, {
67
+ ...(info.alive === undefined ? {} : { alive: info.alive }),
68
+ // This process re-announcing (an engine swap under one root) keeps its own claim; any other live process is refused.
69
+ compatible: current => current.pid === pid,
70
+ describe: current => describeHolder(instance, current),
71
+ })
72
+ } catch (error) {
73
+ if (error instanceof LockHeldError) throw new InstanceAnnounceError(error.message)
74
+ throw error
75
+ }
76
+ announce(osHome, instance, entry)
77
+ let released = false
78
+ return Object.freeze({
79
+ id: instance.id,
80
+ ...(info.port === undefined ? {} : { port: info.port }),
81
+ release(): void {
82
+ if (released) return
83
+ released = true
84
+ withdraw(osHome, instance, pid)
85
+ releaseLock(instance.runLockFile, pid)
86
+ },
87
+ })
88
+ }