@moretea-labs/forge 1.5.0 → 1.6.0

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 (138) hide show
  1. package/CHANGELOG.md +28 -1
  2. package/DESIGN.md +7 -2
  3. package/README.md +7 -7
  4. package/README.zh-CN.md +5 -3
  5. package/THIRD_PARTY_NOTICES.md +1 -1
  6. package/assets/hooks/pre-edit-guard.sh +8 -39
  7. package/assets/hooks/prompt-guard.sh +2 -2
  8. package/assets/plugin-registry.v1.json +54 -3
  9. package/assets/reference-configs/hook-operations.md +1 -1
  10. package/assets/reference-configs/sprint-contracts.md +2 -2
  11. package/assets/skill-version.json +2 -2
  12. package/assets/templates/helpers/ensure-task-workflow.sh +2 -2
  13. package/assets/templates/helpers/sprint-backlog.sh +6 -6
  14. package/docs/architecture/current/automation-and-schedule-engine.md +9 -3
  15. package/docs/architecture/current/codegraph-context-provider.md +15 -3
  16. package/docs/architecture/current/dispatch-and-agent-strategy.md +32 -13
  17. package/docs/architecture/current/entity-model.md +20 -0
  18. package/docs/architecture/current/external-plugin-governance.md +3 -3
  19. package/docs/architecture/current/system-overview.md +26 -1
  20. package/docs/architecture/current/thin-harness-v1.md +10 -0
  21. package/docs/forge-chatgpt-mcp-setup.md +27 -3
  22. package/docs/operations/chatgpt-personal-assistant-runtime.md +12 -2
  23. package/docs/operations/controller-browser-plugin.md +12 -16
  24. package/docs/operations/features.md +1 -1
  25. package/docs/operations/homebrew.md +2 -2
  26. package/docs/public-usage-guide.md +1 -1
  27. package/docs/public-usage-guide.zh-CN.md +1 -1
  28. package/docs/tutorials/01-install-and-start.md +6 -4
  29. package/docs/tutorials/01-install-and-start.zh-CN.md +3 -1
  30. package/docs/tutorials/02-connect-chatgpt.md +8 -2
  31. package/docs/tutorials/02-connect-chatgpt.zh-CN.md +8 -2
  32. package/docs/wiki/Installation.md +1 -1
  33. package/docs/wiki/Quick-Start.md +1 -1
  34. package/package.json +1 -1
  35. package/scripts/check-public-docs.sh +14 -1
  36. package/scripts/migrate-chatgpt-automation-schedules.ts +64 -0
  37. package/scripts/sprint-backlog.sh +1 -1
  38. package/src/cli/commands/chatgpt.ts +31 -2
  39. package/src/cli/commands/init-hook.ts +3 -1
  40. package/src/cli/commands/mcp.ts +2 -0
  41. package/src/cli/commands/plugin.ts +36 -9
  42. package/src/cli/commands/runtime.ts +1 -0
  43. package/src/cli/commands/setup-profile.ts +49 -18
  44. package/src/cli/controller/context-pack.ts +158 -6
  45. package/src/cli/hook/prompt-guard-decision.ts +17 -18
  46. package/src/cli/hook/prompt-intents.ts +1 -1
  47. package/src/cli/local-bridge/console-assets.ts +17 -0
  48. package/src/cli/local-bridge/console-automations.ts +205 -23
  49. package/src/cli/local-bridge/console-view-models.ts +2 -0
  50. package/src/cli/local-bridge/facade-api.ts +2 -0
  51. package/src/cli/local-bridge/frontend/src/App.tsx +1 -1
  52. package/src/cli/local-bridge/frontend/src/features/automations/AutomationsView.tsx +143 -3
  53. package/src/cli/local-bridge/frontend/src/features/capabilities/CapabilitiesView.tsx +1 -1
  54. package/src/cli/local-bridge/frontend/src/features/overview/OverviewView.tsx +181 -3
  55. package/src/cli/local-bridge/frontend/src/features/repositories/RepositoriesView.tsx +1 -1
  56. package/src/cli/local-bridge/frontend/src/features/work/WorkView.tsx +4 -3
  57. package/src/cli/local-bridge/frontend/src/lib/api.ts +18 -6
  58. package/src/cli/local-bridge/frontend/src/shell/CommandBar.tsx +1 -1
  59. package/src/cli/local-bridge/frontend/src/shell/Sidebar.tsx +2 -1
  60. package/src/cli/local-bridge/frontend/src/styles.css +27 -11
  61. package/src/cli/local-bridge/frontend/src/types.ts +6 -2
  62. package/src/cli/local-bridge/server.ts +31 -20
  63. package/src/cli/local-bridge/ui-dist/app.css +1 -1
  64. package/src/cli/local-bridge/ui-dist/app.js +5003 -4815
  65. package/src/cli/mcp/auth.ts +2 -0
  66. package/src/cli/mcp/paths.ts +8 -2
  67. package/src/cli/mcp/repository-tools.ts +124 -9
  68. package/src/cli/mcp/server.ts +164 -19
  69. package/src/cli/mcp/setup.ts +9 -1
  70. package/src/cli/mcp/transports/http.ts +52 -2
  71. package/src/cli/mcp/transports/session-registry.ts +24 -0
  72. package/src/cli/repositories/command-classifier.ts +113 -0
  73. package/src/cli/repositories/safe-patch.ts +6 -4
  74. package/src/cli/repositories/structured-git.ts +49 -7
  75. package/src/cli/repository/inspector.ts +16 -3
  76. package/src/runtime/assistant/intent.ts +3 -3
  77. package/src/runtime/control-plane/execution/direct-edit-work-completion.ts +157 -2
  78. package/src/runtime/control-plane/execution/execution-identity.ts +65 -14
  79. package/src/runtime/control-plane/execution/validation.ts +15 -2
  80. package/src/runtime/control-plane/execution/work-terminal-cleanup.ts +32 -0
  81. package/src/runtime/control-plane/execution/work-validation-reconciler.ts +6 -7
  82. package/src/runtime/control-plane/execution/work-verification-snapshot.ts +2 -1
  83. package/src/runtime/control-plane/facade/capability-registry.ts +1 -1
  84. package/src/runtime/control-plane/facade/controller-session-store.ts +12 -13
  85. package/src/runtime/control-plane/facade/goal-workloop-access.ts +7 -2
  86. package/src/runtime/control-plane/facade/goal-workloop.ts +231 -8
  87. package/src/runtime/control-plane/facade/plan-contract-store.ts +32 -12
  88. package/src/runtime/control-plane/facade/requirement-board.ts +24 -8
  89. package/src/runtime/control-plane/facade/types.ts +33 -6
  90. package/src/runtime/control-plane/facade/work-contract-store.ts +31 -2
  91. package/src/runtime/control-plane/launcher/chatgpt-work-continuation.ts +375 -23
  92. package/src/runtime/control-plane/persistence/requirement-store.ts +15 -11
  93. package/src/runtime/diagnostics/mcp-timing.ts +6 -0
  94. package/src/runtime/execution/process-runtime/check-facade.ts +1 -10
  95. package/src/runtime/execution/process-runtime/check-result.ts +10 -2
  96. package/src/runtime/execution/process-runtime/command-facade.ts +1 -0
  97. package/src/runtime/execution/process-runtime/gc.ts +64 -10
  98. package/src/runtime/execution/process-runtime/persisted-check.ts +10 -2
  99. package/src/runtime/execution/process-runtime/resource-claims.ts +87 -2
  100. package/src/runtime/execution/process-runtime/runtime.ts +16 -1
  101. package/src/runtime/execution/process-runtime/store.ts +6 -0
  102. package/src/runtime/gateway/mcp/execution-tools.ts +27 -12
  103. package/src/runtime/gateway/mcp/router.ts +1 -1
  104. package/src/runtime/gateway/mcp/runtime-tools.ts +482 -178
  105. package/src/runtime/model-clients/deepseek-adapter.ts +0 -32
  106. package/src/runtime/plugins/browser-adapter.ts +19 -72
  107. package/src/runtime/plugins/browser-handoff-host.ts +6 -31
  108. package/src/runtime/plugins/browser-handoff.ts +0 -3
  109. package/src/runtime/plugins/browser-macos-bridge.ts +8 -0
  110. package/src/runtime/plugins/desktop-operator-registration.ts +8 -11
  111. package/src/runtime/plugins/external-registration.ts +84 -5
  112. package/src/runtime/plugins/first-party-registry.ts +2 -2
  113. package/src/runtime/plugins/gmail-adapter.ts +28 -2
  114. package/src/runtime/plugins/local-system-adapter.ts +2 -2
  115. package/src/runtime/plugins/plugin-management-adapter.ts +140 -0
  116. package/src/runtime/plugins/store.ts +107 -5
  117. package/src/runtime/plugins/types.ts +4 -0
  118. package/src/runtime/recovery/actions.ts +0 -10
  119. package/src/runtime/recovery/classifier.ts +0 -9
  120. package/src/runtime/recovery/maintenance-executor.ts +43 -11
  121. package/src/runtime/recovery/probe.ts +0 -1
  122. package/src/runtime/recovery/types.ts +0 -1
  123. package/src/runtime/root/package-connector-service.ts +136 -0
  124. package/src/runtime/root/package-runtime-service.ts +25 -12
  125. package/src/runtime/root/release-materialize.ts +161 -18
  126. package/src/runtime/root/service.ts +6 -4
  127. package/src/runtime/safe-tooling/index.ts +0 -1
  128. package/src/runtime/safe-tooling/types.ts +0 -30
  129. package/src/runtime/standalone-recovery/core.ts +2 -2
  130. package/src/runtime/workflow/schedules/browser-probe.ts +180 -0
  131. package/src/runtime/workflow/schedules/chatgpt-automation-migration.ts +40 -0
  132. package/src/runtime/workflow/schedules/engine.ts +357 -64
  133. package/src/runtime/workflow/schedules/types.ts +5 -0
  134. package/src/runtime/workflow/schedules/work-continuation.ts +100 -27
  135. package/bin/forge-desktop-helper.mjs +0 -204
  136. package/docs/operations/controller-desktop-plugin.md +0 -112
  137. package/src/runtime/plugins/desktop-adapter.ts +0 -374
  138. package/src/runtime/safe-tooling/browser-safe.ts +0 -133
