@wp-operations/wp-ops 0.3.0 → 0.3.1

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 (117) hide show
  1. package/package.json +6 -2
  2. package/src/commands/platform.js +16 -2
  3. package/src/main.js +9 -3
  4. package/wp-operations/CHANGELOG.md +14 -0
  5. package/wp-operations/README.md +39 -0
  6. package/wp-operations/agents/builder/AGENT.md +15 -0
  7. package/wp-operations/assets/admin.css +631 -0
  8. package/wp-operations/assets/admin.js +614 -0
  9. package/wp-operations/assets/app/app.css +1 -0
  10. package/wp-operations/assets/app/app.js +70 -0
  11. package/wp-operations/assets/app/fonts/inter-medium.woff +0 -0
  12. package/wp-operations/assets/app/fonts/inter-regular.woff +0 -0
  13. package/wp-operations/assets/app/fonts/inter-semibold.woff +0 -0
  14. package/wp-operations/assets/app/login.css +42 -0
  15. package/wp-operations/assets/brand/icon.svg +20 -0
  16. package/wp-operations/assets/brand/mark.svg +19 -0
  17. package/wp-operations/assets/editors/audiobook.css +311 -0
  18. package/wp-operations/assets/editors/audiofile.css +286 -0
  19. package/wp-operations/assets/editors/course.css +701 -0
  20. package/wp-operations/assets/editors/course.js +698 -0
  21. package/wp-operations/assets/editors/faq.css +258 -0
  22. package/wp-operations/assets/editors/faq.js +196 -0
  23. package/wp-operations/assets/editors/interactive.css +220 -0
  24. package/wp-operations/assets/editors/interactive.js +378 -0
  25. package/wp-operations/assets/editors/media-sources.css +3 -0
  26. package/wp-operations/assets/editors/media-sources.js +40 -0
  27. package/wp-operations/assets/editors/open-media.css +114 -0
  28. package/wp-operations/assets/editors/open-media.js +182 -0
  29. package/wp-operations/assets/editors/thumbnails.css +335 -0
  30. package/wp-operations/assets/editors/thumbnails.js +447 -0
  31. package/wp-operations/assets/editors/translator.css +818 -0
  32. package/wp-operations/functions.php +24 -0
  33. package/wp-operations/index.php +14 -0
  34. package/wp-operations/platform.json +1836 -0
  35. package/wp-operations/skills/ai-development-guardrails/SKILL.md +49 -0
  36. package/wp-operations/skills/gutenberg-reference/SKILL.md +45 -0
  37. package/wp-operations/skills/js-tooling-for-themes/SKILL.md +51 -0
  38. package/wp-operations/skills/tailwind-for-wp/SKILL.md +62 -0
  39. package/wp-operations/skills/wp-clean-classic-themes/SKILL.md +112 -0
  40. package/wp-operations/skills/wp-psr4-plugins/SKILL.md +2043 -0
  41. package/wp-operations/skills/wp-security/SKILL.md +90 -0
  42. package/wp-operations/src/Admin.php +78 -0
  43. package/wp-operations/src/App/Access.php +57 -0
  44. package/wp-operations/src/App/Admin.php +442 -0
  45. package/wp-operations/src/App/App.php +157 -0
  46. package/wp-operations/src/App/Apps.php +379 -0
  47. package/wp-operations/src/App/Bundle.php +111 -0
  48. package/wp-operations/src/App/Contents.php +676 -0
  49. package/wp-operations/src/App/Engine.php +554 -0
  50. package/wp-operations/src/App/Github.php +308 -0
  51. package/wp-operations/src/App/Module.php +23 -0
  52. package/wp-operations/src/App/Ops.php +470 -0
  53. package/wp-operations/src/App/Packages.php +289 -0
  54. package/wp-operations/src/App/Rest.php +539 -0
  55. package/wp-operations/src/App/Sandboxes.php +206 -0
  56. package/wp-operations/src/App/Store.php +104 -0
  57. package/wp-operations/src/App/Usage.php +268 -0
  58. package/wp-operations/src/Config.php +249 -0
  59. package/wp-operations/src/Content/Editor.php +223 -0
  60. package/wp-operations/src/Content/Fields.php +681 -0
  61. package/wp-operations/src/Content/Scoring.php +253 -0
  62. package/wp-operations/src/Content/Structure.php +293 -0
  63. package/wp-operations/src/Content/Types.php +150 -0
  64. package/wp-operations/src/Content/Uploads.php +50 -0
  65. package/wp-operations/src/Editors/AudiobookAuthor.php +61 -0
  66. package/wp-operations/src/Editors/AudiobookChapters.php +632 -0
  67. package/wp-operations/src/Editors/AudiobookCover.php +235 -0
  68. package/wp-operations/src/Editors/Audiofile.php +462 -0
  69. package/wp-operations/src/Editors/Course.php +784 -0
  70. package/wp-operations/src/Editors/Ebook.php +242 -0
  71. package/wp-operations/src/Editors/Editors.php +44 -0
  72. package/wp-operations/src/Editors/Faq.php +237 -0
  73. package/wp-operations/src/Editors/Files.php +139 -0
  74. package/wp-operations/src/Editors/Interactive/Builder.php +103 -0
  75. package/wp-operations/src/Editors/Interactive/Card.php +76 -0
  76. package/wp-operations/src/Editors/Interactive/Editor.php +42 -0
  77. package/wp-operations/src/Editors/Interactive/Field.php +272 -0
  78. package/wp-operations/src/Editors/Interactive/Map.php +84 -0
  79. package/wp-operations/src/Editors/Interactive/Models.php +227 -0
  80. package/wp-operations/src/Editors/Interactive/Report.php +59 -0
  81. package/wp-operations/src/Editors/Interactive/Save.php +323 -0
  82. package/wp-operations/src/Editors/Interactive/Scoring.php +244 -0
  83. package/wp-operations/src/Editors/Interactive/Structure.php +195 -0
  84. package/wp-operations/src/Editors/Legal.php +235 -0
  85. package/wp-operations/src/Editors/OpenMedia.php +140 -0
  86. package/wp-operations/src/Editors/OriginalTitle.php +112 -0
  87. package/wp-operations/src/Editors/Sources.php +28 -0
  88. package/wp-operations/src/Editors/Thumbnails/Admin.php +306 -0
  89. package/wp-operations/src/Editors/Thumbnails/Ajax.php +163 -0
  90. package/wp-operations/src/Editors/Thumbnails/Box.php +188 -0
  91. package/wp-operations/src/Editors/Thumbnails/Storage.php +228 -0
  92. package/wp-operations/src/Editors/Translator/Admin.php +913 -0
  93. package/wp-operations/src/Editors/Translator/Api.php +63 -0
  94. package/wp-operations/src/Editors/Translator/Bar.php +83 -0
  95. package/wp-operations/src/Editors/Translator/Fields.php +273 -0
  96. package/wp-operations/src/Editors/Translator/Storage.php +131 -0
  97. package/wp-operations/src/Editors/Translator/Thumbnail.php +215 -0
  98. package/wp-operations/src/Identity.php +104 -0
  99. package/wp-operations/src/Languages.php +45 -0
  100. package/wp-operations/src/Lockdown.php +85 -0
  101. package/wp-operations/src/Modules/Apps/Admin.php +472 -0
  102. package/wp-operations/src/Modules/Apps/Api.php +193 -0
  103. package/wp-operations/src/Modules/Apps/Apps.php +279 -0
  104. package/wp-operations/src/Modules/Apps/Formatters.php +478 -0
  105. package/wp-operations/src/Modules/Apps/Schemes.php +248 -0
  106. package/wp-operations/src/Modules/Apps/Table.php +101 -0
  107. package/wp-operations/src/Modules/Thumbnails.php +68 -0
  108. package/wp-operations/src/Modules/Translations.php +133 -0
  109. package/wp-operations/src/Platform.php +59 -0
  110. package/wp-operations/src/Setup.php +273 -0
  111. package/wp-operations/src/Status.php +99 -0
  112. package/wp-operations/src/Storage/Client.php +168 -0
  113. package/wp-operations/src/Storage/Offload.php +120 -0
  114. package/wp-operations/src/Storage/Settings.php +166 -0
  115. package/wp-operations/src/Storage/Storage.php +35 -0
  116. package/wp-operations/src/Updates.php +151 -0
  117. package/wp-operations/style.css +11 -0
