@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,215 @@
1
+ /**
2
+ * Web's own `desktopPlugins` capability (spec 034 T006, scoped v1) - the
3
+ * package-name/preview-token-shaped adapter `@acryldev/cordis-plugin-market`'s install
4
+ * service needs for `disabledPackageNames()` (a hard requirement even for a
5
+ * plain install - `previewInstall` checks a target isn't already disabled),
6
+ * plus real enable/disable for its Installed tab.
7
+ *
8
+ * Not a new lifecycle implementation: wraps the SAME shared
9
+ * `AcrPluginLifecycleController` (spec 034 T005) the CLI's own `acryl
10
+ * plugin enable/disable` and Desktop's Lifecycle tab already drive - this
11
+ * file is only the market-shaped view over it, matching how
12
+ * `acryl-desktop/src/plugins/desktop-plugins.ts` is Desktop's own view over the
13
+ * identical shared controller.
14
+ *
15
+ * `bundleId` here is simply the Loader `entryId` - Web owns both sides of
16
+ * this contract, so there is no need for a second opaque identifier layer
17
+ * the way Desktop's own richer bundle-tracking might want one.
18
+ */
19
+
20
+ import { randomUUID } from 'node:crypto'
21
+ import { type Context, Service } from '@deepseek-ai/cordis'
22
+ import type { AcrPluginLifecycleController } from '@acryldev/control'
23
+ import {
24
+ mountAcrylPluginLifecycle,
25
+ type DshPluginLifecycleOptions,
26
+ } from './plugin-lifecycle.ts'
27
+
28
+ export interface WebMarketPluginBundle {
29
+ readonly bundleId: string
30
+ readonly packageName: string
31
+ readonly status: 'active' | 'disabled'
32
+ readonly mutable: boolean
33
+ }
34
+
35
+ interface PreviewEntry {
36
+ readonly entryId: string
37
+ readonly packageName: string
38
+ readonly targetEnabled: boolean
39
+ readonly expiresAt: number
40
+ }
41
+
42
+ // No `declare module '@deepseek-ai/cordis'` augmentation here - see the
43
+ // identical note in web-market-install.ts. acryl-desktop's own
44
+ // desktop-plugins.ts already declares `desktopPlugins` on Context with its
45
+ // own type; a second, differently-shaped declaration for the same name is a
46
+ // hard TypeScript merge conflict across packages, not something either side
47
+ // can quietly win. `Service`'s constructor takes a plain `name: string`, so
48
+ // providing under this exact name needs no static declaration at all.
49
+
50
+ const PREVIEW_TTL_MS = 5 * 60 * 1000
51
+ const MAX_PREVIEWS = 256
52
+ /** Matches @acryldev/cordis-plugin-market's own PACKAGE_NAME_PATTERN - it rejects the whole list if even one entry isn't a real npm package name. */
53
+ const NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u
54
+
55
+ /** Matches `@acryldev/cordis-plugin-market`'s own `MarketDesktopPlugins` shape exactly - the six methods it actually calls. */
56
+ export class WebPluginsService extends Service {
57
+ private readonly previews = new Map<string, PreviewEntry>()
58
+
59
+ private readonly controller: AcrPluginLifecycleController
60
+ private readonly profileName: string
61
+
62
+ constructor(ctx: Context, options: { readonly controller: AcrPluginLifecycleController; readonly profileName: string }) {
63
+ super(ctx, 'desktopPlugins')
64
+ this.controller = options.controller
65
+ this.profileName = options.profileName
66
+ }
67
+
68
+ list(): readonly WebMarketPluginBundle[] {
69
+ return this.controller.snapshot().entries
70
+ // A Loader row's own `moduleName` is often not npm-package-shaped at
71
+ // all (`cordis:group`, `cordis:include`, ...) - the market validates
72
+ // every name it receives against exactly this npm-package pattern
73
+ // (`@acryldev/cordis-plugin-market`'s own PACKAGE_NAME_PATTERN) and hard-rejects
74
+ // the whole list if even one entry fails, so this filter isn't
75
+ // optional cosmetics.
76
+ .filter(entry => NPM_PACKAGE_NAME_PATTERN.test(entry.moduleName))
77
+ .map(entry => ({
78
+ bundleId: entry.entryId,
79
+ packageName: entry.moduleName,
80
+ status: entry.enabled ? 'active' : 'disabled',
81
+ mutable: entry.mutable,
82
+ }))
83
+ }
84
+
85
+ disabledPackageNames(): readonly string[] {
86
+ return this.controller.snapshot().entries
87
+ .filter(entry => !entry.enabled && NPM_PACKAGE_NAME_PATTERN.test(entry.moduleName))
88
+ .map(entry => entry.moduleName)
89
+ }
90
+
91
+ isDisabled(packageName: string): boolean {
92
+ return this.disabledPackageNames().includes(packageName)
93
+ }
94
+
95
+ private mintPreview(bundleId: string, targetEnabled: boolean): { readonly previewId: string; readonly profileName: string; readonly packageName: string; readonly expiresAt: string } {
96
+ const entry = this.controller.snapshot().entries.find(candidate => candidate.entryId === bundleId)
97
+ if (entry === undefined) throw new Error(`web plugins: no such bundle ${JSON.stringify(bundleId)}`)
98
+ if (!entry.mutable) throw new Error(`web plugins: bundle ${JSON.stringify(bundleId)} is not user-mutable`)
99
+ const expectedCurrent = !targetEnabled
100
+ if (entry.enabled !== expectedCurrent) {
101
+ throw new Error(`web plugins: bundle ${JSON.stringify(bundleId)} is already ${entry.enabled ? 'enabled' : 'disabled'}`)
102
+ }
103
+ // Bounded like Desktop's own preview cache - a preview is a short-lived
104
+ // confirmation token, not persisted state; dropping the oldest on
105
+ // overflow is an acceptable, simple eviction for a purely defensive cap.
106
+ if (this.previews.size >= MAX_PREVIEWS) {
107
+ const oldest = this.previews.keys().next().value
108
+ if (oldest !== undefined) this.previews.delete(oldest)
109
+ }
110
+ const previewId = randomUUID()
111
+ const expiresAt = Date.now() + PREVIEW_TTL_MS
112
+ this.previews.set(previewId, { entryId: bundleId, packageName: entry.moduleName, targetEnabled, expiresAt })
113
+ return { previewId, profileName: this.profileName, packageName: entry.moduleName, expiresAt: new Date(expiresAt).toISOString() }
114
+ }
115
+
116
+ previewDisable(bundleId: string) {
117
+ return this.mintPreview(bundleId, false)
118
+ }
119
+
120
+ previewEnable(bundleId: string) {
121
+ return this.mintPreview(bundleId, true)
122
+ }
123
+
124
+ // `controller.setEnabled()` applies the change through Cordis' own reactive
125
+ // Loader (`entry.update({ disabled: ... })`, spec 032's hot-reload
126
+ // mechanism) before resolving - a resolved call has already taken effect
127
+ // live, so success here always means `live: true`. `MarketDesktopPlugins`
128
+ // (@acryldev/cordis-plugin-market/src/host/routes.ts) requires this field to decide
129
+ // `restartRequired`; omitting it left `restartRequired` permanently `true`
130
+ // for Web regardless of whether the toggle actually applied live.
131
+ private async execute(previewId: string, targetEnabled: boolean): Promise<{ readonly packageName: string; readonly live: boolean }> {
132
+ const preview = this.previews.get(previewId)
133
+ if (preview === undefined || preview.targetEnabled !== targetEnabled) {
134
+ throw new Error('web plugins: preview not found or expired')
135
+ }
136
+ this.previews.delete(previewId)
137
+ if (Date.now() > preview.expiresAt) throw new Error('web plugins: preview expired')
138
+ await this.controller.setEnabled(preview.entryId, targetEnabled)
139
+ return { packageName: preview.packageName, live: true }
140
+ }
141
+
142
+ executeDisable(previewId: string): Promise<{ readonly packageName: string; readonly live: boolean }> {
143
+ return this.execute(previewId, false)
144
+ }
145
+
146
+ executeEnable(previewId: string): Promise<{ readonly packageName: string; readonly live: boolean }> {
147
+ return this.execute(previewId, true)
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Web's own `livePluginActivation` (spec 034 T006 follow-up, prompted by a
153
+ * real user hitting the gap: installing through the Market left the new
154
+ * plugin inactive until a full server-process restart). Matches Desktop's
155
+ * own `LivePluginActivationService` (`acryl-desktop/src/plugins/lifecycle/plugin-lifecycle-
156
+ * controller.ts`) almost line for line - both are thin wrappers over the
157
+ * exact same shared `AcrPluginLifecycleController` (spec 034 T005), whose
158
+ * `activate()`/`deactivate()`/`setEnabledByPackageName()`/`statusOfPackage()`
159
+ * are already fully generic: `activate()` resolves the just-installed
160
+ * package's own Loader row through `PluginLifecycleHost.bundleRow()` (backed
161
+ * here by the same `resolvePackageJson` this file's own `provideWebMarketPlugins`
162
+ * already wires up) and mounts it into the *live* Loader tree via
163
+ * `ctx.loader.create()` - the same proven, still-shipped host-side hot-mount
164
+ * mechanism `specs/032-universal-hot-reload`'s T1/T2/T4/T5 already landed and
165
+ * use elsewhere. Nothing new or risky is built here; this is reuse.
166
+ *
167
+ * `@acryldev/cordis-plugin-market`'s own install service calls `activate()`
168
+ * automatically right after a successful install when this service is
169
+ * present (`liveActivate` in `@acryldev/cordis-plugin-market/src/index.ts`), then
170
+ * `acknowledgeLiveInstall()` (already implemented as a no-op above - no WAL
171
+ * to acknowledge). The market's own client finishes with a full page
172
+ * `location.reload()` - the same safe mechanism Desktop's Client half uses
173
+ * (a renderer/webContent reload, not a process restart); Web's `location` IS
174
+ * the browser tab, so this is the exact same operation for both surfaces,
175
+ * not something this file needs to build separately.
176
+ */
177
+ export class WebLiveActivationService extends Service {
178
+ constructor(ctx: Context, private readonly controller: AcrPluginLifecycleController) {
179
+ super(ctx, 'livePluginActivation')
180
+ }
181
+
182
+ async activate(packageName: string): Promise<void> {
183
+ await this.controller.activate(packageName)
184
+ }
185
+
186
+ async deactivate(packageName: string): Promise<void> {
187
+ await this.controller.deactivate(packageName)
188
+ }
189
+
190
+ requireModules(owner: string, modules: readonly string[]): Promise<void> {
191
+ return this.controller.requireModules(owner, modules)
192
+ }
193
+
194
+ setEnabled(packageName: string, enabled: boolean): Promise<boolean> {
195
+ return this.controller.setEnabledByPackageName(packageName, enabled)
196
+ }
197
+
198
+ statusOf(packageName: string): 'active' | 'disabled' | undefined {
199
+ return this.controller.statusOfPackage(packageName)
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Mount the shared plugin lifecycle for Web (not yet done anywhere in this
205
+ * surface before this file) and provide the market-shaped view over it,
206
+ * plus live activation so a Market install/uninstall takes effect without a
207
+ * server-process restart.
208
+ * @param ctx - the host root (matching `provideWebMarketInstall`'s own timing/scope).
209
+ * @param options - the same options shape the CLI's own `plugin-command.ts` already builds.
210
+ */
211
+ export function provideWebMarketPlugins(ctx: Context, options: DshPluginLifecycleOptions): void {
212
+ const lifecycle = mountAcrylPluginLifecycle(ctx, options)
213
+ ctx.plugin(WebPluginsService, { controller: lifecycle.controller, profileName: options.profileName })
214
+ ctx.plugin(WebLiveActivationService, lifecycle.controller)
215
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Finding and applying the Web port of an app. Which port an app starts from is part of its instance family (`instance/`, which also reads
3
+ * `ACRYL_WEB_PORT`); this module only scans for a free loopback port from there and turns it into the web server's Loader patch.
4
+ *
5
+ * @module @acryldev/harness-runtime/web-port
6
+ */
7
+
8
+ import { createServer } from 'node:net'
9
+ import { isRestrictedPort } from '@acryldev/blends/cordis/node-server'
10
+ import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
11
+
12
+ const HOST = '127.0.0.1'
13
+
14
+ /** The Loader patch that moves the web server to `port`, on `host` (loopback unless the instance's web access says otherwise). */
15
+ export function webPortPatch(port: number, host: string = HOST): PatchOptions {
16
+ return { id: 'webserver', config: { host, port } }
17
+ }
18
+
19
+ /** How many consecutive ports are tried before giving up. */
20
+ export const WEB_PORT_ATTEMPTS = 32
21
+
22
+ /** Can something listen on this port right now (on loopback, or on `host`)? A probe, so a race with another process is possible but narrow. */
23
+ export function loopbackPortIsFree(port: number, host: string = HOST): Promise<boolean> {
24
+ return new Promise(resolve => {
25
+ const server = createServer()
26
+ server.once('error', () => resolve(false))
27
+ server.listen({ host, port, exclusive: true }, () => server.close(() => resolve(true)))
28
+ })
29
+ }
30
+
31
+ /** The first free port at or after `start` that a browser may open (the Fetch standard's bad ports are skipped; an app's stable port is hashed into 3100..3999, which holds 3659). `probe` is injectable so the scan is testable without sockets. */
32
+ export async function findFreeWebPort(start: number, probe: (port: number) => Promise<boolean> = loopbackPortIsFree, attempts = WEB_PORT_ATTEMPTS): Promise<number> {
33
+ for (let offset = 0; offset < attempts; offset += 1) {
34
+ const port = start + offset
35
+ if (port > 65_535) break
36
+ if (!isRestrictedPort(port) && await probe(port)) return port
37
+ }
38
+ throw new Error(`no free web port from ${String(start)} to ${String(Math.min(start + attempts - 1, 65_535))}; set ACRYL_WEB_PORT to another starting port`)
39
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * The terminal's DeepSeek account sign-in (`account-callback` capability, research R44) through a real Loader: the rows
3
+ * the capability declares, the built `@acryldev/sign-in/account-callback`, a real loopback server, and a stand-in for DeepSeek's
4
+ * account service that uses `webServer` exactly as `dsh-deepseek-account-platform` does (`ctx.get('webServer')`, one exact
5
+ * `/oauth/callback` route per attempt). The server must be visible to the account row only.
6
+ */
7
+
8
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { request } from 'node:http'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import { Context, type FiberState } from '@deepseek-ai/cordis'
13
+ import { Loader } from '@deepseek-ai/cordis-plugin-loader'
14
+ import { ACCOUNT_SIGN_IN_SERVICE, type AccountSignInPort } from '@acryldev/control'
15
+ import { afterEach, describe, expect, it } from 'vitest'
16
+ import { CODING_CAPABILITY_COMPOSITIONS } from '@acryldev/coding-capabilities'
17
+
18
+ const ACTIVE = 2 as FiberState.ACTIVE
19
+
20
+ /** The rows exactly as the capability declares them: the callback row and the `deepseek-account` row's isolation. */
21
+ function declaredRows() {
22
+ const capability = CODING_CAPABILITY_COMPOSITIONS.find(candidate => candidate.id === 'account-callback')
23
+ if (capability === undefined) throw new Error('account-callback capability is not declared')
24
+ const [insertPatch, accountPatch] = capability.loaderPatches
25
+ const callback = insertPatch?.insert?.[0]
26
+ if (callback === undefined || accountPatch?.id !== 'deepseek-account') throw new Error('unexpected account-callback patches')
27
+ return { callback, accountIsolate: accountPatch.isolate as Record<string, string> }
28
+ }
29
+
30
+ /** DeepSeek's account service, reduced to how it uses `webServer` and what `AccountSignIn` reads. */
31
+ const FAKE_ACCOUNT = `
32
+ export const name = 'fake-deepseek-account'
33
+ export function apply(ctx) {
34
+ let view = { status: 'signed-out', attempt: null }
35
+ const listeners = new Set()
36
+ const set = (attempt) => { view = { ...view, attempt }; for (const listener of listeners) listener() }
37
+ let count = 0
38
+ ctx.reflect.provide('deepseekAccount', {
39
+ async getState() { return view },
40
+ async startSignIn(client, origin, loginSource) {
41
+ const web = ctx.get('webServer')
42
+ if (web === undefined) throw new Error('protocol')
43
+ const id = 'attempt-' + String(++count)
44
+ const dispose = web.register({ kind: 'exact', path: '/oauth/callback', handler: (req, res) => {
45
+ const url = new URL(req.url, 'http://127.0.0.1')
46
+ if (url.searchParams.get('state') !== id) { res.writeHead(400).end(); return }
47
+ res.writeHead(204).end()
48
+ dispose()
49
+ set({ id, phase: 'succeeded' })
50
+ } })
51
+ set({ id, phase: 'waiting-browser', authorizeUrl: origin + '/oauth/callback?code=c&state=' + id + '&source=' + loginSource })
52
+ return view
53
+ },
54
+ async cancelSignIn(id) { if (view.attempt?.id === id) set({ id, phase: 'cancelled' }); return view },
55
+ async *watch(signal) {
56
+ let dirty = true
57
+ let wake
58
+ const changed = () => { dirty = true; wake?.() }
59
+ listeners.add(changed)
60
+ signal.addEventListener('abort', changed, { once: true })
61
+ try {
62
+ while (!signal.aborted) {
63
+ if (dirty) { dirty = false; yield view; continue }
64
+ await new Promise(resolve => { wake = resolve })
65
+ }
66
+ } finally { listeners.delete(changed) }
67
+ },
68
+ })
69
+ }
70
+ `
71
+
72
+ /** A row that is not in the realm: it must not see the callback server. */
73
+ const NEIGHBOR = `
74
+ export const name = 'neighbor'
75
+ export function apply(ctx) { ctx.reflect.provide('neighborProbe', { seesWebServer: () => ctx.get('webServer') !== undefined }) }
76
+ `
77
+
78
+ const roots: string[] = []
79
+ afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
80
+
81
+ async function mount() {
82
+ const root = mkdtempSync(join(tmpdir(), 'acryl-account-callback-'))
83
+ roots.push(root)
84
+ writeFileSync(join(root, 'callback.mjs'), `export * from ${JSON.stringify(import.meta.resolve('@acryldev/sign-in/account-callback'))}\n`)
85
+ writeFileSync(join(root, 'account.mjs'), FAKE_ACCOUNT)
86
+ writeFileSync(join(root, 'neighbor.mjs'), NEIGHBOR)
87
+ const { callback, accountIsolate } = declaredRows()
88
+ const ctx = new Context()
89
+ await ctx.plugin(Loader, { baseUrl: `file://${root}/` })
90
+ const accountId = await ctx.loader.create({ id: 'deepseek-account', name: './account.mjs', isolate: accountIsolate })
91
+ const callbackId = await ctx.loader.create({ ...callback, name: './callback.mjs' })
92
+ await ctx.loader.create({ id: 'neighbor', name: './neighbor.mjs' })
93
+ await ctx.loader.await()
94
+ const signIn = (): AccountSignInPort => {
95
+ const port = ctx.get(ACCOUNT_SIGN_IN_SERVICE) as AccountSignInPort | undefined
96
+ if (port === undefined) throw new Error('acrylAccountSignIn is not provided')
97
+ return port
98
+ }
99
+ const state = (id: string) => [...ctx.loader.entries()].find(entry => entry.id === id)?.fiber?.state
100
+ return { ctx, signIn, state, accountId, callbackId }
101
+ }
102
+
103
+ describe('account-callback through a real Loader', () => {
104
+ it('signs in: the account row registers its callback, the browser reaches it over loopback HTTP, the sign-in settles', async () => {
105
+ const { signIn, state, accountId, callbackId } = await mount()
106
+ expect(state(accountId)).toBe(ACTIVE)
107
+ expect(state(callbackId)).toBe(ACTIVE)
108
+ const opened: string[] = []
109
+ const outcome = await signIn().signIn({
110
+ notify(url) {
111
+ opened.push(url)
112
+ void fetch(url)
113
+ },
114
+ })
115
+ expect(outcome).toEqual({ status: 'authorized' })
116
+ expect(opened).toHaveLength(1)
117
+ expect(opened[0]).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback\?code=c&state=attempt-1&source=desktop$/)
118
+ })
119
+
120
+ it('serves the callback server to the account row only: a sibling row and the root see no webServer', async () => {
121
+ const { ctx } = await mount()
122
+ const probe = ctx.get('neighborProbe' as never) as { seesWebServer(): boolean }
123
+ expect(probe.seesWebServer()).toBe(false)
124
+ expect(ctx.get('webServer')).toBeUndefined()
125
+ })
126
+
127
+ it('answers 404 for any other path and refuses a request for another host name', async () => {
128
+ const { signIn } = await mount()
129
+ let origin = ''
130
+ const running = signIn().signIn({ notify(url) { origin = new URL(url).origin } })
131
+ await until(() => origin !== '')
132
+ expect((await fetch(`${origin}/v1/chat/completions`)).status).toBe(404)
133
+ // A DNS-rebound name pointing at the port (fetch drops a Host header, so a plain request).
134
+ expect(await statusFor(`${origin}/oauth/callback?code=c&state=attempt-1`, `rebound.example:${new URL(origin).port}`)).toBe(421)
135
+ await fetch(`${origin}/oauth/callback?code=c&state=attempt-1`)
136
+ expect(await running).toEqual({ status: 'authorized' })
137
+ })
138
+
139
+ it('cancels the attempt when the caller aborts', async () => {
140
+ const { signIn } = await mount()
141
+ const abort = new AbortController()
142
+ const outcome = signIn().signIn({ signal: abort.signal, notify() { abort.abort() } })
143
+ expect(await outcome).toEqual({ status: 'cancelled' })
144
+ })
145
+
146
+ it('closes the port and withdraws its services when the row unloads', async () => {
147
+ const { ctx, signIn, callbackId } = await mount()
148
+ let origin = ''
149
+ const abort = new AbortController()
150
+ const running = signIn().signIn({ signal: abort.signal, notify(url) { origin = new URL(url).origin } })
151
+ await until(() => origin !== '')
152
+ abort.abort()
153
+ await running
154
+ await ctx.loader.remove(callbackId)
155
+ await ctx.loader.await()
156
+ expect(ctx.get(ACCOUNT_SIGN_IN_SERVICE)).toBeUndefined()
157
+ await expect(fetch(`${origin}/oauth/callback`)).rejects.toThrow()
158
+ })
159
+ })
160
+
161
+ function statusFor(url: string, host: string): Promise<number | undefined> {
162
+ return new Promise((resolve, reject) => {
163
+ request(url, { headers: { host } }, (res) => { res.resume(); resolve(res.statusCode) }).on('error', reject).end()
164
+ })
165
+ }
166
+
167
+ async function until(check: () => boolean): Promise<void> {
168
+ for (let i = 0; i < 300; i += 1) {
169
+ if (check()) return
170
+ await new Promise(resolve => { setTimeout(resolve, 10) })
171
+ }
172
+ throw new Error('timed out')
173
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `ACRYL_HOME` / `DSH_HOME` precedence for ACRYL's roots.
3
+ *
4
+ * `ACRYL_HOME` is the product root and engines nest beneath it, so an explicit
5
+ * `ACRYL_HOME` must outrank an ambient `DSH_HOME` (commonly exported in a
6
+ * developer shell, and set by the DSH Desktop app). When it did not, pinning
7
+ * ACRYL's root silently kept using the real `~/.dsh`.
8
+ */
9
+ import { homedir } from 'node:os'
10
+ import { join, resolve } from 'node:path'
11
+ import { describe, expect, it } from 'vitest'
12
+ import { resolveAcrylDshHome, resolveAcrylHome } from '../src/acryl-home.ts'
13
+
14
+ describe('resolveAcrylHome', () => {
15
+ it('uses ACRYL_HOME when set', () => {
16
+ expect(resolveAcrylHome({ ACRYL_HOME: '/tmp/acryl-root' })).toBe(resolve('/tmp/acryl-root'))
17
+ })
18
+
19
+ it('defaults to ~/.acryl, ignoring a blank value', () => {
20
+ expect(resolveAcrylHome({})).toBe(join(homedir(), '.acryl'))
21
+ expect(resolveAcrylHome({ ACRYL_HOME: ' ' })).toBe(join(homedir(), '.acryl'))
22
+ })
23
+ })
24
+
25
+ describe('resolveAcrylDshHome precedence', () => {
26
+ it('nests under ACRYL_HOME even when DSH_HOME is exported', () => {
27
+ expect(resolveAcrylDshHome({ ACRYL_HOME: '/tmp/acryl-root', DSH_HOME: '/tmp/ambient' }))
28
+ .toBe(join(resolve('/tmp/acryl-root'), '.dsh'))
29
+ })
30
+
31
+ it('honors DSH_HOME when ACRYL_HOME is unset', () => {
32
+ expect(resolveAcrylDshHome({ DSH_HOME: '/tmp/explicit-dsh' })).toBe(resolve('/tmp/explicit-dsh'))
33
+ })
34
+
35
+ it('defaults to ~/.acryl/.dsh when neither is set', () => {
36
+ expect(resolveAcrylDshHome({})).toBe(join(homedir(), '.acryl', '.dsh'))
37
+ expect(resolveAcrylDshHome({ DSH_HOME: ' ' })).toBe(join(homedir(), '.acryl', '.dsh'))
38
+ })
39
+ })
@@ -0,0 +1,101 @@
1
+ /**
2
+ * T044 (spec 001), the part that needs no model: an agent extends ACRYL through the tools it is given. The tools are executed through
3
+ * the real registry (`tools.execute`, the path an agent's call takes, policy hooks included) on the real web engine: verify a plugin it
4
+ * wrote, install it live, call what it added, edit it and update it live, see it listed, remove it. What an agent decides to write
5
+ * is the model's part and waits for a key (see R30).
6
+ */
7
+ import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { mkdtemp, rm } from 'node:fs/promises'
9
+ import { tmpdir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
12
+ import { afterEach, describe, expect, it } from 'vitest'
13
+ import { createWebEngineDefinition } from '../src/engine-dsh.ts'
14
+ import { createAcrylEngineHost } from '../src/engine-host.ts'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { codingCapabilities } from '@acryldev/coding-capabilities'
17
+
18
+ const example = fileURLToPath(new URL('../../../plugins/plugin-context/example-plugins/packages/tool-basic/', import.meta.url))
19
+ const initialDshHome = process.env.DSH_HOME
20
+ const folders: string[] = []
21
+
22
+ afterEach(async () => {
23
+ if (initialDshHome === undefined) delete process.env.DSH_HOME
24
+ else process.env.DSH_HOME = initialDshHome
25
+ await Promise.all(folders.splice(0).map(folder => rm(folder, { force: true, recursive: true })))
26
+ })
27
+
28
+ type ToolResult = Record<string, unknown>
29
+ interface Tools { execute(input: { callId: string, name: string, arguments: unknown, signal: AbortSignal }): Promise<ToolResult> }
30
+
31
+ /** The package an agent would write: a model-callable tool whose answer carries `version`. */
32
+ function authorPlugin(version: string): string {
33
+ const dir = mkdtempSync(join(tmpdir(), 'acryl-authored-'))
34
+ folders.push(dir)
35
+ cpSync(example, dir, { recursive: true })
36
+ const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as Record<string, unknown>
37
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ ...manifest, name: 'acryl-authored-probe', version: '0.1.0' }, null, 2))
38
+ writeFileSync(join(dir, 'cordis.patch.yml'), readFileSync(join(dir, 'cordis.patch.yml'), 'utf8').replaceAll('acryl-example-tool', 'acryl-authored-probe').replaceAll('example-tool', 'authored-probe'))
39
+ editPlugin(dir, version)
40
+ return dir
41
+ }
42
+
43
+ function editPlugin(dir: string, version: string): void {
44
+ const source = readFileSync(example + 'index.js', 'utf8')
45
+ .replace("'acryl-example-tool'", "'acryl-authored-probe'")
46
+ .replace("name: 'example_echo'", "name: 'authored_probe'")
47
+ .replace('return args.message.toUpperCase()', `return 'probe ${version}: ' + args.message.toUpperCase()`)
48
+ writeFileSync(join(dir, 'index.js'), source)
49
+ }
50
+
51
+ describe('an agent extends ACRYL through its tools (no model)', () => {
52
+ it('verifies, installs, updates and removes a plugin it wrote, live, on the web engine', async () => {
53
+ const home = await mkdtemp(join(tmpdir(), 'acryl-self-hosting-'))
54
+ folders.push(home)
55
+ process.env.DSH_HOME = home
56
+ const host = await createAcrylEngineHost({
57
+ engines: [createWebEngineDefinition(new URL('../package.json', import.meta.url).href, codingCapabilities)],
58
+ initialEngine: 'dsh',
59
+ prepare: hostCtx => { provideCmdline(hostCtx, { args: ['--no-open', '--port', '0'], exit: () => {} }) },
60
+ })
61
+ const tools = host.ctx.get('tools' as never) as unknown as Tools
62
+ let call = 0
63
+ const run = async (name: string, args: unknown): Promise<string> => JSON.stringify(await tools.execute({ callId: `c${String(++call)}`, name, arguments: args, signal: new AbortController().signal }))
64
+ try {
65
+ const dir = authorPlugin('v1')
66
+
67
+ const verified = await run('acryl_verify_plugin', { path: dir })
68
+ expect(verified).not.toMatch(/"isError":\s*true/)
69
+
70
+ const installed = await run('acryl_install_plugin', { path: dir })
71
+ expect(installed).not.toMatch(/"isError":\s*true/)
72
+ expect(await run('authored_probe', { message: 'hi' })).toContain('probe v1: HI')
73
+ expect(await run('acryl_list_plugins', {})).toContain('acryl-authored-probe')
74
+
75
+ // The agent edits its own plugin and installs again: an update, live, no restart.
76
+ editPlugin(dir, 'v2')
77
+ expect(await run('acryl_install_plugin', { path: dir })).not.toMatch(/"isError":\s*true/)
78
+ expect(await run('authored_probe', { message: 'hi' })).toContain('probe v2: HI')
79
+
80
+ // An update that fails to activate is refused with the exact error, and the version that was running is brought back (T050): the agent
81
+ // does not lose a working plugin because its next edit was wrong.
82
+ writeFileSync(join(dir, 'index.js'), 'export const name = "acryl-authored-probe"\nexport function apply() { throw new Error("authored on purpose") }\n')
83
+ const refused = await run('acryl_install_plugin', { path: dir })
84
+ expect(refused).toContain('authored on purpose')
85
+ expect(refused).toContain('restoredPrevious')
86
+ expect(refused).toMatch(/restoredPrevious\\?":\s*true/u)
87
+ expect(await run('authored_probe', { message: 'hi' })).toContain('probe v2: HI')
88
+ expect(await run('acryl_list_plugins', {})).toContain('acryl-authored-probe')
89
+
90
+ // The agent fixes it and installs again, then removes it live.
91
+ editPlugin(dir, 'v3')
92
+ expect(await run('acryl_install_plugin', { path: dir })).not.toMatch(/"isError":\s*true/)
93
+ expect(await run('authored_probe', { message: 'hi' })).toContain('probe v3: HI')
94
+ expect(await run('acryl_remove_plugin', { package: 'acryl-authored-probe' })).not.toMatch(/"isError":\s*true/)
95
+ expect(await run('authored_probe', { message: 'hi' })).toContain('unknown tool')
96
+ expect(await run('acryl_list_plugins', {})).not.toContain('acryl-authored-probe')
97
+ } finally {
98
+ await host.dispose()
99
+ }
100
+ }, 240_000)
101
+ })
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A composition root announces the app it serves (spec 048 T011): the process that serves takes the app's run lock and writes the Registry entry with the
3
+ * port it really bound, so `acryl control list` finds an app started by `pnpm web`, Desktop or the CLI. It withdraws both when it exits, refuses a second
4
+ * live app on the same instance, and takes over a claim whose process is gone.
5
+ */
6
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { join } from 'node:path'
9
+ import { afterEach, describe, expect, it } from 'vitest'
10
+ import {
11
+ InstanceAnnounceError,
12
+ announceSelf,
13
+ appFolder,
14
+ listRunning,
15
+ readLock,
16
+ } from '../src/instance/index.ts'
17
+
18
+ const dirs: string[] = []
19
+ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { force: true, recursive: true }) })
20
+ const temp = (): string => { const dir = realpathSync(mkdtempSync(join(tmpdir(), 'acryl-announce-'))); dirs.push(dir); return dir }
21
+ /** An app folder (`bin/acryl` runs one), so the instance is pinned to it and not to the OS home. */
22
+ const app = (root: string): string => { const dir = join(root, 'notes'); mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, 'blend.yaml'), 'x'); return dir }
23
+ const alive = (pids: number[]): ((pid: number) => boolean) => pid => pids.includes(pid)
24
+
25
+ describe('announceSelf', () => {
26
+ it('announces the app with the port it bound, and the listing shows it', () => {
27
+ const osHome = temp()
28
+ const instance = appFolder(app(temp()), osHome)
29
+ const announced = announceSelf(instance, { surface: 'web', port: 3107, pid: 4242, osHome })
30
+ expect(announced.id).toBe(instance.id)
31
+ expect(announced.port).toBe(3107)
32
+ const [entry] = listRunning(osHome, alive([4242]))
33
+ expect(entry).toMatchObject({ id: instance.id, home: instance.home, pid: 4242, surface: 'web', port: 3107 })
34
+ expect(readLock(instance.runLockFile)).toMatchObject({ pid: 4242, surface: 'web', port: 3107 })
35
+ })
36
+
37
+ it('withdraws the announcement and the claim on release, once', () => {
38
+ const osHome = temp()
39
+ const instance = appFolder(app(temp()), osHome)
40
+ const announced = announceSelf(instance, { surface: 'desktop', port: 3108, pid: 4243, osHome })
41
+ announced.release()
42
+ expect(listRunning(osHome, alive([4243]))).toEqual([])
43
+ expect(readLock(instance.runLockFile)).toBeUndefined()
44
+ announced.release()
45
+ expect(listRunning(osHome, alive([4243]))).toEqual([])
46
+ })
47
+
48
+ it('refuses a second live app on the same instance, naming the holder', () => {
49
+ const osHome = temp()
50
+ const instance = appFolder(app(temp()), osHome)
51
+ announceSelf(instance, { surface: 'web', port: 3107, pid: 4244, osHome })
52
+ let refused: unknown
53
+ try { announceSelf(instance, { surface: 'desktop', port: 3109, pid: 4245, osHome, alive: alive([4244]) }) } catch (error) { refused = error }
54
+ expect(refused).toBeInstanceOf(InstanceAnnounceError)
55
+ expect((refused as Error).message).toBe(`app "${instance.id}" is already running (pid 4244, web, port 3107). Stop it (node scripts/instances.mjs stop ${instance.id}) or start another app.`)
56
+ // The refused process changed neither the claim nor the announcement.
57
+ expect(readLock(instance.runLockFile)).toMatchObject({ pid: 4244, surface: 'web' })
58
+ expect(listRunning(osHome, alive([4244, 4245]))[0]).toMatchObject({ pid: 4244, port: 3107 })
59
+ })
60
+
61
+ it('takes over the claim of a process that is gone, and the older holder cannot take the newer claim down', () => {
62
+ const osHome = temp()
63
+ const instance = appFolder(app(temp()), osHome)
64
+ const older = announceSelf(instance, { surface: 'web', port: 3107, pid: 4246, osHome })
65
+ const newer = announceSelf(instance, { surface: 'web', port: 3110, pid: 4247, osHome, alive: alive([4247]) })
66
+ expect(listRunning(osHome, alive([4247]))[0]).toMatchObject({ pid: 4247, port: 3110 })
67
+ older.release()
68
+ expect(readLock(instance.runLockFile)).toMatchObject({ pid: 4247 })
69
+ expect(listRunning(osHome, alive([4247]))[0]).toMatchObject({ pid: 4247, port: 3110 })
70
+ newer.release()
71
+ expect(readLock(instance.runLockFile)).toBeUndefined()
72
+ expect(listRunning(osHome, alive([4247]))).toEqual([])
73
+ })
74
+
75
+ it('keeps its own claim when the same process announces again (an engine swap under one root)', () => {
76
+ const osHome = temp()
77
+ const instance = appFolder(app(temp()), osHome)
78
+ announceSelf(instance, { surface: 'web', port: 3107, pid: 4248, osHome })
79
+ const again = announceSelf(instance, { surface: 'web', port: 3112, pid: 4248, osHome })
80
+ expect(listRunning(osHome, alive([4248]))[0]).toMatchObject({ pid: 4248, port: 3112 })
81
+ again.release()
82
+ expect(readLock(instance.runLockFile)).toBeUndefined()
83
+ })
84
+ })