@@ -1,374 +0,0 @@
1
- import { existsSync, mkdirSync } from 'fs';
2
- import { dirname, join } from 'path';
3
- import { fileURLToPath } from 'url';
4
- import { controllerSystemRoot } from '../../cli/repositories/controller-home';
5
- import { readJsonFile, writeJsonAtomic } from '../shared/json-files';
6
- import { readReleaseIdentityBindingFromEnv } from '../release/identity';
7
- import { AssistantPluginError } from './errors';
8
- import { resolveBrowserBridgeNodeExecutable } from './browser-node-bridge';
9
- import { executeManagedPluginProcess, type ManagedPluginProcessRequest, type ManagedPluginProcessSpec } from './managed-process-adapter';
10
- import type {
11
- AssistantPluginActionDescriptor,
12
- AssistantPluginActionExecutionInput,
13
- AssistantPluginCapability,
14
- AssistantPluginHealth,
15
- AssistantPluginManifest,
16
- AssistantPluginPermissionScope,
17
- } from './types';
18
-
19
- const PLUGIN_ID = 'desktop';
20
- const CONFIG_FILE = 'config.json';
21
- const HELPER_VERSION = '1.0.0';
22
- const REQUIRED_CAPABILITIES = ['status', 'observe', 'open_application'];
23
-
24
- interface DesktopPluginConfig {
25
- schemaVersion: 1;
26
- enabled: boolean;
27
- }
28
-
29
- export interface DesktopPluginHooks {
30
- now?: () => Date;
31
- platform?: NodeJS.Platform;
32
- resolveHelperPath?: () => string;
33
- resolveRuntimeExecutable?: () => string;
34
- executeManaged?: (spec: ManagedPluginProcessSpec, request: ManagedPluginProcessRequest) => Promise<Record<string, unknown>>;
35
- }
36
-
37
- let hooks: DesktopPluginHooks = {};
38
-
39
- export function setDesktopPluginHooksForTest(next: DesktopPluginHooks): void {
40
- hooks = next;
41
- }
42
-
43
- export function resetDesktopPluginHooksForTest(): void {
44
- hooks = {};
45
- }
46
-
47
- function now(): string {
48
- return (hooks.now?.() ?? new Date()).toISOString();
49
- }
50
-
51
- function platform(): NodeJS.Platform {
52
- return hooks.platform ?? process.platform;
53
- }
54
-
55
- function pluginRootFromSystemRoot(systemRoot: string): string {
56
- const root = join(systemRoot, 'desktop');
57
- mkdirSync(root, { recursive: true });
58
- return root;
59
- }
60
-
61
- function configPathFromSystemRoot(systemRoot: string): string {
62
- return join(pluginRootFromSystemRoot(systemRoot), CONFIG_FILE);
63
- }
64
-
65
- function loadConfig(systemRoot: string): DesktopPluginConfig {
66
- try {
67
- const config = readJsonFile<DesktopPluginConfig>(configPathFromSystemRoot(systemRoot));
68
- return { schemaVersion: 1, enabled: config.enabled === true };
69
- } catch {
70
- return { schemaVersion: 1, enabled: false };
71
- }
72
- }
73
-
74
- function saveConfig(systemRoot: string, config: DesktopPluginConfig): DesktopPluginConfig {
75
- writeJsonAtomic(configPathFromSystemRoot(systemRoot), config);
76
- return config;
77
- }
78
-
79
- export function resolveDesktopRuntimeExecutable(): string {
80
- return hooks.resolveRuntimeExecutable?.() ?? resolveBrowserBridgeNodeExecutable();
81
- }
82
-
83
- export function resolveDesktopHelperPath(options: {
84
- argvEntry?: string;
85
- runtimeExecutable?: string;
86
- sourceHelperPath?: string;
87
- releasePath?: string;
88
- env?: NodeJS.ProcessEnv;
89
- pathExists?: (path: string) => boolean;
90
- } = {}): string {
91
- if (hooks.resolveHelperPath) return hooks.resolveHelperPath();
92
- const releasePath = options.releasePath
93
- ?? readReleaseIdentityBindingFromEnv(options.env ?? process.env)?.releasePath;
94
- const argvEntry = options.argvEntry ?? process.argv[1];
95
- const runtimeExecutable = options.runtimeExecutable ?? process.execPath;
96
- const sourceHelperPath = options.sourceHelperPath
97
- ?? fileURLToPath(new URL('../../../bin/forge-desktop-helper.mjs', import.meta.url));
98
- const pathExists = options.pathExists ?? existsSync;
99
- const candidates = [
100
- releasePath ? join(releasePath, 'forge-desktop-helper.mjs') : undefined,
101
- argvEntry ? join(dirname(argvEntry), 'forge-desktop-helper.mjs') : undefined,
102
- runtimeExecutable ? join(dirname(runtimeExecutable), 'forge-desktop-helper.mjs') : undefined,
103
- sourceHelperPath,
104
- ].filter((entry): entry is string => Boolean(entry));
105
- for (const candidate of candidates) {
106
- if (pathExists(candidate)) return candidate;
107
- }
108
- throw new AssistantPluginError('PLUGIN_DESKTOP_HELPER_UNAVAILABLE', 'The bundled Desktop helper is missing from the active Forge installation.', {
109
- retryable: false,
110
- });
111
- }
112
-
113
- function helperAvailability(): { available: boolean; path?: string; error?: string } {
114
- try {
115
- return { available: true, path: resolveDesktopHelperPath() };
116
- } catch (error) {
117
- return { available: false, error: error instanceof Error ? error.message : String(error) };
118
- }
119
- }
120
-
121
- function runtimeAvailability(): { available: boolean; path?: string; error?: string } {
122
- try {
123
- return { available: true, path: resolveDesktopRuntimeExecutable() };
124
- } catch (error) {
125
- return { available: false, error: error instanceof Error ? error.message : String(error) };
126
- }
127
- }
128
-
129
- function health(config: DesktopPluginConfig): AssistantPluginHealth {
130
- const helper = helperAvailability();
131
- const currentPlatform = platform();
132
- const runtime = config.enabled && currentPlatform === 'darwin' ? runtimeAvailability() : undefined;
133
- const details = {
134
- provider: 'bundled-managed-desktop',
135
- scope: 'controller',
136
- repositoryRegistrationRequired: false,
137
- runtime: 'managed_process',
138
- transport: 'stdio-jsonl',
139
- helperVersion: HELPER_VERSION,
140
- helperBundled: helper.available,
141
- helperPathReturned: false,
142
- runtimeProbed: Boolean(runtime),
143
- runtimeAvailable: runtime?.available ?? false,
144
- runtimePathReturned: false,
145
- readinessMode: 'on_demand_helper',
146
- platform: currentPlatform,
147
- };
148
- if (!config.enabled) {
149
- return {
150
- state: 'disabled',
151
- checkedAt: now(),
152
- ready: false,
153
- probed: false,
154
- errors: [],
155
- warnings: ['Desktop plugin is disabled.'],
156
- details,
157
- };
158
- }
159
- if (currentPlatform !== 'darwin') {
160
- return {
161
- state: 'degraded',
162
- checkedAt: now(),
163
- ready: false,
164
- probed: true,
165
- errors: [],
166
- warnings: ['Desktop plugin currently supports macOS only.'],
167
- details,
168
- };
169
- }
170
- if (!helper.available) {
171
- return {
172
- state: 'error',
173
- checkedAt: now(),
174
- ready: false,
175
- probed: true,
176
- errors: [helper.error ?? 'Bundled Desktop helper is unavailable.'],
177
- warnings: [],
178
- details,
179
- };
180
- }
181
- if (!runtime?.available) {
182
- return {
183
- state: 'error',
184
- checkedAt: now(),
185
- ready: false,
186
- probed: true,
187
- errors: [runtime?.error ?? 'A trusted Node runtime for the Desktop helper is unavailable.'],
188
- warnings: [],
189
- details,
190
- };
191
- }
192
- return {
193
- state: 'ready',
194
- checkedAt: now(),
195
- ready: true,
196
- probed: true,
197
- errors: [],
198
- warnings: [],
199
- details,
200
- };
201
- }
202
-
203
- function actions(): AssistantPluginActionDescriptor[] {
204
- const controllerWrite = [{ resource: 'repo-state' as const, mode: 'write' as const }];
205
- return [
206
- {
207
- actionId: 'configure',
208
- title: 'Configure Desktop plugin',
209
- description: 'Enable or disable the bundled managed Desktop helper.',
210
- readOnly: false,
211
- risk: 'workspace_write',
212
- confirmation: 'authorization',
213
- defaultTimeoutMs: 15_000,
214
- cancellable: true,
215
- idempotent: true,
216
- scopes: ['desktop.manage'],
217
- resourceClaims: controllerWrite,
218
- argumentsSchema: { type: 'object', properties: { enabled: { type: 'boolean' } }, required: ['enabled'], additionalProperties: false },
219
- },
220
- {
221
- actionId: 'status',
222
- title: 'Desktop helper status',
223
- description: 'Run a live managed-helper handshake and return bounded macOS readiness diagnostics.',
224
- readOnly: true,
225
- risk: 'readonly',
226
- confirmation: 'none',
227
- defaultTimeoutMs: 10_000,
228
- cancellable: true,
229
- idempotent: true,
230
- scopes: ['desktop.observe'],
231
- resourceClaims: [],
232
- argumentsSchema: { type: 'object', properties: {}, additionalProperties: false },
233
- },
234
- {
235
- actionId: 'observe',
236
- title: 'Observe active desktop application',
237
- description: 'Read the frontmost macOS application without capturing the screen or interacting with UI elements.',
238
- readOnly: true,
239
- risk: 'readonly',
240
- confirmation: 'none',
241
- defaultTimeoutMs: 10_000,
242
- cancellable: true,
243
- idempotent: true,
244
- scopes: ['desktop.observe'],
245
- resourceClaims: [],
246
- argumentsSchema: { type: 'object', properties: {}, additionalProperties: false },
247
- },
248
- {
249
- actionId: 'open_application',
250
- title: 'Open desktop application',
251
- description: 'Open one macOS application by exact name or bundle identifier through the managed helper.',
252
- readOnly: false,
253
- risk: 'workspace_write',
254
- confirmation: 'authorization',
255
- defaultTimeoutMs: 30_000,
256
- cancellable: true,
257
- idempotent: false,
258
- scopes: ['desktop.open'],
259
- resourceClaims: controllerWrite,
260
- argumentsSchema: {
261
- type: 'object',
262
- properties: { app_name: { type: 'string' }, bundle_id: { type: 'string' } },
263
- additionalProperties: false,
264
- },
265
- },
266
- ];
267
- }
268
-
269
- function permissions(): AssistantPluginPermissionScope[] {
270
- return [
271
- { scope: 'desktop.observe', mode: 'read', description: 'Read bounded frontmost-application and helper readiness diagnostics.', granted: true, required: true },
272
- { scope: 'desktop.open', mode: 'write', description: 'Open an application after action authorization.', granted: true, required: false },
273
- { scope: 'desktop.manage', mode: 'write', description: 'Enable or disable the bundled Desktop plugin.', granted: true, required: true },
274
- ];
275
- }
276
-
277
- function capabilities(): AssistantPluginCapability[] {
278
- return [
279
- { capabilityId: 'desktop-observe', title: 'Desktop observation', description: 'Inspect the active macOS application without screen capture or UI interaction.', scopes: ['desktop.observe'], actions: ['status', 'observe'] },
280
- { capabilityId: 'desktop-open', title: 'Desktop application launch', description: 'Open one macOS application through a bounded managed helper.', scopes: ['desktop.open'], actions: ['open_application'] },
281
- { capabilityId: 'desktop-lifecycle', title: 'Desktop plugin lifecycle', description: 'Enable or disable the bundled helper without installing external packages.', scopes: ['desktop.manage'], actions: ['configure'] },
282
- ];
283
- }
284
-
285
- export function buildDesktopPluginManifest(previousRevision = 0, previousUpdatedAt?: string, systemRoot?: string): AssistantPluginManifest {
286
- const root = systemRoot ?? process.cwd();
287
- const config = loadConfig(root);
288
- const currentHealth = health(config);
289
- return {
290
- schemaVersion: 1,
291
- manifestVersion: 1,
292
- revision: Math.max(1, previousRevision || 1),
293
- pluginId: PLUGIN_ID,
294
- provider: 'bundled-managed-desktop',
295
- displayName: 'Forge Desktop',
296
- pluginVersion: '1.0.0',
297
- authority: {
298
- strategy: 'derived',
299
- duplicateStateAllowed: false,
300
- sourceOfTruth: ['controllerHome:system/desktop/config.json', 'package:bin/forge-desktop-helper.mjs'],
301
- },
302
- enabled: config.enabled,
303
- lifecycle: {
304
- state: !config.enabled ? 'disabled' : currentHealth.ready ? 'enabled' : currentHealth.state === 'degraded' ? 'degraded' : 'error',
305
- reason: !config.enabled
306
- ? 'Desktop plugin is disabled.'
307
- : currentHealth.ready
308
- ? 'Bundled Desktop helper is ready for on-demand managed execution.'
309
- : currentHealth.errors[0] ?? currentHealth.warnings[0],
310
- },
311
- health: currentHealth,
312
- permissions: permissions(),
313
- capabilities: capabilities(),
314
- actions: actions(),
315
- updatedAt: previousUpdatedAt ?? now(),
316
- };
317
- }
318
-
319
- function optionalString(args: Record<string, unknown>, key: string): string | undefined {
320
- const value = typeof args[key] === 'string' ? String(args[key]).trim() : '';
321
- return value || undefined;
322
- }
323
-
324
- export async function executeDesktopPluginAction(input: AssistantPluginActionExecutionInput): Promise<Record<string, unknown>> {
325
- const systemRoot = controllerSystemRoot(input.controllerHome);
326
- const config = loadConfig(systemRoot);
327
- if (input.actionId === 'configure') {
328
- const next = saveConfig(systemRoot, { schemaVersion: 1, enabled: input.args.enabled === true });
329
- return {
330
- config: next,
331
- storage: 'controllerHome/system/desktop/config.json',
332
- health: health(next),
333
- };
334
- }
335
- if (!config.enabled) {
336
- throw new AssistantPluginError('PLUGIN_DISABLED', 'Desktop plugin is disabled.', { retryable: false });
337
- }
338
- if (platform() !== 'darwin') {
339
- throw new AssistantPluginError('PLUGIN_DESKTOP_PLATFORM_UNSUPPORTED', 'Desktop plugin currently supports macOS only.', { retryable: false });
340
- }
341
- if (!REQUIRED_CAPABILITIES.includes(input.actionId)) {
342
- throw new AssistantPluginError('PLUGIN_ACTION_NOT_SUPPORTED', `desktop/${input.actionId} is not supported.`, { retryable: false });
343
- }
344
- if (input.actionId === 'open_application') {
345
- const appName = optionalString(input.args, 'app_name');
346
- const bundleId = optionalString(input.args, 'bundle_id');
347
- if ((!appName && !bundleId) || (appName && bundleId)) {
348
- throw new AssistantPluginError('PLUGIN_ACTION_ARGUMENT_INVALID', 'Provide exactly one of app_name or bundle_id.', { retryable: false });
349
- }
350
- }
351
- const helperPath = resolveDesktopHelperPath();
352
- const runtimeExecutable = resolveDesktopRuntimeExecutable();
353
- const executeManaged = hooks.executeManaged ?? executeManagedPluginProcess;
354
- return await executeManaged({
355
- pluginId: PLUGIN_ID,
356
- helperPath,
357
- runtimeExecutable,
358
- requiredCapabilities: REQUIRED_CAPABILITIES,
359
- timeoutMs: input.timeoutMs,
360
- }, {
361
- requestId: input.requestId,
362
- actionId: input.actionId,
363
- input: input.args,
364
- timeoutMs: input.timeoutMs,
365
- signal: input.signal,
366
- });
367
- }
368
-
369
- export const desktopPluginAdapter = {
370
- pluginId: PLUGIN_ID,
371
- scope: 'controller' as const,
372
- buildManifest: buildDesktopPluginManifest,
373
- executeAction: executeDesktopPluginAction,
374
- };
@@ -1,133 +0,0 @@
1
- import { createHash } from 'crypto';
2
- import { readFileSync } from 'fs';
3
- import { join } from 'path';
4
- import type { AssistantPluginManifest } from '../plugins/types';
5
- import type { WebDomainAccessPreview, WebTarget } from './types';
6
-
7
- interface BrowserConfigLike {
8
- enabled?: boolean;
9
- allowedDomains?: string[];
10
- defaultTimeoutMs?: number;
11
- profileDir?: string;
12
- }
13
-
14
- const CONFIG_RELATIVE_PATH = '.forge/plugins/browser.json';
15
- const DOMAIN_KEY_MAX_LENGTH = 48;
16
- const DOMAIN_GRANT_TTL_MS = 15 * 60_000;
17
-
18
- function readConfig(repoRoot: string): BrowserConfigLike {
19
- try {
20
- return JSON.parse(readFileSync(join(repoRoot, CONFIG_RELATIVE_PATH), 'utf-8')) as BrowserConfigLike;
21
- } catch {
22
- return {};
23
- }
24
- }
25
-
26
- function hostnameFromDomain(value: string): string {
27
- const raw = value.trim().toLowerCase();
28
- if (!raw) throw new Error('DOMAIN_REQUIRED');
29
- let hostname = raw;
30
- if (raw.includes('://')) {
31
- const parsed = new URL(raw);
32
- hostname = parsed.hostname.toLowerCase();
33
- }
34
- hostname = hostname.replace(/^\.+|\.+$/g, '');
35
- if (!hostname || hostname.length > 253) throw new Error('DOMAIN_INVALID');
36
- if (hostname === 'localhost' || /^\d+\.\d+\.\d+\.\d+$/.test(hostname)) throw new Error('DOMAIN_PUBLIC_HOST_REQUIRED');
37
- if (!/^[a-z0-9.-]+$/.test(hostname) || hostname.includes('..') || !hostname.includes('.')) throw new Error('DOMAIN_INVALID');
38
- return hostname;
39
- }
40
-
41
- export function domainKeyFor(domain: string): string {
42
- const normalized = hostnameFromDomain(domain);
43
- const base = normalized.replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, DOMAIN_KEY_MAX_LENGTH);
44
- return base || createHash('sha256').update(normalized).digest('hex').slice(0, 12);
45
- }
46
-
47
- export function browserAllowedDomains(repoRoot: string, manifest?: AssistantPluginManifest): string[] {
48
- const config = readConfig(repoRoot);
49
- const rawFromConfig = Array.isArray(config.allowedDomains) ? config.allowedDomains : undefined;
50
- const rawFromManifest = Array.isArray(manifest?.health.details?.allowedDomains) ? manifest?.health.details?.allowedDomains : undefined;
51
- const raw = rawFromConfig ?? rawFromManifest ?? [];
52
- return Array.from(new Set(raw.map((entry) => {
53
- try { return hostnameFromDomain(String(entry)); }
54
- catch { return undefined; }
55
- }).filter((entry): entry is string => Boolean(entry)))).sort();
56
- }
57
-
58
- export function listWebTargets(repoRoot: string, manifest?: AssistantPluginManifest): WebTarget[] {
59
- return browserAllowedDomains(repoRoot, manifest).map((domain) => ({
60
- targetKey: domainKeyFor(domain),
61
- domain,
62
- origin: `https://${domain}`,
63
- allowed: true,
64
- defaultPath: '/',
65
- }));
66
- }
67
-
68
- export function resolveWebTargetUrl(repoRoot: string, targetKey: string, rawPath?: unknown, query?: unknown, manifest?: AssistantPluginManifest): string {
69
- const targets = listWebTargets(repoRoot, manifest);
70
- const normalizedKey = String(targetKey ?? '').trim();
71
- const target = targets.find((entry) => entry.targetKey === normalizedKey || entry.domain === normalizedKey);
72
- if (!target) throw new Error(`WEB_TARGET_NOT_ALLOWED: ${normalizedKey}`);
73
- const path = typeof rawPath === 'string' && rawPath.trim() ? rawPath.trim() : '/';
74
- if (path.includes('://')) throw new Error('WEB_TARGET_PATH_ONLY: provide a path, not an absolute URL');
75
- if (path.includes('..')) throw new Error('WEB_TARGET_PATH_INVALID: parent traversal is not allowed');
76
- const url = new URL(path.startsWith('/') ? path : `/${path}`, target.origin);
77
- if (query && typeof query === 'object' && !Array.isArray(query)) {
78
- for (const [key, value] of Object.entries(query as Record<string, unknown>)) {
79
- if (value === undefined || value === null) continue;
80
- if (Array.isArray(value)) {
81
- for (const entry of value) url.searchParams.append(key, String(entry));
82
- } else {
83
- url.searchParams.set(key, String(value));
84
- }
85
- }
86
- }
87
- return url.toString();
88
- }
89
-
90
- function accessTicket(domain: string, currentDomains: string[], reason: string, expiresAt: string): string {
91
- const payload = {
92
- type: 'browser-domain-access',
93
- domain,
94
- currentDomains,
95
- reason: reason.slice(0, 240),
96
- expiresAt,
97
- };
98
- return `BDG-${createHash('sha256').update(JSON.stringify(payload)).digest('hex').slice(0, 20)}`;
99
- }
100
-
101
- export function previewBrowserDomainAccess(repoRoot: string, rawDomain: unknown, rawReason: unknown, manifest?: AssistantPluginManifest): WebDomainAccessPreview {
102
- const normalizedDomain = hostnameFromDomain(String(rawDomain ?? ''));
103
- const currentAllowedDomains = browserAllowedDomains(repoRoot, manifest);
104
- const reason = typeof rawReason === 'string' && rawReason.trim() ? rawReason.trim() : 'Requested by user.';
105
- const expiresAt = new Date(Date.now() + DOMAIN_GRANT_TTL_MS).toISOString();
106
- return {
107
- ticketId: accessTicket(normalizedDomain, currentAllowedDomains, reason, expiresAt),
108
- normalizedDomain,
109
- domainKey: domainKeyFor(normalizedDomain),
110
- reason,
111
- expiresAt,
112
- alreadyAllowed: currentAllowedDomains.includes(normalizedDomain),
113
- currentAllowedDomainCount: currentAllowedDomains.length,
114
- risk: 'workspace_write',
115
- confirmation: 'authorization',
116
- localOnly: true,
117
- willChange: {
118
- pluginId: 'browser',
119
- configField: 'allowedDomains',
120
- addDomain: normalizedDomain,
121
- },
122
- safety: {
123
- arbitraryUrlAccepted: false,
124
- domainOnly: true,
125
- sensitiveConfigReturned: false,
126
- },
127
- };
128
- }
129
-
130
- export function mergeAllowedDomains(repoRoot: string, rawDomain: unknown, manifest?: AssistantPluginManifest): string[] {
131
- const normalizedDomain = hostnameFromDomain(String(rawDomain ?? ''));
132
- return Array.from(new Set([...browserAllowedDomains(repoRoot, manifest), normalizedDomain])).sort();
133
- }