@@ -0,0 +1,554 @@
1
+ <?php
2
+ namespace Platform\App;
3
+
4
+ use Platform\Identity;
5
+ use Platform\Modules\Apps\Apps as Registry;
6
+
7
+ defined( 'ABSPATH' ) || exit;
8
+
9
+ final class Engine {
10
+
11
+ const OPTION = 'platform_engine';
12
+ const PAGE = 'ai-models';
13
+ const FORMATS = [ 'openai' => 'OpenAI-compatible (chat/completions)', 'anthropic' => 'Anthropic (messages)', 'images' => 'Images (OpenAI-compatible images/generations)' ];
14
+ const SIZES = [ '1:1' => '1024x1024', '16:9' => '1536x1024', '4:3' => '1536x1024', '2:3' => '1024x1536' ];
15
+ const MAX_FILES = 30;
16
+ const MAX_BYTES = 400000;
17
+ const BLOCKED = '#(^|/)(\.git|vendor|node_modules)(/|$)|^\.github/#';
18
+
19
+ public static function defaults(): array {
20
+ return [ 'providers' => [], 'default' => '', 'modes' => [], 'rules' => '', 'history' => 6, 'branch' => 'platform/{slug}' ];
21
+ }
22
+
23
+ public static function settings(): array {
24
+ $saved = (array) get_option( self::OPTION, [] );
25
+
26
+ return array_merge( self::defaults(), array_intersect_key( $saved, self::defaults() ) );
27
+ }
28
+
29
+ private static function provider( string $mode ): ?array {
30
+ $settings = self::settings();
31
+ $images = 'image' === $mode;
32
+ $providers = array_values( array_filter( (array) $settings['providers'], static fn( array $p ): bool => $images === ( 'images' === $p['format'] ) ) );
33
+ $key = (string) ( $settings['modes'][ $mode ] ?? '' ) ?: ( $images ? '' : $settings['default'] );
34
+
35
+ foreach ( $providers as $provider ) {
36
+ if ( $provider['key'] === $key ) {
37
+ return $provider;
38
+ }
39
+ }
40
+
41
+ return $providers[0] ?? null;
42
+ }
43
+
44
+ public static function image( string $prompt, string $ratio, string $title ) {
45
+ $provider = self::provider( 'image' );
46
+
47
+ if ( ! $provider ) {
48
+ return new \WP_Error( 'engine_unavailable', 'No image model is connected yet. Add one with the Images format in AI Models.', [ 'status' => 503 ] );
49
+ }
50
+
51
+ $key = self::secret( $provider );
52
+
53
+ if ( '' === $key ) {
54
+ return new \WP_Error( 'engine_unavailable', sprintf( 'The model "%s" has no API key. Add define( \'%s\', \'…\' ) to wp-config.php.', $provider['label'], $provider['key_constant'] ), [ 'status' => 503 ] );
55
+ }
56
+
57
+ $response = wp_remote_post(
58
+ untrailingslashit( $provider['base_url'] ) . '/images/generations',
59
+ [
60
+ 'timeout' => 180,
61
+ 'headers' => [ 'Authorization' => 'Bearer ' . $key, 'Content-Type' => 'application/json', 'User-Agent' => 'wp-operations' ],
62
+ 'body' => wp_json_encode( [ 'model' => $provider['model'], 'prompt' => $prompt, 'n' => 1, 'size' => self::SIZES[ $ratio ] ?? '1024x1024' ] ),
63
+ ]
64
+ );
65
+
66
+ if ( is_wp_error( $response ) ) {
67
+ return new \WP_Error( 'engine', sprintf( '%s could not be reached: %s', $provider['label'], $response->get_error_message() ), [ 'status' => 502 ] );
68
+ }
69
+
70
+ $code = (int) wp_remote_retrieve_response_code( $response );
71
+ $data = json_decode( (string) wp_remote_retrieve_body( $response ), true );
72
+
73
+ if ( $code >= 400 || ! is_array( $data ) ) {
74
+ return new \WP_Error( 'engine', sprintf( '%s returned %d%s', $provider['label'], $code, is_array( $data ) && ! empty( $data['error']['message'] ) ? ': ' . $data['error']['message'] : '.' ), [ 'status' => 502 ] );
75
+ }
76
+
77
+ $item = (array) ( $data['data'][0] ?? [] );
78
+ $bytes = '';
79
+
80
+ if ( ! empty( $item['b64_json'] ) ) {
81
+ $bytes = (string) base64_decode( (string) $item['b64_json'] );
82
+ } elseif ( ! empty( $item['url'] ) ) {
83
+ $file = wp_remote_get( esc_url_raw( (string) $item['url'] ), [ 'timeout' => 60 ] );
84
+ $bytes = is_wp_error( $file ) ? '' : (string) wp_remote_retrieve_body( $file );
85
+ }
86
+
87
+ if ( '' === $bytes ) {
88
+ return new \WP_Error( 'engine', sprintf( '%s returned no image.', $provider['label'] ), [ 'status' => 502 ] );
89
+ }
90
+
91
+ $type = function_exists( 'getimagesizefromstring' ) ? (string) ( getimagesizefromstring( $bytes )['mime'] ?? 'image/png' ) : 'image/png';
92
+ $ext = 'image/jpeg' === $type ? 'jpg' : ( 'image/webp' === $type ? 'webp' : 'png' );
93
+ $name = sanitize_file_name( ( $title ?: 'thumbnail' ) . '-' . wp_generate_password( 6, false ) . '.' . $ext );
94
+ $bits = wp_upload_bits( $name, null, $bytes );
95
+
96
+ if ( ! empty( $bits['error'] ) ) {
97
+ return new \WP_Error( 'upload', (string) $bits['error'], [ 'status' => 500 ] );
98
+ }
99
+
100
+ require_once ABSPATH . 'wp-admin/includes/image.php';
101
+
102
+ $id = wp_insert_attachment( [ 'post_title' => $title ?: $name, 'post_mime_type' => $type, 'post_status' => 'inherit' ], $bits['file'] );
103
+
104
+ if ( is_wp_error( $id ) || ! $id ) {
105
+ return new \WP_Error( 'upload', 'The image could not be saved.', [ 'status' => 500 ] );
106
+ }
107
+
108
+ wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $bits['file'] ) );
109
+ update_post_meta( $id, '_platform_ai_prompt', $prompt );
110
+
111
+ return Contents::attachment( (int) $id );
112
+ }
113
+
114
+ public static function ready(): bool {
115
+ $provider = self::provider( 'build' );
116
+
117
+ return $provider && '' !== self::secret( $provider );
118
+ }
119
+
120
+ private static function secret( array $provider ): string {
121
+ $constant = (string) ( $provider['key_constant'] ?? '' );
122
+
123
+ return '' !== $constant && defined( $constant ) ? trim( (string) constant( $constant ) ) : '';
124
+ }
125
+
126
+ public static function unavailable(): string {
127
+ return (string) Module::config( 'engine.unavailable', 'No AI model is connected yet. An admin can add one in Settings → AI Models. Your prompt was saved.' );
128
+ }
129
+
130
+ public static function complete( string $mode, string $system, array $messages, ?array $provider = null ) {
131
+ $provider = $provider ?? self::provider( $mode );
132
+
133
+ if ( ! $provider ) {
134
+ return new \WP_Error( 'engine_unavailable', self::unavailable(), [ 'status' => 503 ] );
135
+ }
136
+
137
+ $key = self::secret( $provider );
138
+
139
+ if ( '' === $key ) {
140
+ return new \WP_Error( 'engine_unavailable', sprintf( 'The model "%s" has no API key. Add define( \'%s\', \'…\' ) to wp-config.php.', $provider['label'], $provider['key_constant'] ), [ 'status' => 503 ] );
141
+ }
142
+
143
+ $base = untrailingslashit( $provider['base_url'] );
144
+ $anthropic = 'anthropic' === $provider['format'];
145
+ $body = [
146
+ 'model' => $provider['model'],
147
+ 'max_tokens' => (int) $provider['max_tokens'],
148
+ 'temperature' => (float) $provider['temperature'],
149
+ ];
150
+
151
+ if ( $anthropic ) {
152
+ $body['system'] = $system;
153
+ $body['messages'] = $messages;
154
+ $url = $base . '/messages';
155
+ $headers = [ 'x-api-key' => $key, 'anthropic-version' => '2023-06-01' ];
156
+ } else {
157
+ $body['messages'] = array_merge( [ [ 'role' => 'system', 'content' => $system ] ], $messages );
158
+ $url = $base . '/chat/completions';
159
+ $headers = [ 'Authorization' => 'Bearer ' . $key ];
160
+ }
161
+
162
+ $response = wp_remote_post(
163
+ $url,
164
+ [
165
+ 'timeout' => (int) apply_filters( 'platform_engine_timeout', 120 ),
166
+ 'headers' => $headers + [ 'Content-Type' => 'application/json', 'User-Agent' => 'wp-operations' ],
167
+ 'body' => wp_json_encode( $body ),
168
+ ]
169
+ );
170
+
171
+ if ( is_wp_error( $response ) ) {
172
+ return new \WP_Error( 'engine', sprintf( '%s could not be reached: %s', $provider['label'], $response->get_error_message() ), [ 'status' => 502 ] );
173
+ }
174
+
175
+ $code = (int) wp_remote_retrieve_response_code( $response );
176
+ $data = json_decode( (string) wp_remote_retrieve_body( $response ), true );
177
+
178
+ if ( $code >= 400 || ! is_array( $data ) ) {
179
+ $message = is_array( $data ) ? (string) ( $data['error']['message'] ?? $data['message'] ?? '' ) : '';
180
+
181
+ return new \WP_Error( 'engine', sprintf( '%s returned %d%s', $provider['label'], $code, '' === $message ? '.' : ': ' . $message ), [ 'status' => 502 ] );
182
+ }
183
+
184
+ if ( $anthropic ) {
185
+ $text = implode( '', array_map( static fn( $part ): string => is_array( $part ) && 'text' === ( $part['type'] ?? '' ) ? (string) $part['text'] : '', (array) ( $data['content'] ?? [] ) ) );
186
+ $in = (int) ( $data['usage']['input_tokens'] ?? 0 );
187
+ $out = (int) ( $data['usage']['output_tokens'] ?? 0 );
188
+ $stop = (string) ( $data['stop_reason'] ?? '' );
189
+ } else {
190
+ $text = (string) ( $data['choices'][0]['message']['content'] ?? '' );
191
+ $in = (int) ( $data['usage']['prompt_tokens'] ?? 0 );
192
+ $out = (int) ( $data['usage']['completion_tokens'] ?? 0 );
193
+ $stop = (string) ( $data['choices'][0]['finish_reason'] ?? '' );
194
+ }
195
+
196
+ if ( in_array( $stop, [ 'length', 'max_tokens' ], true ) ) {
197
+ return new \WP_Error( 'engine_truncated', 'The answer was cut off by the model token limit, so it was discarded. Ask for a smaller change or raise Max tokens in Settings → AI Models.', [ 'status' => 502, 'tokens_in' => $in, 'tokens_out' => $out ] );
198
+ }
199
+
200
+ return [ 'text' => trim( $text ), 'tokens_in' => $in, 'tokens_out' => $out, 'model' => $provider['model'] ];
201
+ }
202
+
203
+ private static function rules(): string {
204
+ $extra = trim( (string) self::settings()['rules'] );
205
+
206
+ return implode(
207
+ "\n",
208
+ [
209
+ 'Rules you must follow without exception:',
210
+ '1. Do exactly what the person asked and nothing more. No extra features, files, refactors, renames or "improvements" they did not request.',
211
+ '2. Never invent file contents, functions, hooks, APIs, packages, options or paths. Use only what is shown below or what is standard WordPress/PHP/JS.',
212
+ '3. If you need a file you have not been shown, do not guess it: list its path in "needs" and change nothing.',
213
+ '4. If the request is ambiguous, ask in "questions" and change nothing.',
214
+ '5. You cannot run commands, install, deploy, push or publish. You only propose; a person reviews every change before it is committed.',
215
+ '6. Stay inside this app folder. Never touch vendor/, node_modules/, .git/ or .github/.',
216
+ '7. Say "I don\'t know" instead of guessing.',
217
+ '' === $extra ? '' : "\nPlatform rules:\n" . $extra,
218
+ ]
219
+ );
220
+ }
221
+
222
+ public static function knowledge( int $app_id, string $role, string $prompt ): string {
223
+ $text = strtolower( $prompt );
224
+ $matches = static fn( array $item ): bool => ! empty( $item['enabled'] ?? true ) && ( empty( $item['apps'] ) || in_array( (string) $app_id, array_map( 'strval', (array) $item['apps'] ), true ) );
225
+ $skills = array_column( Store::all( 'skills' ), null, 'id' );
226
+ $parts = [];
227
+ $used = [];
228
+
229
+ foreach ( Store::all( 'agents' ) as $agent ) {
230
+ if ( ( $agent['role'] ?? 'builder' ) !== $role || ! $matches( $agent ) ) {
231
+ continue;
232
+ }
233
+
234
+ $parts[] = sprintf( "Agent \"%s\":\n%s", (string) ( $agent['name'] ?? '' ), wp_strip_all_tags( (string) ( $agent['instructions'] ?? '' ) ) );
235
+
236
+ foreach ( (array) ( $agent['skills'] ?? [] ) as $skill ) {
237
+ $used[ (string) $skill ] = true;
238
+ }
239
+ }
240
+
241
+ foreach ( $skills as $id => $skill ) {
242
+ $trigger = strtolower( trim( (string) ( $skill['trigger'] ?? '' ) ) );
243
+
244
+ if ( $matches( $skill ) && ( isset( $used[ $id ] ) || ( '' !== $trigger && false !== strpos( $text, $trigger ) ) ) ) {
245
+ $parts[] = sprintf( "Skill \"%s\":\n%s", (string) ( $skill['name'] ?? '' ), wp_strip_all_tags( (string) ( $skill['instructions'] ?? '' ) ) );
246
+ }
247
+ }
248
+
249
+ foreach ( Store::all( 'docs' ) as $doc ) {
250
+ $title = strtolower( trim( (string) ( $doc['title'] ?? '' ) ) );
251
+
252
+ if ( '' !== $title && false !== strpos( $text, $title ) ) {
253
+ $parts[] = sprintf( "Doc \"%s\":\n%s", (string) $doc['title'], wp_strip_all_tags( (string) ( $doc['body'] ?? '' ) ) );
254
+ }
255
+ }
256
+
257
+ return $parts ? "Instructions from this platform's agents, skills and docs (the rules above still come first):\n\n" . implode( "\n\n", $parts ) : '';
258
+ }
259
+
260
+ private static function context( array $app, array $tree, array $files ): string {
261
+ $mapping = Ops::mapping( (int) $app['id'], (string) $app['name'] );
262
+ $lines = [
263
+ sprintf( 'Platform: %s. Apps are WordPress themes kept in the platform repository and deployed into full WordPress sites by GitHub Actions. PSR-4 plugins live in %s/ and are required by apps through composer path repositories. Content comes from the platform CMS API.', Identity::brand()['name'], Ops::settings()['packages'] ),
264
+ sprintf( 'App: %s. Folder: %s (%s). Languages: %s. Content types: %s.', $app['name'], $mapping['path'] ?: 'not mapped', $mapping['label'], implode( ', ', (array) $app['languages'] ) ?: 'default', implode( ', ', array_keys( array_diff_key( (array) $app['contents'], [ 'thumbnail_group_id' => 1 ] ) ) ) ?: 'none' ),
265
+ ];
266
+
267
+ if ( $tree ) {
268
+ $lines[] = "Files in the app folder (paths relative to it):\n" . implode( "\n", array_slice( $tree, 0, 400 ) ) . ( count( $tree ) > 400 ? "\n… " . ( count( $tree ) - 400 ) . ' more' : '' );
269
+ } else {
270
+ $lines[] = 'The app folder could not be listed (repository not connected or empty).';
271
+ }
272
+
273
+ foreach ( $files as $path => $content ) {
274
+ $lines[] = sprintf( "File %s:\n```\n%s\n```", $path, $content );
275
+ }
276
+
277
+ return implode( "\n\n", $lines );
278
+ }
279
+
280
+ private static function format( string $mode ): string {
281
+ if ( 'build' === $mode ) {
282
+ return 'Answer with one JSON object and nothing else, in this shape: {"summary": "what you changed and why, in plain words", "changes": [{"path": "relative/path.php", "action": "write" | "delete", "content": "the complete new file content for write"}], "needs": ["paths you must read first"], "questions": ["questions for the person"]}. "content" must be the whole file, never a fragment or a placeholder. When "needs" or "questions" is not empty, "changes" must be empty.';
283
+ }
284
+
285
+ if ( 'plan' === $mode ) {
286
+ return 'Do not write code. Answer with a short numbered plan: the steps, the files each step touches (existing or new), and anything you need to know first.';
287
+ }
288
+
289
+ return 'Answer the question in plain words. Do not propose code changes unless asked; use short code snippets only to explain.';
290
+ }
291
+
292
+ private static function files( int $app_id, array $tree, string $prompt, array $wanted ): array {
293
+ $files = [];
294
+
295
+ foreach ( $tree as $path ) {
296
+ if ( in_array( $path, $wanted, true ) || false !== strpos( $prompt, $path ) ) {
297
+ $file = Ops::file( $app_id, $path );
298
+
299
+ if ( ! is_wp_error( $file ) && ! $file['binary'] && strlen( $file['content'] ) <= 120000 ) {
300
+ $files[ $path ] = $file['content'];
301
+ }
302
+ }
303
+
304
+ if ( count( $files ) >= 12 ) {
305
+ break;
306
+ }
307
+ }
308
+
309
+ return $files;
310
+ }
311
+
312
+ public static function chat( int $app_id, string $mode, string $prompt, array $attachments, array $wanted ) {
313
+ $app = Registry::get( $app_id );
314
+
315
+ if ( ! $app ) {
316
+ return new \WP_Error( 'not_found', 'App not found.', [ 'status' => 404 ] );
317
+ }
318
+
319
+ $mode = in_array( $mode, [ 'build', 'plan', 'chat' ], true ) ? $mode : 'build';
320
+ $listing = Ops::tree( $app_id );
321
+ $tree = is_wp_error( $listing ) ? [] : array_column( (array) $listing['files'], 'path' );
322
+ $files = self::files( $app_id, $tree, $prompt, array_map( 'strval', $wanted ) );
323
+ $system = "You are the coding agent of the wp-operations platform.\n\n" . self::rules() . "\n\n" . self::knowledge( $app_id, 'builder', $prompt ) . "\n\n" . self::format( $mode ) . "\n\n" . self::context( $app, $tree, $files );
324
+ $history = [];
325
+
326
+ foreach ( array_slice( Usage::history( $app_id, get_current_user_id() ), -1 * max( 0, (int) self::settings()['history'] ) ) as $row ) {
327
+ if ( in_array( $row['status'], [ 'ok', 'proposed', 'applied', 'needs' ], true ) ) {
328
+ $history[] = [ 'role' => 'user', 'content' => (string) $row['prompt'] ];
329
+ $history[] = [ 'role' => 'assistant', 'content' => (string) $row['response'] ];
330
+ }
331
+ }
332
+
333
+ $history[] = [ 'role' => 'user', 'content' => $prompt . ( $attachments ? "\n\nAttached files:\n" . implode( "\n", $attachments ) : '' ) ];
334
+ $result = self::complete( $mode, $system, $history );
335
+
336
+ if ( is_wp_error( $result ) ) {
337
+ return $result;
338
+ }
339
+
340
+ if ( 'build' !== $mode ) {
341
+ return $result + [ 'status' => 'ok', 'response' => $result['text'] ];
342
+ }
343
+
344
+ $proposal = self::proposal( $result['text'], $tree, array_keys( $files ) );
345
+
346
+ if ( is_wp_error( $proposal ) ) {
347
+ return new \WP_Error( $proposal->get_error_code(), $proposal->get_error_message(), [ 'status' => 422, 'tokens_in' => $result['tokens_in'], 'tokens_out' => $result['tokens_out'] ] );
348
+ }
349
+
350
+ return $result + [
351
+ 'status' => $proposal['changes'] ? 'proposed' : ( $proposal['needs'] || $proposal['questions'] ? 'needs' : 'ok' ),
352
+ 'response' => (string) wp_json_encode( $proposal ),
353
+ ];
354
+ }
355
+
356
+ public static function proposal( string $text, array $tree, array $seen ) {
357
+ $json = trim( preg_replace( '/^```(?:json)?\s*|\s*```$/', '', trim( $text ) ) );
358
+ $data = json_decode( $json, true );
359
+
360
+ if ( ! is_array( $data ) ) {
361
+ return new \WP_Error( 'engine_invalid', 'The model did not return a valid change set, so nothing was proposed. Try again or rephrase.' );
362
+ }
363
+
364
+ $changes = [];
365
+
366
+ foreach ( (array) ( $data['changes'] ?? [] ) as $change ) {
367
+ $path = ltrim( str_replace( '\\', '/', (string) ( $change['path'] ?? '' ) ), '/' );
368
+ $action = 'delete' === ( $change['action'] ?? 'write' ) ? 'delete' : 'write';
369
+
370
+ if ( '' === $path || false !== strpos( $path, '..' ) || preg_match( self::BLOCKED, $path ) || ! preg_match( '#^[A-Za-z0-9._/@ -]+$#', $path ) ) {
371
+ return new \WP_Error( 'engine_scope', sprintf( 'The model tried to change "%s", which is outside this app. Nothing was proposed.', $path ) );
372
+ }
373
+
374
+ $exists = in_array( $path, $tree, true );
375
+
376
+ if ( $exists && ! in_array( $path, $seen, true ) ) {
377
+ return new \WP_Error( 'engine_unseen', sprintf( 'The model tried to rewrite %s without reading it first. Nothing was proposed. Mention the file by its path so it is included.', $path ) );
378
+ }
379
+
380
+ if ( 'delete' === $action && ! $exists ) {
381
+ continue;
382
+ }
383
+
384
+ $content = (string) ( $change['content'] ?? '' );
385
+
386
+ if ( 'write' === $action && ( '' === trim( $content ) || strlen( $content ) > self::MAX_BYTES ) ) {
387
+ return new \WP_Error( 'engine_invalid', sprintf( 'The model returned empty or oversized content for %s. Nothing was proposed.', $path ) );
388
+ }
389
+
390
+ $changes[ $path ] = [ 'path' => $path, 'action' => $action, 'content' => 'write' === $action ? $content : '', 'new' => ! $exists ];
391
+ }
392
+
393
+ if ( count( $changes ) > self::MAX_FILES ) {
394
+ return new \WP_Error( 'engine_invalid', sprintf( 'The model proposed %d files; the limit is %d. Ask for a smaller step.', count( $changes ), self::MAX_FILES ) );
395
+ }
396
+
397
+ $needs = array_values( array_filter( array_map( 'strval', (array) ( $data['needs'] ?? [] ) ) ) );
398
+ $questions = array_values( array_filter( array_map( 'strval', (array) ( $data['questions'] ?? [] ) ) ) );
399
+
400
+ return [
401
+ 'summary' => (string) ( $data['summary'] ?? '' ),
402
+ 'changes' => $needs || $questions ? [] : array_values( $changes ),
403
+ 'needs' => $needs,
404
+ 'questions' => $questions,
405
+ ];
406
+ }
407
+
408
+ public static function apply( int $app_id, int $message_id ) {
409
+ $row = Usage::find( $message_id );
410
+ $app = Registry::get( $app_id );
411
+
412
+ if ( ! $row || ! $app || (int) $row['app_id'] !== $app_id || ( (int) $row['user_id'] !== get_current_user_id() && ! current_user_can( 'manage_options' ) ) ) {
413
+ return new \WP_Error( 'not_found', 'Message not found.', [ 'status' => 404 ] );
414
+ }
415
+
416
+ if ( 'proposed' !== $row['status'] ) {
417
+ return new \WP_Error( 'state', 'applied' === $row['status'] ? 'These changes were already committed.' : 'There is nothing to commit for this message.', [ 'status' => 409 ] );
418
+ }
419
+
420
+ $proposal = json_decode( (string) $row['response'], true );
421
+ $mapping = Ops::mapping( $app_id, (string) $app['name'] );
422
+
423
+ if ( ! is_array( $proposal ) || '' === $mapping['path'] ) {
424
+ return new \WP_Error( 'state', 'This app has no folder in the repository yet.', [ 'status' => 409 ] );
425
+ }
426
+
427
+ $changes = [];
428
+
429
+ foreach ( (array) $proposal['changes'] as $change ) {
430
+ $changes[ $mapping['path'] . '/' . $change['path'] ] = 'delete' === $change['action'] ? null : (string) $change['content'];
431
+ }
432
+
433
+ $branch = self::branch( $mapping );
434
+ $commit = Github::commit( sprintf( '%s: %s', $mapping['slug'], wp_trim_words( (string) $proposal['summary'] ?: 'changes', 14, '…' ) ), $changes, $branch );
435
+
436
+ if ( is_wp_error( $commit ) ) {
437
+ return $commit;
438
+ }
439
+
440
+ $proposal['commit'] = $commit;
441
+ Usage::update( $message_id, [ 'status' => 'applied', 'response' => (string) wp_json_encode( $proposal ) ] );
442
+
443
+ return $commit;
444
+ }
445
+
446
+ public static function branch( array $mapping ): string {
447
+ $branch = strtr( (string) self::settings()['branch'], [ '{slug}' => $mapping['slug'], '{kind}' => $mapping['kind'] ] );
448
+
449
+ return preg_replace( '#[^A-Za-z0-9._/-]#', '-', $branch ) ?: 'platform/' . $mapping['slug'];
450
+ }
451
+
452
+ public static function assist( string $action, string $scope, string $prompt, $target ) {
453
+ $system = "You help editors of the wp-operations CMS with content.\n\n"
454
+ . "Rules: work only with the data given. Never invent facts, names, numbers, links or content that is not in the data or the request. If something is missing, say so. Do not claim you saved or changed anything: you only suggest, and the editor decides.\n\n"
455
+ . self::knowledge( 0, 'content', $prompt . ' ' . $action ) . "\n\n"
456
+ . 'Task: ' . $action . ' (' . $scope . '). Answer in plain words or, for lists, short markdown.';
457
+
458
+ return self::complete( 'chat', $system, [ [ 'role' => 'user', 'content' => trim( $prompt . "\n\nData:\n" . wp_json_encode( $target, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ) ] ] );
459
+ }
460
+
461
+
462
+ public static function admin(): array {
463
+ $settings = self::settings();
464
+
465
+ return [
466
+ 'settings' => array_merge(
467
+ $settings,
468
+ [
469
+ 'providers' => array_map(
470
+ static fn( array $p ): array => $p + [ 'key_set' => '' !== self::secret( $p ) ],
471
+ (array) $settings['providers']
472
+ ),
473
+ ]
474
+ ),
475
+ 'formats' => self::FORMATS,
476
+ 'modes' => array_values( (array) Module::config( 'modes', [] ) ),
477
+ ];
478
+ }
479
+
480
+ public static function save( array $input ): array {
481
+ $providers = [];
482
+
483
+ foreach ( (array) ( $input['providers'] ?? [] ) as $row ) {
484
+ $label = sanitize_text_field( (string) ( $row['label'] ?? '' ) );
485
+ $base = esc_url_raw( trim( (string) ( $row['base_url'] ?? '' ) ), [ 'https', 'http' ] );
486
+ $model = sanitize_text_field( (string) ( $row['model'] ?? '' ) );
487
+
488
+ if ( '' === $label || '' === $base || '' === $model ) {
489
+ continue;
490
+ }
491
+
492
+ $key = sanitize_key( (string) ( $row['key'] ?? '' ) ) ?: sanitize_key( sanitize_title( $label ) );
493
+ $providers[ $key ] = [
494
+ 'key' => $key,
495
+ 'label' => $label,
496
+ 'format' => isset( self::FORMATS[ $row['format'] ?? '' ] ) ? (string) $row['format'] : 'openai',
497
+ 'base_url' => untrailingslashit( $base ),
498
+ 'model' => $model,
499
+ 'key_constant' => preg_replace( '/[^A-Z0-9_]/', '', strtoupper( (string) ( $row['key_constant'] ?? '' ) ) ),
500
+ 'max_tokens' => max( 256, min( 200000, (int) ( $row['max_tokens'] ?? 8192 ) ) ),
501
+ 'temperature' => max( 0, min( 1, (float) ( $row['temperature'] ?? 0.2 ) ) ),
502
+ ];
503
+ }
504
+
505
+ $modes = [];
506
+
507
+ foreach ( (array) ( $input['modes'] ?? [] ) as $mode => $key ) {
508
+ if ( isset( $providers[ $key ] ) ) {
509
+ $modes[ sanitize_key( (string) $mode ) ] = (string) $key;
510
+ }
511
+ }
512
+
513
+ update_option(
514
+ self::OPTION,
515
+ [
516
+ 'providers' => array_values( $providers ),
517
+ 'default' => isset( $providers[ $input['default'] ?? '' ] ) ? (string) $input['default'] : (string) ( array_key_first( $providers ) ?? '' ),
518
+ 'modes' => $modes,
519
+ 'rules' => sanitize_textarea_field( (string) ( $input['rules'] ?? '' ) ),
520
+ 'history' => max( 0, min( 20, (int) ( $input['history'] ?? 6 ) ) ),
521
+ 'branch' => preg_replace( '#[^A-Za-z0-9._/{}-]#', '', (string) ( $input['branch'] ?? 'platform/{slug}' ) ) ?: 'platform/{slug}',
522
+ ],
523
+ false
524
+ );
525
+
526
+ return self::admin();
527
+ }
528
+
529
+ public static function test( string $key ) {
530
+ foreach ( (array) self::settings()['providers'] as $provider ) {
531
+ if ( $provider['key'] === $key ) {
532
+ $started = microtime( true );
533
+
534
+ if ( 'images' === $provider['format'] ) {
535
+ $secret = self::secret( $provider );
536
+ $response = '' === $secret ? new \WP_Error( 'key', sprintf( 'Add define( \'%s\', \'…\' ) to wp-config.php.', $provider['key_constant'] ) ) : wp_remote_get( untrailingslashit( $provider['base_url'] ) . '/models', [ 'timeout' => 15, 'headers' => [ 'Authorization' => 'Bearer ' . $secret ] ] );
537
+ $code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
538
+
539
+ if ( is_wp_error( $response ) || $code >= 400 ) {
540
+ return new \WP_Error( 'engine', is_wp_error( $response ) ? $response->get_error_message() : sprintf( '%s returned %d.', $provider['label'], $code ), [ 'status' => 502 ] );
541
+ }
542
+
543
+ return [ 'text' => 'OK', 'model' => $provider['model'], 'ms' => (int) round( ( microtime( true ) - $started ) * 1000 ) ];
544
+ }
545
+
546
+ $result = self::complete( 'chat', 'Reply with the single word OK.', [ [ 'role' => 'user', 'content' => 'Connection test.' ] ], [ 'max_tokens' => 16 ] + $provider );
547
+
548
+ return is_wp_error( $result ) ? $result : [ 'text' => $result['text'], 'model' => $result['model'], 'ms' => (int) round( ( microtime( true ) - $started ) * 1000 ) ];
549
+ }
550
+ }
551
+
552
+ return new \WP_Error( 'missing', 'Unknown model.', [ 'status' => 404 ] );
553
+ }
554
+ }