@adhdev/daemon-core 0.6.77 → 0.7.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.
@@ -0,0 +1,2342 @@
1
+ import { S as StatusResponse, D as DaemonEvent, C as CommandResult$2, a as SessionEntry, P as ProviderCategory, b as ProviderModule, R as ResolvedProvider, c as ProviderSettingSchema, d as CdpTargetFilter, e as ProviderInstance, I as InstanceContext, f as ProviderState, g as ProviderEvent, h as SessionTransport, i as StatusReportPayload, A as AvailableProviderInfo, j as AcpProviderState, k as ContentBlock } from './normalize-S2PmiRgB.mjs';
2
+ export { l as AcpConfigOption, m as AcpMode, n as ActiveChatData, o as AgentEntry, p as AgentSessionStream, q as ChatMessage, r as CliProviderState, s as DetectedIde, t as DetectedIdeInfo, E as ExtensionInfo, u as ExtensionProviderState, v as IdeProviderState, M as MachineInfo, w as ManagedStatus, x as ProviderConfig, y as ProviderErrorReason, z as ProviderInfo, B as ProviderStatus, F as SessionCapability, G as SessionKind, H as SystemInfo, W as WorkspaceActivity, J as WorkspaceEntry, K as addCliHistory, L as getWorkspaceActivity, N as getWorkspaceState, O as isManagedStatusWaiting, Q as isManagedStatusWorking, T as isSetupComplete, U as loadConfig, V as markSetupComplete, X as normalizeActiveChatData, Y as normalizeManagedStatus, Z as resetConfig, _ as saveConfig, $ as updateConfig } from './normalize-S2PmiRgB.mjs';
3
+
4
+ /**
5
+ * DaemonCore — Core daemon orchestrator interface
6
+ *
7
+ * Provides the core daemon orchestrator interface consumed by daemon-standalone.
8
+ * Actual implementation extracted from launcher and placed in this package.
9
+ */
10
+
11
+ interface DaemonCoreOptions {
12
+ /** Data directory for config, logs */
13
+ dataDir?: string;
14
+ /** Custom provider directories */
15
+ providerDirs?: string[];
16
+ /** Enable/disable specific detectors */
17
+ enableIdeDetection?: boolean;
18
+ enableCliDetection?: boolean;
19
+ enableAcpDetection?: boolean;
20
+ /** Status report interval (ms) */
21
+ statusInterval?: number;
22
+ }
23
+ interface IDaemonCore {
24
+ /** Initialize and start the daemon core */
25
+ start(): Promise<void>;
26
+ /** Gracefully stop the daemon */
27
+ stop(): Promise<void>;
28
+ /** Get current daemon status snapshot */
29
+ getStatus(): StatusResponse;
30
+ /** Subscribe to status changes. Returns unsubscribe function. */
31
+ onStatusChange(callback: (status: StatusResponse) => void): () => void;
32
+ /** Subscribe to all daemon events. Returns unsubscribe function. */
33
+ onEvent(callback: (event: DaemonEvent) => void): () => void;
34
+ /** Execute a command (send_chat, new_session, etc.) */
35
+ executeCommand(type: string, payload: any, target?: string): Promise<CommandResult$2>;
36
+ /** Get current canonical runtime sessions */
37
+ getSessions(): SessionEntry[];
38
+ }
39
+
40
+ /**
41
+ * ADHDev — IDE Detector (canonical implementation)
42
+ *
43
+ * Detects installed IDEs on the user's local machine.
44
+ * Supports macOS, Windows, and Linux.
45
+ *
46
+ * Migrated from @adhdev/core — this is now the single source of truth.
47
+ */
48
+ interface IDEInfo {
49
+ id: string;
50
+ name: string;
51
+ displayName: string;
52
+ installed: boolean;
53
+ path: string | null;
54
+ cliCommand: string | null;
55
+ version: string | null;
56
+ icon: string;
57
+ notes?: string;
58
+ }
59
+ declare function detectIDEs(): Promise<IDEInfo[]>;
60
+
61
+ /**
62
+ * Provider Version Detection & Archiving
63
+ *
64
+ * Detects installed versions for all provider categories (IDE, CLI, ACP, Extension).
65
+ * Archives version history to ~/.adhdev/version-history.json for compatibility tracking.
66
+ *
67
+ * Usage:
68
+ * const archive = new VersionArchive();
69
+ * const results = await detectAllVersions(providerLoader, archive);
70
+ */
71
+
72
+ interface ProviderVersionInfo {
73
+ type: string;
74
+ name: string;
75
+ category: string;
76
+ installed: boolean;
77
+ version: string | null;
78
+ path: string | null;
79
+ binary: string | null;
80
+ detectedAt: string;
81
+ /**
82
+ * Set when the detected version is NOT listed in provider.json testedVersions.
83
+ * Means scripts may not work correctly with this version.
84
+ */
85
+ warning?: string;
86
+ }
87
+ interface VersionHistoryEntry {
88
+ version: string;
89
+ detectedAt: string;
90
+ os: string;
91
+ }
92
+ interface VersionHistory {
93
+ [providerType: string]: VersionHistoryEntry[];
94
+ }
95
+ declare class VersionArchive {
96
+ private history;
97
+ constructor();
98
+ private load;
99
+ /** Record a detected version (deduplicates same version) */
100
+ record(type: string, version: string): void;
101
+ /** Get version history for a provider */
102
+ getHistory(type: string): VersionHistoryEntry[];
103
+ /** Get latest known version for a provider */
104
+ getLatest(type: string): string | null;
105
+ /** Get full archive */
106
+ getAll(): VersionHistory;
107
+ private save;
108
+ }
109
+ /**
110
+ * Detect versions for all loaded providers
111
+ */
112
+ declare function detectAllVersions(loader: ProviderLoader, archive?: VersionArchive): Promise<ProviderVersionInfo[]>;
113
+
114
+ /**
115
+ * ProviderLoader — Provider discovery + OS/version override resolution
116
+ *
117
+ * Role:
118
+ * 1. Load providers from upstream auto-download (~/.adhdev/providers/.upstream/)
119
+ * 2. Load user custom from ~/.adhdev/providers/ (overrides)
120
+ * 3. Apply OS/version overrides (process.platform + detected IDE version)
121
+ * 4. Hot-reload support (fs.watch)
122
+ *
123
+ * Design principles:
124
+ * - Load JS files via require() (CJS compatible)
125
+ * - User custom can override builtin
126
+ * - provider.js files are independent, so load order doesn't matter
127
+ */
128
+
129
+ declare class ProviderLoader {
130
+ private providers;
131
+ private userDir;
132
+ private upstreamDir;
133
+ private disableUpstream;
134
+ private watchers;
135
+ private logFn;
136
+ private versionArchive;
137
+ private scriptsCache;
138
+ /** Inject VersionArchive so resolve() can auto-detect installed versions */
139
+ setVersionArchive(archive: VersionArchive): void;
140
+ private static readonly GITHUB_TARBALL_URL;
141
+ private static readonly META_FILE;
142
+ constructor(options?: {
143
+ userDir?: string;
144
+ logFn?: (msg: string) => void;
145
+ /** Disable upstream auto-download (for dev/testing/OSS) */
146
+ disableUpstream?: boolean;
147
+ });
148
+ private log;
149
+ /**
150
+ * User override root (~/.adhdev/providers by default).
151
+ */
152
+ getUserDir(): string;
153
+ /**
154
+ * Auto-updated upstream root (~/.adhdev/providers/.upstream by default).
155
+ */
156
+ getUpstreamDir(): string;
157
+ /**
158
+ * Provider search order for on-disk lookups.
159
+ * Highest-priority editable overrides come first.
160
+ */
161
+ getProviderRoots(): string[];
162
+ /**
163
+ * Canonical provider directory shape for a given root.
164
+ */
165
+ getProviderDir(root: string, category: ProviderCategory, type: string): string;
166
+ /**
167
+ * Canonical user override directory for a provider.
168
+ */
169
+ getUserProviderDir(category: ProviderCategory, type: string): string;
170
+ /**
171
+ * Canonical upstream directory for a provider.
172
+ */
173
+ getUpstreamProviderDir(category: ProviderCategory, type: string): string;
174
+ /**
175
+ * Find the on-disk directory for a provider by type.
176
+ * Search order: user override → upstream.
177
+ */
178
+ findProviderDir(type: string): string | null;
179
+ /**
180
+ * Resolve a file within a provider directory.
181
+ */
182
+ resolveProviderFile(type: string, ...segments: string[]): string | null;
183
+ /**
184
+ * Load all providers (3-tier priority)
185
+ * 1. .upstream/ (GitHub auto-download — primary source)
186
+ * 2. User custom (~/.adhdev/providers/ excluding .upstream)
187
+ * User custom always wins (highest priority).
188
+ * If .upstream/ is empty, call fetchLatest() before loadAll().
189
+ */
190
+ loadAll(): void;
191
+ /**
192
+ * Check if upstream directory exists and has providers.
193
+ */
194
+ hasUpstream(): boolean;
195
+ /**
196
+ * Get raw provider metadata by type (NO scripts loaded).
197
+ * Use resolve() when you need scripts (readChat, listModels, etc).
198
+ * @deprecated Use getMeta() for metadata or resolve() for scripts.
199
+ */
200
+ get(type: string): ProviderModule | undefined;
201
+ /**
202
+ * Get raw provider metadata by type (NO scripts loaded).
203
+ * Safe for: category checks, icon, displayName, targetFilter, cdpPorts.
204
+ * NOT safe for: script execution (readChat, listModels, sendMessage).
205
+ * Use resolve() when scripts are needed.
206
+ */
207
+ getMeta(type: string): ProviderModule | undefined;
208
+ /**
209
+ * Resolve provider type by alias
210
+ * 'claude' → 'claude-cli', 'codex' → 'codex-cli' etc
211
+ * Returns input as-is if no match found.
212
+ */
213
+ resolveAlias(input: string): string;
214
+ /**
215
+ * Get provider with alias resolution (get + alias fallback)
216
+ */
217
+ getByAlias(input: string): ProviderModule | undefined;
218
+ /**
219
+ * Build CLI/ACP detection list (replaces cli-detector)
220
+ * Dynamically generated from provider.js spawn.command.
221
+ */
222
+ getCliDetectionList(): {
223
+ id: string;
224
+ displayName: string;
225
+ icon: string;
226
+ command: string;
227
+ category: string;
228
+ versionCommand?: string;
229
+ }[];
230
+ /**
231
+ * List providers by category
232
+ */
233
+ getByCategory(cat: ProviderCategory): ProviderModule[];
234
+ /**
235
+ * Extension Extension providers with extensionIdPattern only
236
+ * (used by discoverAgentWebviews in daemon-cdp.ts)
237
+ */
238
+ getExtensionProviders(): ProviderModule[];
239
+ /**
240
+ * All loaded providers
241
+ */
242
+ getAll(): ProviderModule[];
243
+ /**
244
+ * Check if a provider is enabled (per-IDE)
245
+ * Checks ideSettings[ideType].extensions[type].enabled.
246
+ * Default false (disabled) — user must explicitly enable.
247
+ * Always returns true when called without ideType.
248
+ */
249
+ isEnabled(type: string, ideType?: string): boolean;
250
+ /**
251
+ * Save IDE extension enabled setting
252
+ */
253
+ setIdeExtensionEnabled(ideType: string, extensionType: string, enabled: boolean): boolean;
254
+ /**
255
+ * Return only enabled providers by category (per-IDE)
256
+ */
257
+ getEnabledByCategory(cat: ProviderCategory, ideType?: string): ProviderModule[];
258
+ /**
259
+ * Extension Enabled extension providers with extensionIdPattern only (per-IDE)
260
+ */
261
+ getEnabledExtensionProviders(ideType?: string): ProviderModule[];
262
+ /**
263
+ * Return CDP port map for IDE providers
264
+ * Used by launch.ts, adhdev-daemon.ts
265
+ */
266
+ getCdpPortMap(): Record<string, [number, number]>;
267
+ /**
268
+ * Return IDE process name map (macOS)
269
+ */
270
+ getMacAppIdentifiers(): Record<string, string>;
271
+ /**
272
+ * Return IDE process name map (Windows)
273
+ */
274
+ getWinProcessNames(): Record<string, string[]>;
275
+ /**
276
+ * Available IDE types (only those with cdpPorts)
277
+ */
278
+ getAvailableIdeTypes(): string[];
279
+ /**
280
+ * Register IDE providers to core/detector registry
281
+ * → Enables detectIDEs() to detect provider.js-based IDEs
282
+ */
283
+ registerToDetector(): number;
284
+ /**
285
+ * Return final provider with OS/version overrides applied.
286
+ *
287
+ * Script resolution order:
288
+ * 1. compatibility array (new format — preferred)
289
+ * Provider.json defines: "compatibility": [{ "ideVersion": ">=1.107.0", "scriptDir": "scripts/1.107" }]
290
+ * First matching range wins. Fallback: defaultScriptDir.
291
+ * 2. versions field (legacy format — backward compat)
292
+ * "versions": { "< 1.107.0": { "__dir": "scripts/legacy" } }
293
+ * 3. Root scripts.js (original format — no versioning)
294
+ *
295
+ * Version source: context.version → VersionArchive → undefined
296
+ */
297
+ resolve(type: string, context?: {
298
+ os?: string;
299
+ version?: string;
300
+ }): ResolvedProvider | undefined;
301
+ /**
302
+ * Load scripts from a scriptDir within a provider directory.
303
+ * Tries scripts.js first, then individual .js files.
304
+ */
305
+ private loadScriptsFromDir;
306
+ /**
307
+ * Hot-reload: start watching for file changes
308
+ */
309
+ watch(): void;
310
+ /**
311
+ * Stop hot-reload
312
+ */
313
+ stopWatch(): void;
314
+ /**
315
+ * Full reload
316
+ */
317
+ reload(): void;
318
+ /**
319
+ * Download latest providers tarball from GitHub → extract to .upstream/
320
+ * - ETag-based change detection (skip if unchanged)
321
+ * - Never touches user custom files in ~/.adhdev/providers/
322
+ * - Runs in background; existing providers are kept on failure
323
+ *
324
+ * @returns Whether an update occurred
325
+ */
326
+ fetchLatest(): Promise<{
327
+ updated: boolean;
328
+ error?: string;
329
+ }>;
330
+ /** HTTP(S) file download (follows redirects) */
331
+ private downloadFile;
332
+ /** Recursive directory copy */
333
+ private copyDirRecursive;
334
+ /** .meta.json save */
335
+ private writeMeta;
336
+ /** Count provider files (provider.js or provider.json) */
337
+ private countProviders;
338
+ /**
339
+ * Get public settings schema for a provider (for dashboard UI rendering)
340
+ */
341
+ getPublicSettings(type: string): ProviderSettingSchema[];
342
+ /**
343
+ * Get public settings schema for all providers
344
+ */
345
+ getAllPublicSettings(): Record<string, ProviderSettingSchema[]>;
346
+ /**
347
+ * Resolved setting value for a provider (default + user override)
348
+ */
349
+ getSettingValue(type: string, key: string): any;
350
+ /**
351
+ * All resolved settings for a provider (default + user override)
352
+ */
353
+ getSettings(type: string): Record<string, any>;
354
+ /**
355
+ * Save provider setting value (writes to config.json)
356
+ */
357
+ setSetting(type: string, key: string, value: any): boolean;
358
+ /**
359
+ * Find the on-disk directory for a provider by type.
360
+ * Canonical shape: root/category/type.
361
+ */
362
+ private findProviderDirInternal;
363
+ /**
364
+ * Build a scripts function map from individual .js files in a directory.
365
+ * Each file is wrapped as: (params?) => fs.readFileSync(filePath, 'utf-8')
366
+ * (template substitution is NOT applied here — scripts.js handles that)
367
+ */
368
+ private buildScriptWrappersFromDir;
369
+ /**
370
+ * Recursively scan directory to load provider files
371
+ * Supports two formats:
372
+ * 1. provider.json (metadata) + scripts.js (optional CDP scripts)
373
+ * 2. provider.js (legacy — everything in one file)
374
+ * Structure: dir/category/agent-name/provider.{json,js}
375
+ */
376
+ private loadDir;
377
+ /**
378
+ * Simple semver range matching
379
+ * Supported formats: '>=4.0.0', '<3.0.0', '>=2.1.0'
380
+ */
381
+ private matchesVersion;
382
+ private compareVersions;
383
+ }
384
+
385
+ /**
386
+ * CLI AI Agent Detector
387
+ *
388
+ * Dynamic CLI detection based on Provider.
389
+ * Reads spawn.command from cli/acp categories via ProviderLoader to check installation.
390
+ *
391
+ * Uses parallel execution for fast detection across many providers.
392
+ */
393
+
394
+ interface CLIInfo {
395
+ id: string;
396
+ displayName: string;
397
+ icon: string;
398
+ command: string;
399
+ versionCommand?: string;
400
+ installed: boolean;
401
+ version?: string;
402
+ path?: string;
403
+ category?: string;
404
+ }
405
+ /**
406
+ * Detect all CLI/ACP agents (parallel)
407
+ * @param providerLoader ProviderLoader instance (dynamic list creation)
408
+ */
409
+ declare function detectCLIs(providerLoader?: ProviderLoader): Promise<CLIInfo[]>;
410
+
411
+ /**
412
+ * Host memory metrics — macOS-aware "available" memory.
413
+ *
414
+ * Node's os.freemem() on darwin reports only the tiny truly-free pool; most RAM
415
+ * sits in inactive/file-backed cache that the OS can reclaim. Dashboard "used %"
416
+ * based on (total - freemem) looks ~99% almost always — misleading.
417
+ *
418
+ * On macOS we parse `vm_stat` and approximate available bytes as:
419
+ * (free + inactive + speculative + purgeable [+ file_backed]) × page size
420
+ * (aligned with common Activity Monitor–style interpretations.)
421
+ */
422
+ interface HostMemorySnapshot {
423
+ totalMem: number;
424
+ /** Raw kernel "free" — small on macOS; kept for debugging / API compat */
425
+ freeMem: number;
426
+ /** Use this for UI "used %" — on darwin from vm_stat; else equals freeMem */
427
+ availableMem: number;
428
+ }
429
+ declare function getHostMemorySnapshot(): HostMemorySnapshot;
430
+
431
+ /**
432
+ * CDP Manager for ADHDev Daemon
433
+ *
434
+ * Ported cdp.ts from Extension for Daemon use.
435
+ * vscode dependencies removed — works in pure Node.js environment.
436
+ *
437
+ * Connects to IDE CDP port (9222, 9333 etc) to:
438
+ * - Execute JS via Runtime.evaluate
439
+ * - Agent webview iframe search & session connection
440
+ * - DOM query
441
+ */
442
+
443
+ interface CdpTarget {
444
+ id: string;
445
+ type: string;
446
+ title: string;
447
+ url: string;
448
+ webSocketDebuggerUrl: string;
449
+ }
450
+ interface AgentWebviewTarget {
451
+ targetId: string;
452
+ extensionId: string;
453
+ agentType: string;
454
+ url: string;
455
+ }
456
+ declare class DaemonCdpManager {
457
+ private ws;
458
+ private browserWs;
459
+ private browserMsgId;
460
+ private browserPending;
461
+ private msgId;
462
+ private pending;
463
+ private port;
464
+ private _connected;
465
+ private _browserConnected;
466
+ private targetUrl;
467
+ private reconnectTimer;
468
+ private contexts;
469
+ private connectPromise;
470
+ private failureCount;
471
+ private readonly MAX_FAILURES;
472
+ private agentSessions;
473
+ private logFn;
474
+ private extensionProviders;
475
+ private _lastDiscoverSig;
476
+ private _targetId;
477
+ private _pageTitle;
478
+ private _targetFilter;
479
+ private _lastDiscoveredTargets?;
480
+ constructor(port?: number, logFn?: (msg: string) => void, targetId?: string, targetFilter?: CdpTargetFilter);
481
+ /** Set target filter (can be updated after construction) */
482
+ setTargetFilter(filter: CdpTargetFilter): void;
483
+ /**
484
+ * Check if a page title should be excluded (non-main page).
485
+ * Uses provider-configured titleExcludes, falls back to default pattern.
486
+ */
487
+ private isNonMainTitle;
488
+ /**
489
+ * Check if a page URL matches the main window criteria.
490
+ * Uses provider-configured urlIncludes/urlExcludes.
491
+ */
492
+ private isMainPageUrl;
493
+ /** Connected page title (includes workspace name) */
494
+ get pageTitle(): string;
495
+ /** Connected target ID */
496
+ get targetId(): string | null;
497
+ /**
498
+ * Query all workbench pages on port (static)
499
+ * Returns multiple entries if multiple IDE windows are open on same port
500
+ */
501
+ static listAllTargets(port: number): Promise<CdpTarget[]>;
502
+ setPort(port: number): void;
503
+ getPort(): number;
504
+ private log;
505
+ connect(): Promise<boolean>;
506
+ private doConnect;
507
+ private findTargetOnPort;
508
+ private findTarget;
509
+ setExtensionProviders(providers: {
510
+ agentType: string;
511
+ extensionId: string;
512
+ extensionIdPattern: RegExp;
513
+ }[]): void;
514
+ private connectToTarget;
515
+ /** Browser-level CDP connection — needed for Target discovery */
516
+ private connectBrowserWs;
517
+ private getBrowserWsUrl;
518
+ private sendBrowser;
519
+ private scheduleReconnect;
520
+ disconnect(): void;
521
+ get isConnected(): boolean;
522
+ private sendInternal;
523
+ send(method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<any>;
524
+ sendCdpCommand(method: string, params?: Record<string, unknown>): Promise<any>;
525
+ evaluate(expression: string, timeoutMs?: number): Promise<unknown>;
526
+ querySelector(selector: string): Promise<string | null>;
527
+ /**
528
+ * Input text via CDP protocol then send Enter
529
+ * Used for editors where execCommand does not work (e.g. Lexical).
530
+ *
531
+ * 1. Find editor by selector, focus + click
532
+ * 2. Insert text via Input.insertText
533
+ * 3. Send Enter via Input.dispatchKeyEvent
534
+ */
535
+ typeAndSend(selector: string, text: string): Promise<boolean>;
536
+ /**
537
+ * Coordinate-based typeAndSend — for input fields inside webview iframe
538
+ * Receives coordinates directly instead of selector for click+input+Enter
539
+ */
540
+ typeAndSendAt(x: number, y: number, text: string): Promise<boolean>;
541
+ /**
542
+ * Evaluate JS from inside Webview iframe
543
+ * Kiro, PearAI etc Used for IDEs where chat UI is inside webview iframe.
544
+ *
545
+ * 1. Query Target.getTargets via browser WS → find vscode-webview iframes
546
+ * 2. Target.attachToTarget → session acquire
547
+ * 3. Page.getFrameTree → nested iframe find
548
+ * 4. Page.createIsolatedWorld → contextId acquire
549
+ * 5. Runtime.evaluate → result return
550
+ *
551
+ * @param expression JS expression to execute
552
+ * @param matchFn webview iframe URL match function (optional, all webview attempt)
553
+ * @returns evaluate result or null
554
+ */
555
+ evaluateInWebviewFrame(expression: string, matchFn?: (bodyPreview: string) => boolean): Promise<string | null>;
556
+ discoverAgentWebviews(): Promise<AgentWebviewTarget[]>;
557
+ attachToAgent(target: AgentWebviewTarget): Promise<string | null>;
558
+ evaluateInSession(sessionId: string, expression: string, timeoutMs?: number): Promise<unknown>;
559
+ /**
560
+ * Evaluate inside the child frame of an attached session.
561
+ * Extension webviews have a nested iframe structure:
562
+ * outer (vscode-webview://) → inner (extension React app)
563
+ * This method navigates into the inner frame using CDP Page.getFrameTree.
564
+ * Falls back to evaluateInSession if no child frame is found.
565
+ */
566
+ evaluateInSessionFrame(sessionId: string, expression: string, timeoutMs?: number): Promise<unknown>;
567
+ detachAgent(sessionId: string): Promise<void>;
568
+ detachAllAgents(): Promise<void>;
569
+ getAgentSessions(): Map<string, AgentWebviewTarget>;
570
+ private getCurrentPageWebviewUrls;
571
+ captureScreenshot(opts?: {
572
+ quality?: number;
573
+ }): Promise<Buffer | null>;
574
+ }
575
+
576
+ /**
577
+ * ProviderInstanceManager — lifecycle management for all ProviderInstances
578
+ *
579
+ * Role:
580
+ * 1. Instance create/delete
581
+ * 2. Tick engine (periodic onTick calls)
582
+ * 3. Collect overall state
583
+ * 4. Event collection and propagation
584
+ */
585
+
586
+ declare class ProviderInstanceManager {
587
+ private instances;
588
+ private tickTimer;
589
+ private tickInterval;
590
+ private eventListeners;
591
+ /**
592
+ * Instance add and initialize
593
+ */
594
+ addInstance(id: string, instance: ProviderInstance, context: InstanceContext): Promise<void>;
595
+ /**
596
+ * Instance remove
597
+ */
598
+ removeInstance(id: string): void;
599
+ /**
600
+ * Import by Instance ID
601
+ */
602
+ getInstance(id: string): ProviderInstance | undefined;
603
+ /**
604
+ * Per-category Instance list
605
+ */
606
+ getByCategory(category: 'cli' | 'ide' | 'extension' | 'acp'): ProviderInstance[];
607
+ /**
608
+ * All Instance count
609
+ */
610
+ get size(): number;
611
+ /**
612
+ * all Instance's current status collect
613
+ * + Propagate pending events to event listeners
614
+ */
615
+ collectAllStates(): ProviderState[];
616
+ /**
617
+ * Per-category status collect
618
+ */
619
+ collectStatesByCategory(category: 'cli' | 'ide' | 'extension' | 'acp'): ProviderState[];
620
+ /**
621
+ * Start tick — periodically call all Instance.onTick() call
622
+ */
623
+ startTicking(intervalMs?: number): void;
624
+ /**
625
+ * Stop tick
626
+ */
627
+ stopTicking(): void;
628
+ /**
629
+ * Register event listener (used for daemon status_event transmission)
630
+ */
631
+ onEvent(listener: (event: ProviderEvent & {
632
+ providerType: string;
633
+ }) => void): void;
634
+ /**
635
+ * Forward event to specific Instance
636
+ */
637
+ sendEvent(id: string, event: string, data?: any): void;
638
+ /**
639
+ * Broadcast event to all Instances
640
+ */
641
+ broadcast(event: string, data?: any): void;
642
+ /**
643
+ * Update settings for all instances of a given provider type.
644
+ * Called when user changes settings from dashboard.
645
+ */
646
+ updateInstanceSettings(providerType: string, settings: Record<string, any>): number;
647
+ /**
648
+ * All terminate
649
+ */
650
+ disposeAll(): void;
651
+ }
652
+
653
+ interface SessionRuntimeTarget {
654
+ sessionId: string;
655
+ parentSessionId: string | null;
656
+ providerType: string;
657
+ providerCategory: 'ide' | 'extension' | 'cli' | 'acp';
658
+ transport: SessionTransport;
659
+ cdpManagerKey?: string;
660
+ adapterKey?: string;
661
+ instanceKey?: string;
662
+ }
663
+ declare class SessionRegistry {
664
+ private readonly bySessionId;
665
+ private readonly byManagerKey;
666
+ private readonly byInstanceKey;
667
+ private readonly byParentSessionId;
668
+ register(target: SessionRuntimeTarget): void;
669
+ get(sessionId: string | undefined | null): SessionRuntimeTarget | undefined;
670
+ unregister(sessionId: string | undefined | null): void;
671
+ unregisterByManagerKey(managerKey: string): void;
672
+ unregisterByInstanceKey(instanceKey: string): void;
673
+ listChildren(parentSessionId: string): SessionRuntimeTarget[];
674
+ private addIndex;
675
+ private removeIndex;
676
+ }
677
+
678
+ /**
679
+ * Agent Stream Types — ported for Daemon (identical to original)
680
+ *
681
+ * Agent stream types.
682
+ * No vscode dependency — can be used as-is.
683
+ */
684
+ /** Agent chat message */
685
+ interface AgentChatMessage {
686
+ role: 'user' | 'assistant' | 'system';
687
+ content: string;
688
+ timestamp?: number;
689
+ }
690
+ /** Agent chat history item */
691
+ interface AgentChatListItem {
692
+ title: string;
693
+ id: string;
694
+ status?: string;
695
+ time?: string;
696
+ cost?: string;
697
+ }
698
+ /** Agent stream status */
699
+ interface AgentStreamState {
700
+ agentType: string;
701
+ agentName: string;
702
+ extensionId: string;
703
+ status: 'idle' | 'streaming' | 'waiting_approval' | 'error' | 'disconnected' | 'panel_hidden' | 'not_monitored';
704
+ messages: AgentChatMessage[];
705
+ inputContent: string;
706
+ model?: string;
707
+ mode?: string;
708
+ activeModal?: {
709
+ message: string;
710
+ buttons: string[];
711
+ };
712
+ }
713
+ /** Agent stream adapter interface */
714
+ interface IAgentStreamAdapter {
715
+ readonly agentType: string;
716
+ readonly agentName: string;
717
+ readonly extensionId: string;
718
+ readonly extensionIdPattern: RegExp;
719
+ readChat(evaluate: AgentEvaluateFn): Promise<AgentStreamState>;
720
+ sendMessage(evaluate: AgentEvaluateFn, text: string): Promise<void>;
721
+ resolveAction(evaluate: AgentEvaluateFn, action: string, button?: string): Promise<boolean>;
722
+ newSession(evaluate: AgentEvaluateFn): Promise<void>;
723
+ listChats?(evaluate: AgentEvaluateFn): Promise<AgentChatListItem[]>;
724
+ switchSession?(evaluate: AgentEvaluateFn, sessionId: string): Promise<boolean>;
725
+ focusEditor?(evaluate: AgentEvaluateFn): Promise<void>;
726
+ setProvider?(provider: any): void;
727
+ }
728
+ type AgentEvaluateFn = (expression: string, timeoutMs?: number) => Promise<unknown>;
729
+
730
+ /**
731
+ * DaemonAgentStreamManager — manage agent streams (ported for Daemon)
732
+ *
733
+ * Agent stream manager for extension data collection.
734
+ * All vscode dependencies removed — pure Node.js environment.
735
+ *
736
+ * Panel focus is delegated to Extension via IPC.
737
+ * CDP session management uses DaemonCdpManager directly.
738
+ */
739
+
740
+ interface ManagedAgent {
741
+ adapter: IAgentStreamAdapter;
742
+ runtimeSessionId: string;
743
+ parentSessionId: string;
744
+ cdpSessionId: string;
745
+ target: AgentWebviewTarget;
746
+ lastState: AgentStreamState | null;
747
+ lastError: string | null;
748
+ lastHiddenCheckTime: number;
749
+ }
750
+ declare class DaemonAgentStreamManager {
751
+ private readonly sessionRegistry?;
752
+ private adaptersByType;
753
+ private managedBySessionId;
754
+ private enabled;
755
+ private logFn;
756
+ private lastDiscoveryTimeByParent;
757
+ private discoveryIntervalMsByParent;
758
+ private activeSessionIdByParent;
759
+ constructor(logFn?: (msg: string) => void, providerLoader?: ProviderLoader, sessionRegistry?: SessionRegistry | undefined);
760
+ setEnabled(enabled: boolean): void;
761
+ get isEnabled(): boolean;
762
+ getActiveSessionId(parentSessionId: string): string | null;
763
+ private getSessionTarget;
764
+ resetParentSession(parentSessionId: string): void;
765
+ /** Panel focus based on provider.js focusPanel or extensionId (currently no-op) */
766
+ ensureSessionPanelOpen(_sessionId: string): Promise<void>;
767
+ setActiveSession(cdp: DaemonCdpManager, parentSessionId: string, sessionId: string | null): Promise<void>;
768
+ private resolveSessionIdForTarget;
769
+ private connectManagedSession;
770
+ /** Agent webview discovery + session connection */
771
+ syncActiveSession(cdp: DaemonCdpManager, parentSessionId: string): Promise<void>;
772
+ /** Collect active extension session state */
773
+ collectActiveSession(cdp: DaemonCdpManager, parentSessionId: string): Promise<AgentStreamState | null>;
774
+ sendToSession(cdp: DaemonCdpManager, sessionId: string, text: string): Promise<boolean>;
775
+ resolveSessionAction(cdp: DaemonCdpManager, sessionId: string, action: 'approve' | 'reject'): Promise<boolean>;
776
+ newSession(cdp: DaemonCdpManager, sessionId: string): Promise<boolean>;
777
+ listSessionChats(cdp: DaemonCdpManager, sessionId: string): Promise<AgentChatListItem[]>;
778
+ switchConversation(cdp: DaemonCdpManager, sessionId: string, conversationId: string): Promise<boolean>;
779
+ focusSession(cdp: DaemonCdpManager, sessionId: string): Promise<boolean>;
780
+ getConnectedSessions(parentSessionId?: string): string[];
781
+ getManagedSession(sessionId: string): ManagedAgent | undefined;
782
+ dispose(cdpManagers: Map<string, DaemonCdpManager>): Promise<void>;
783
+ resolveSessionForAgent(parentSessionId: string, agentType: string): string | null;
784
+ }
785
+
786
+ /**
787
+ * AgentStreamPoller — Periodic agent stream polling + extension dynamic management
788
+ *
789
+ * Handles periodic agent stream polling and extension dynamic management.
790
+ *
791
+ * Responsibilities:
792
+ * 1. Refresh extension providers in CDP managers (config changes take effect immediately)
793
+ * 2. Dynamically add/remove IDE instance extensions based on enabled state
794
+ * 3. Sync agent sessions + collect agent streams
795
+ * 4. Auto-discover agents in connected IDEs
796
+ */
797
+
798
+ interface AgentStreamPollerDeps {
799
+ agentStreamManager: DaemonAgentStreamManager;
800
+ providerLoader: ProviderLoader;
801
+ instanceManager: ProviderInstanceManager;
802
+ cdpManagers: Map<string, DaemonCdpManager>;
803
+ sessionRegistry: SessionRegistry;
804
+ /** Callback when agent streams are updated */
805
+ onStreamsUpdated?: (ideType: string, streams: AgentStreamState[]) => void;
806
+ }
807
+ declare class AgentStreamPoller {
808
+ private deps;
809
+ private timer;
810
+ constructor(deps: AgentStreamPollerDeps);
811
+ /** Currently active IDE type for agent streaming */
812
+ get activeIde(): string | null;
813
+ /** Reset active IDE tracking (e.g., when IDE is stopped) */
814
+ resetActiveIde(parentSessionId: string): void;
815
+ /** Start polling (idempotent — ignored if already started) */
816
+ start(intervalMs?: number): void;
817
+ /** Stop polling */
818
+ stop(): void;
819
+ /** Single poll tick — can also be called manually */
820
+ private tick;
821
+ }
822
+
823
+ /**
824
+ * Chat History Persistence — Persist completed chat messages to local disk
825
+ *
826
+ * Design:
827
+ * - ~/.adhdev/history/{agentType}/YYYY-MM-DD.jsonl
828
+ * - JSONL format (one line = one message, append-friendly)
829
+ * - Track only new messages (hash comparison with previous)
830
+ * - Auto-rotation (delete files older than 30 days)
831
+ * - Async/non-blocking (no impact on chat collection)
832
+ */
833
+ interface HistoryMessage {
834
+ ts: string;
835
+ receivedAt: number;
836
+ role: 'user' | 'assistant' | 'system';
837
+ content: string;
838
+ agent: string;
839
+ instanceId?: string;
840
+ sessionTitle?: string;
841
+ }
842
+ declare class ChatHistoryWriter {
843
+ /** Last seen message count per agent (deduplication) */
844
+ private lastSeenCounts;
845
+ /** Last seen message hash per agent (deduplication) */
846
+ private lastSeenHashes;
847
+ /** Last seen append-only terminal transcript per agent */
848
+ private lastSeenTerminal;
849
+ private rotated;
850
+ /**
851
+ * Append new messages to history
852
+ *
853
+ * @param agentType agent type (e.g. 'antigravity', 'cursor')
854
+ * @param messages Message array received from readChat
855
+ * @param sessionTitle Current session title
856
+ * @param instanceId IDE instance UUID (distinguishes windows of the same agent)
857
+ */
858
+ appendNewMessages(agentType: string, messages: Array<{
859
+ role: string;
860
+ content: string;
861
+ receivedAt?: number;
862
+ }>, sessionTitle?: string, instanceId?: string): void;
863
+ appendTerminalHistory(agentType: string, terminalHistory: string, sessionTitle?: string, instanceId?: string): void;
864
+ /** Called when agent session is explicitly changed */
865
+ onSessionChange(agentType: string): void;
866
+ /** Delete history files older than 30 days */
867
+ private rotateOldFiles;
868
+ /** Allow only filename-safe characters */
869
+ private sanitize;
870
+ }
871
+ /**
872
+ * Read history (static — called from P2P commands)
873
+ *
874
+ * Read JSONL files in reverse order, returning most recent messages first.
875
+ * When instanceId is specified, reads only that instance file.
876
+ * Offset/limit-based paging.
877
+ */
878
+ declare function readChatHistory(agentType: string, offset?: number, limit?: number, instanceId?: string): {
879
+ messages: HistoryMessage[];
880
+ hasMore: boolean;
881
+ };
882
+
883
+ /**
884
+ * DaemonCommandHandler — unified command routing for CDP & CLI
885
+ *
886
+ * Routes incoming commands (from server WS, P2P, or local WS) to
887
+ * the correct CDP manager or CLI adapter.
888
+ *
889
+ * Key concepts:
890
+ * - extractIdeType(): determines target IDE from targetSessionId or ideType
891
+ * - getCdp(): returns the DaemonCdpManager for current command
892
+ * - getProvider(): returns the ProviderModule for current command
893
+ * - handle(): main entry point, sets context then dispatches
894
+ */
895
+
896
+ interface CommandResult$1 {
897
+ success: boolean;
898
+ [key: string]: unknown;
899
+ }
900
+ interface CommandContext {
901
+ cdpManagers: Map<string, DaemonCdpManager>;
902
+ ideType: string;
903
+ adapters: Map<string, any>;
904
+ providerLoader?: ProviderLoader;
905
+ /** ProviderInstanceManager — for runtime settings propagation */
906
+ instanceManager?: ProviderInstanceManager;
907
+ sessionRegistry?: SessionRegistry;
908
+ }
909
+ /**
910
+ * Shared helpers interface — passed to sub-module command functions
911
+ * for accessing CDP, providers, agent streams, and other handler-owned state.
912
+ */
913
+ interface CommandHelpers {
914
+ getCdp(ideType?: string): DaemonCdpManager | null;
915
+ getProvider(overrideType?: string): ProviderModule | undefined;
916
+ getProviderScript(scriptName: string, params?: Record<string, string>, ideType?: string): string | null;
917
+ evaluateProviderScript(scriptName: string, params?: Record<string, string>, timeout?: number): Promise<{
918
+ result: any;
919
+ category: string;
920
+ } | null>;
921
+ getCliAdapter(type?: string): any | null;
922
+ readonly currentManagerKey: string | undefined;
923
+ readonly currentIdeType: string | undefined;
924
+ readonly currentProviderType: string | undefined;
925
+ readonly currentSession: SessionRuntimeTarget | undefined;
926
+ readonly agentStream: DaemonAgentStreamManager | null;
927
+ readonly ctx: CommandContext;
928
+ readonly historyWriter: ChatHistoryWriter;
929
+ }
930
+ declare class DaemonCommandHandler implements CommandHelpers {
931
+ private _ctx;
932
+ private _agentStream;
933
+ private domHandlers;
934
+ private _historyWriter;
935
+ /** Current request route context */
936
+ private _currentRoute;
937
+ constructor(ctx: CommandContext);
938
+ get ctx(): CommandContext;
939
+ get agentStream(): DaemonAgentStreamManager | null;
940
+ get historyWriter(): ChatHistoryWriter;
941
+ get currentManagerKey(): string | undefined;
942
+ get currentIdeType(): string | undefined;
943
+ get currentProviderType(): string | undefined;
944
+ get currentSession(): SessionRuntimeTarget | undefined;
945
+ /** Get CDP manager for a specific session or manager key. */
946
+ getCdp(ideType?: string): DaemonCdpManager | null;
947
+ /**
948
+ * Get provider module — _currentProviderType (agentType priority) use.
949
+ */
950
+ getProvider(overrideType?: string): ProviderModule | undefined;
951
+ /** Get a provider script by name from ProviderLoader. */
952
+ getProviderScript(scriptName: string, params?: Record<string, string>, ideType?: string): string | null;
953
+ /**
954
+ * per-category CDP script execute:
955
+ * IDE → cdp.evaluate(script) (main window)
956
+ * Extension → cdp.evaluateInSession(sessionId, script) (webview)
957
+ */
958
+ evaluateProviderScript(scriptName: string, params?: Record<string, string>, timeout?: number): Promise<{
959
+ result: any;
960
+ category: string;
961
+ } | null>;
962
+ /** CLI adapter search */
963
+ getCliAdapter(type?: string): any | null;
964
+ private inferProviderType;
965
+ private resolveRoute;
966
+ /** Extract CDP scope key from target session or explicit ideType */
967
+ private extractIdeType;
968
+ setAgentStreamManager(manager: DaemonAgentStreamManager): void;
969
+ handle(cmd: string, args: any): Promise<CommandResult$1>;
970
+ private dispatch;
971
+ private handleGetRecentWorkspaces;
972
+ private handleRefreshScripts;
973
+ private proxyDevServerPost;
974
+ private proxyDevServerGet;
975
+ private proxyDevServerScaffold;
976
+ }
977
+
978
+ /**
979
+ * CDP DOM Analysis Tools — DOM dump, query, debug
980
+ *
981
+ * Separated from daemon-commands.ts.
982
+ * Tools for analyzing DOM structure when developing new IDE scripts.
983
+ */
984
+
985
+ type CdpGetter = (ideType?: string) => DaemonCdpManager | null;
986
+ /**
987
+ * CDP DOM analysis handler
988
+ *
989
+ * Uses getCdp from DaemonCommandHandler.
990
+ */
991
+ declare class CdpDomHandlers {
992
+ private getCdp;
993
+ constructor(getCdp: CdpGetter);
994
+ /**
995
+ * CDP DOM Dump — IDE's DOM tree retrieve
996
+ *
997
+ * args:
998
+ * selector?: string — CSS selector to dump specific area only (default: All)
999
+ * depth?: number — Dump depth limit (default: 10)
1000
+ * attrs?: boolean — Whether to include properties (default: true)
1001
+ * maxLength?: number — Max character count (default: 200000)
1002
+ * format?: 'html' | 'tree' | 'summary' — Output format (default: 'html')
1003
+ * sessionId?: string — Agent webview session ID (if provided, match webview DOM)
1004
+ */
1005
+ handleDomDump(args: any): Promise<CommandResult$1>;
1006
+ /**
1007
+ * CDP DOM Query — CSS Test selector
1008
+ * Check how many elements match selector and what elements they are
1009
+ *
1010
+ * args:
1011
+ * selector: string — CSS selector
1012
+ * limit?: number — Max element count to return (default: 20)
1013
+ * content?: boolean — Whether to include text content (default: true)
1014
+ * sessionId?: string — agent webview session ID
1015
+ */
1016
+ handleDomQuery(args: any): Promise<CommandResult$1>;
1017
+ /**
1018
+ * CDP DOM Debug — IDE AI panel specialized analysis
1019
+ * Collect all essential info at once when supporting new IDE
1020
+ *
1021
+ * args:
1022
+ * ideType?: string — IDE type hint
1023
+ * sessionId?: string — agent webview session ID
1024
+ */
1025
+ handleDomDebug(args: any): Promise<CommandResult$1>;
1026
+ }
1027
+
1028
+ /**
1029
+ * ExtensionProviderInstance — Runtime instance for Extension Provider
1030
+ *
1031
+ * Manages IDE extensions (Cline, Roo Code, etc).
1032
+ * CDP webview discovery + agent stream collection moved here.
1033
+ */
1034
+
1035
+ declare class ExtensionProviderInstance implements ProviderInstance {
1036
+ readonly type: string;
1037
+ readonly category: "extension";
1038
+ private provider;
1039
+ private context;
1040
+ private settings;
1041
+ private events;
1042
+ private currentStatus;
1043
+ private agentStreams;
1044
+ private messages;
1045
+ private activeModal;
1046
+ private currentModel;
1047
+ private currentMode;
1048
+ private lastAgentStatus;
1049
+ private generatingStartedAt;
1050
+ private monitor;
1051
+ private instanceId;
1052
+ private ideType;
1053
+ constructor(provider: ProviderModule);
1054
+ init(context: InstanceContext): Promise<void>;
1055
+ onTick(): Promise<void>;
1056
+ getState(): ProviderState;
1057
+ onEvent(event: string, data?: any): void;
1058
+ dispose(): void;
1059
+ /** Query UUID instanceId */
1060
+ getInstanceId(): string;
1061
+ private detectTransition;
1062
+ private pushEvent;
1063
+ private flushEvents;
1064
+ }
1065
+
1066
+ /**
1067
+ * IdeProviderInstance — Runtime instance for IDE Provider
1068
+ *
1069
+ * Within a single IDE:
1070
+ * 1. Native chat (readChat via CDP)
1071
+ * 2. Extension agents (Cline, Roo Code etc)
1072
+ *
1073
+ * IDE Instance manages child Extension Instances.
1074
+ * Daemon collects all via a single IDE Instance.getState() call.
1075
+ */
1076
+
1077
+ declare class IdeProviderInstance implements ProviderInstance {
1078
+ readonly type: string;
1079
+ readonly category: "ide";
1080
+ private provider;
1081
+ private context;
1082
+ private settings;
1083
+ private events;
1084
+ private tickErrorCount;
1085
+ private cachedChat;
1086
+ private currentStatus;
1087
+ private lastAgentStatuses;
1088
+ private generatingStartedAt;
1089
+ private tickBusy;
1090
+ private monitor;
1091
+ private historyWriter;
1092
+ private autoApproveBusy;
1093
+ private ideVersion;
1094
+ private instanceId;
1095
+ private workspace;
1096
+ private extensions;
1097
+ constructor(provider: ProviderModule, instanceKey?: string);
1098
+ init(context: InstanceContext): Promise<void>;
1099
+ onTick(): Promise<void>;
1100
+ getState(): ProviderState;
1101
+ onEvent(event: string, data?: any): void;
1102
+ dispose(): void;
1103
+ /** Extension Instance add */
1104
+ addExtension(provider: ProviderModule, settings?: Record<string, any>): Promise<void>;
1105
+ /** Extension Instance remove */
1106
+ removeExtension(type: string): void;
1107
+ /** Extension Instance Import */
1108
+ getExtension(type: string): ExtensionProviderInstance | undefined;
1109
+ /** Child Extension list */
1110
+ getExtensionTypes(): string[];
1111
+ /** Query UUID instanceId */
1112
+ getInstanceId(): string;
1113
+ /** all Extension Instance list */
1114
+ getExtensionInstances(): ExtensionProviderInstance[];
1115
+ /** Set workspace from daemon launch context */
1116
+ setWorkspace(workspace: string): void;
1117
+ private readChat;
1118
+ private getReadChatScript;
1119
+ private detectAgentTransitions;
1120
+ private pushEvent;
1121
+ private flushEvents;
1122
+ updateCdp(cdp: InstanceContext['cdp']): void;
1123
+ private autoApproveViaScript;
1124
+ }
1125
+
1126
+ /**
1127
+ * DaemonCdpSetup — Shared CDP initialization helpers
1128
+ *
1129
+ * Common CDP setup logic for consistent
1130
+ * CDP → ProviderInstance registration.
1131
+ */
1132
+
1133
+ interface CdpSetupContext {
1134
+ providerLoader: ProviderLoader;
1135
+ instanceManager: ProviderInstanceManager;
1136
+ cdpManagers: Map<string, DaemonCdpManager>;
1137
+ sessionRegistry: SessionRegistry;
1138
+ /** Server connection (optional) */
1139
+ serverConn?: any;
1140
+ }
1141
+ interface SetupIdeInstanceOptions {
1142
+ /** Provider-based IDE type (e.g., 'antigravity', 'cursor') */
1143
+ ideType: string;
1144
+ /** Connected CDP manager */
1145
+ manager: DaemonCdpManager;
1146
+ /** CDP manager key (for multi-window: 'antigravity_remote_vs', single: 'antigravity') */
1147
+ managerKey?: string;
1148
+ /** Provider settings override */
1149
+ settings?: Record<string, any>;
1150
+ }
1151
+ /**
1152
+ * Register extension providers on a CDP manager.
1153
+ * Common pattern used during CDP init and periodic scans.
1154
+ */
1155
+ declare function registerExtensionProviders(providerLoader: ProviderLoader, manager: DaemonCdpManager, ideType: string): void;
1156
+ /**
1157
+ * Setup a CDP-connected IDE as a ProviderInstance.
1158
+ *
1159
+ * Performs:
1160
+ * 1. providerLoader.resolve() to get scripts
1161
+ * 2. Create IdeProviderInstance
1162
+ * 3. Register in InstanceManager
1163
+ * 4. Register enabled extensions
1164
+ * 5. Register runtime sessions (workspace + extension children)
1165
+ *
1166
+ * @returns The created IdeProviderInstance, or null if provider not found
1167
+ */
1168
+ declare function setupIdeInstance(ctx: CdpSetupContext, opts: SetupIdeInstanceOptions): Promise<IdeProviderInstance | null>;
1169
+ /**
1170
+ * Create and connect a DaemonCdpManager for a given port.
1171
+ *
1172
+ * @returns Connected manager or null if connection failed
1173
+ */
1174
+ declare function connectCdpManager(port: number, ideType: string, logFn: (msg: string) => void, providerLoader: ProviderLoader, targetId?: string): Promise<DaemonCdpManager | null>;
1175
+ /**
1176
+ * Probe a CDP port to check if it's listening.
1177
+ * @returns true if CDP is available on this port
1178
+ */
1179
+ declare function probeCdpPort(port: number, timeoutMs?: number): Promise<boolean>;
1180
+
1181
+ /**
1182
+ * DaemonCdpScanner — Periodic CDP port scanning & auto-connect
1183
+ *
1184
+ * Periodic CDP port scanning and auto-connect for IDE discovery.
1185
+ * Provides a unified approach to:
1186
+ * 1. Initial CDP port discovery
1187
+ * 2. Periodic scanning for newly launched IDEs
1188
+ * 3. Multi-window support (multiple pages on same port)
1189
+ */
1190
+
1191
+ interface CdpScannerOptions {
1192
+ /** Context for setup operations */
1193
+ ctx: CdpSetupContext;
1194
+ /** Log function for per-IDE CDP logs */
1195
+ logFn?: (ideType: string) => (msg: string) => void;
1196
+ /** Whether to support multi-window (multiple pages per port) */
1197
+ multiWindow?: boolean;
1198
+ /** Scan interval in ms (default: 30000) */
1199
+ scanIntervalMs?: number;
1200
+ /** Callback when a new CDP connection is established */
1201
+ onConnected?: (ideType: string, managerKey: string, manager: DaemonCdpManager) => void;
1202
+ }
1203
+ declare class DaemonCdpScanner {
1204
+ private ctx;
1205
+ private opts;
1206
+ private scanTimer;
1207
+ private discoveryTimer;
1208
+ constructor(opts: CdpScannerOptions);
1209
+ /**
1210
+ * Initial CDP discovery — connect to all available IDEs.
1211
+ * Supports both single-window and multi-window modes.
1212
+ */
1213
+ initialScan(enabledIdes?: string[]): Promise<void>;
1214
+ /**
1215
+ * Start periodic scanning for newly launched IDEs.
1216
+ */
1217
+ startPeriodicScan(): void;
1218
+ /**
1219
+ * Start periodic agent webview discovery on all connected CDPs.
1220
+ */
1221
+ startWebviewDiscovery(intervalMs?: number): void;
1222
+ /**
1223
+ * Stop all timers.
1224
+ */
1225
+ stop(): void;
1226
+ private getLogFn;
1227
+ /**
1228
+ * Single-window connection (standalone mode).
1229
+ * One CDP manager per IDE, first working port wins.
1230
+ */
1231
+ private connectSingleWindow;
1232
+ /**
1233
+ * Multi-window connection.
1234
+ * Multiple CDP managers per IDE — one per workbench page.
1235
+ */
1236
+ private connectMultiWindow;
1237
+ }
1238
+
1239
+ /**
1240
+ * DaemonCdpInitializer — Unified CDP initialization + periodic scanning
1241
+ *
1242
+ * Unified CDP initialization + periodic scanning.
1243
+ *
1244
+ * Features:
1245
+ * 1. Initial connection: connectAll() — multi-window aware
1246
+ * 2. Periodic scan: startPeriodicScan() — auto-detect newly opened IDEs
1247
+ * 3. Discovery: startDiscovery() — periodic agent webview discovery
1248
+ */
1249
+
1250
+ interface CdpInitializerConfig {
1251
+ providerLoader: ProviderLoader;
1252
+ cdpManagers: Map<string, DaemonCdpManager>;
1253
+ /** Filter: only connect these IDEs (empty/undefined = all) */
1254
+ enabledIdes?: string[];
1255
+ /** Callback when a new CDP manager is connected */
1256
+ onConnected?: (ideType: string, manager: DaemonCdpManager, managerKey: string) => void | Promise<void>;
1257
+ /** Callback when a stale/disconnected CDP manager is removed */
1258
+ onDisconnected?: (ideType: string, manager: DaemonCdpManager, managerKey: string, reason: 'ide_closed' | 'target_closed' | 'target_rekeyed') => void | Promise<void>;
1259
+ }
1260
+ declare class DaemonCdpInitializer {
1261
+ private config;
1262
+ private scanTimer;
1263
+ private discoveryTimer;
1264
+ constructor(config: CdpInitializerConfig);
1265
+ /**
1266
+ * Connect to all detected IDEs.
1267
+ * Multi-window aware: creates separate CdpManager per workbench page.
1268
+ */
1269
+ connectAll(detectedIdes: any[]): Promise<void>;
1270
+ /**
1271
+ * Connect to a single IDE port.
1272
+ * Tries multi-window first (listAllTargets), falls back to direct connect.
1273
+ */
1274
+ private connectIdePort;
1275
+ private pruneStaleManagers;
1276
+ /**
1277
+ * Start periodic scanning for newly opened IDEs.
1278
+ * Idempotent — ignored if already started.
1279
+ */
1280
+ startPeriodicScan(intervalMs?: number): void;
1281
+ /**
1282
+ * Start periodic agent webview discovery.
1283
+ */
1284
+ startDiscovery(intervalMs?: number): void;
1285
+ /** Stop all timers */
1286
+ stop(): void;
1287
+ }
1288
+
1289
+ /**
1290
+ * CliAdapter — common interface for CLI agents
1291
+ *
1292
+ * Contract implemented by all CLI adapters (ProviderCliAdapter etc).
1293
+ */
1294
+ interface CliAdapter {
1295
+ cliType: string;
1296
+ cliName: string;
1297
+ workingDir: string;
1298
+ spawn(): Promise<void>;
1299
+ sendMessage(text: string): Promise<void>;
1300
+ getStatus(): any;
1301
+ getPartialResponse(): string;
1302
+ shutdown(): void;
1303
+ cancel(): void;
1304
+ isProcessing(): boolean;
1305
+ isReady(): boolean;
1306
+ setOnStatusChange(callback: () => void): void;
1307
+ setServerConn?(serverConn: any): void;
1308
+ setOnPtyData?(callback: (data: string) => void): void;
1309
+ writeRaw?(data: string): void;
1310
+ resize?(cols: number, rows: number): void;
1311
+ }
1312
+
1313
+ /**
1314
+ * DaemonCliManager — CLI session creation, management, and command handling
1315
+ *
1316
+ * Separated from adhdev-daemon.ts.
1317
+ * CLI cases of createAdapter, startCliSession, stopCliSession, executeDaemonCommand extracted to independent module extract.
1318
+ */
1319
+
1320
+ interface CliManagerDeps {
1321
+ /** Server connection — injected into adapter */
1322
+ getServerConn(): any | null;
1323
+ /** P2P — PTY output transmit */
1324
+ getP2p(): {
1325
+ broadcastPtyOutput(key: string, data: string): void;
1326
+ } | null;
1327
+ /** StatusReporter callback */
1328
+ onStatusChange(): void;
1329
+ removeAgentTracking(key: string): void;
1330
+ /** InstanceManager — register in CLI unified status */
1331
+ getInstanceManager(): ProviderInstanceManager | null;
1332
+ getSessionRegistry?(): SessionRegistry | null;
1333
+ }
1334
+ type CommandResult = {
1335
+ success: boolean;
1336
+ [key: string]: unknown;
1337
+ };
1338
+ declare class DaemonCliManager {
1339
+ readonly adapters: Map<string, CliAdapter>;
1340
+ private deps;
1341
+ private providerLoader;
1342
+ constructor(deps: CliManagerDeps, providerLoader: ProviderLoader);
1343
+ getCliKey(cliType: string, dir: string): string;
1344
+ private persistRecentDir;
1345
+ private createAdapter;
1346
+ startSession(cliType: string, workingDir: string, cliArgs?: string[], initialModel?: string): Promise<void>;
1347
+ stopSession(key: string): Promise<void>;
1348
+ shutdownAll(): void;
1349
+ /**
1350
+ * Search for CLI adapter. Priority order:
1351
+ * 0. sessionId (UUID direct match)
1352
+ * 1. agentType + dir (iteration match)
1353
+ * 2. agentType fuzzy match (⚠ returns first match when multiple sessions exist)
1354
+ */
1355
+ findAdapter(agentType: string, opts?: {
1356
+ dir?: string;
1357
+ instanceKey?: string;
1358
+ }): {
1359
+ adapter: CliAdapter;
1360
+ key: string;
1361
+ } | null;
1362
+ handleCliCommand(cmd: string, args: any): Promise<CommandResult | null>;
1363
+ }
1364
+
1365
+ /**
1366
+ * DaemonCommandRouter — Unified command routing for daemon-level commands
1367
+ *
1368
+ * Unified command routing for daemon-level commands.
1369
+ *
1370
+ * Routing flow:
1371
+ * 1. Daemon-level commands (launch_ide, stop_ide, restart_ide, etc.) → handled here
1372
+ * 2. CLI/ACP commands → delegated to cliManager
1373
+ * 3. Everything else → delegated to commandHandler.handle()
1374
+ */
1375
+
1376
+ interface CommandRouterDeps {
1377
+ commandHandler: DaemonCommandHandler;
1378
+ cliManager: DaemonCliManager;
1379
+ cdpManagers: Map<string, DaemonCdpManager>;
1380
+ providerLoader: ProviderLoader;
1381
+ instanceManager: ProviderInstanceManager;
1382
+ /** Reference to detected IDEs array (mutable — router updates it) */
1383
+ detectedIdes: {
1384
+ value: any[];
1385
+ };
1386
+ sessionRegistry: SessionRegistry;
1387
+ /** Callback for CDP manager creation after launch_ide */
1388
+ onCdpManagerCreated?: (ideType: string, manager: DaemonCdpManager) => void;
1389
+ /** Callback after IDE connected (e.g., startAgentStreamPolling) */
1390
+ onIdeConnected?: () => void;
1391
+ /** Callback after status change (stop_ide, restart) */
1392
+ onStatusChange?: () => void;
1393
+ /** Callback after chat-related commands */
1394
+ onPostChatCommand?: () => void;
1395
+ /** Get a connected CDP manager (for agent stream reset check) */
1396
+ getCdpLogFn?: (ideType: string) => (msg: string) => void;
1397
+ /** Package name for upgrade detection ('adhdev' or '@adhdev/daemon-standalone') */
1398
+ packageName?: string;
1399
+ }
1400
+ interface CommandRouterResult {
1401
+ success: boolean;
1402
+ [key: string]: unknown;
1403
+ }
1404
+ declare class DaemonCommandRouter {
1405
+ private deps;
1406
+ constructor(deps: CommandRouterDeps);
1407
+ /**
1408
+ * Unified command routing.
1409
+ * Returns result for all commands:
1410
+ * 1. Daemon-level commands (launch_ide, stop_ide, etc.)
1411
+ * 2. CLI commands (launch_cli, stop_cli, agent_command)
1412
+ * 3. DaemonCommandHandler delegation (CDP/agent-stream/file commands)
1413
+ *
1414
+ * @param cmd Command name
1415
+ * @param args Command arguments
1416
+ * @param source Log source ('ws' | 'p2p' | 'standalone' | etc.)
1417
+ */
1418
+ execute(cmd: string, args: any, source?: string): Promise<CommandRouterResult>;
1419
+ /**
1420
+ * Daemon-level command execution (IDE start/stop/restart, CLI, detect, logs).
1421
+ * Returns null if not handled at this level → caller delegates to CommandHandler.
1422
+ */
1423
+ private executeDaemonCommand;
1424
+ /**
1425
+ * IDE stop: CDP disconnect + InstanceManager cleanup + optionally kill OS process
1426
+ */
1427
+ private stopIde;
1428
+ }
1429
+
1430
+ /**
1431
+ * DaemonStatusReporter — status collect & transmit (StatusReport / P2P / StatusEvent)
1432
+ *
1433
+ * Collect status from ProviderInstanceManager → assemble payload → transmit
1434
+ * Each Instance manages its own status/transition. This module only assembles + transmits.
1435
+ */
1436
+
1437
+ interface StatusReporterDeps {
1438
+ serverConn: {
1439
+ isConnected(): boolean;
1440
+ sendMessage(type: string, data: any): void;
1441
+ getUserPlan(): string;
1442
+ } | null;
1443
+ cdpManagers: Map<string, {
1444
+ isConnected: boolean;
1445
+ }>;
1446
+ p2p: {
1447
+ isConnected: boolean;
1448
+ isAvailable: boolean;
1449
+ connectionState: string;
1450
+ connectedPeerCount: number;
1451
+ screenshotActive: boolean;
1452
+ sendStatus(data: any): void;
1453
+ } | null;
1454
+ providerLoader: {
1455
+ resolve(type: string): any;
1456
+ getAll(): any[];
1457
+ };
1458
+ detectedIdes: any[];
1459
+ instanceId: string;
1460
+ daemonVersion?: string;
1461
+ instanceManager: {
1462
+ collectAllStates(): ProviderState[];
1463
+ collectStatesByCategory(cat: string): ProviderState[];
1464
+ };
1465
+ getScreenshotUsage?: () => {
1466
+ dailyUsedMinutes: number;
1467
+ dailyBudgetMinutes: number;
1468
+ budgetExhausted: boolean;
1469
+ } | null;
1470
+ }
1471
+ declare class DaemonStatusReporter {
1472
+ private deps;
1473
+ private log;
1474
+ private lastStatusSentAt;
1475
+ private statusPendingThrottle;
1476
+ private lastP2PStatusHash;
1477
+ private lastStatusSummary;
1478
+ private statusTimer;
1479
+ private p2pTimer;
1480
+ constructor(deps: StatusReporterDeps, opts?: {
1481
+ logFn?: (msg: string) => void;
1482
+ });
1483
+ startReporting(): void;
1484
+ stopReporting(): void;
1485
+ onStatusChange(): void;
1486
+ throttledReport(): void;
1487
+ emitStatusEvent(event: Record<string, unknown>): void;
1488
+ removeAgentTracking(_key: string): void;
1489
+ updateAgentStreams(_ideType: string, _streams: any[]): void;
1490
+ /** Reset P2P dedup hash — forces next send to transmit even if content unchanged */
1491
+ resetP2PHash(): void;
1492
+ private ts;
1493
+ sendUnifiedStatusReport(opts?: {
1494
+ p2pOnly?: boolean;
1495
+ }): Promise<void>;
1496
+ private sendP2PPayload;
1497
+ private simpleHash;
1498
+ }
1499
+
1500
+ /**
1501
+ * Status Builders — shared conversion functions for ProviderState → ManagedEntry
1502
+ *
1503
+ * Used by:
1504
+ * - daemon-standalone (StandaloneServer.getStatus)
1505
+ * - DaemonStatusReporter
1506
+ *
1507
+ * Consolidates ProviderState→ManagedEntry mapping logic.
1508
+ */
1509
+
1510
+ /**
1511
+ * Find a CDP manager by key, with prefix matching for multi-window support.
1512
+ *
1513
+ * Lookup order:
1514
+ * 1. Exact match: cdpManagers.get(key)
1515
+ * 2. Prefix match: key starts with `${ideType}_` (multi-window: "cursor_remote_vs")
1516
+ * 3. null
1517
+ *
1518
+ * This replaces raw `cdpManagers.get(ideType)` calls that broke when
1519
+ * multi-window keys like "cursor_remote_vs" were used.
1520
+ */
1521
+ declare function findCdpManager(cdpManagers: Map<string, DaemonCdpManager>, key: string): DaemonCdpManager | null;
1522
+ /**
1523
+ * Check if any CDP manager matches the given key (exact or prefix).
1524
+ */
1525
+ declare function hasCdpManager(cdpManagers: Map<string, DaemonCdpManager>, key: string): boolean;
1526
+ /**
1527
+ * Check if any CDP manager matching the key is connected.
1528
+ */
1529
+ declare function isCdpConnected(cdpManagers: Map<string, DaemonCdpManager>, key: string): boolean;
1530
+ declare function buildSessionEntries(allStates: ProviderState[], cdpManagers: Map<string, DaemonCdpManager>): SessionEntry[];
1531
+
1532
+ /**
1533
+ * Shared status snapshot builders.
1534
+ *
1535
+ * Used by:
1536
+ * - DaemonStatusReporter (cloud)
1537
+ * - daemon-standalone HTTP/WS status responses
1538
+ */
1539
+
1540
+ interface StatusSnapshotOptions {
1541
+ allStates: ProviderState[];
1542
+ cdpManagers: Map<string, unknown>;
1543
+ providerLoader: {
1544
+ getAll(): Array<{
1545
+ type: string;
1546
+ icon?: string;
1547
+ displayName?: string;
1548
+ category: 'ide' | 'extension' | 'cli' | 'acp';
1549
+ }>;
1550
+ };
1551
+ detectedIdes: Array<{
1552
+ id: string;
1553
+ name?: string;
1554
+ displayName?: string;
1555
+ installed?: boolean;
1556
+ path?: string;
1557
+ }>;
1558
+ instanceId: string;
1559
+ version: string;
1560
+ daemonMode: boolean;
1561
+ timestamp?: number;
1562
+ p2p?: StatusReportPayload['p2p'];
1563
+ machineNickname?: string | null;
1564
+ }
1565
+ interface StatusSnapshot extends StatusReportPayload {
1566
+ availableProviders: AvailableProviderInfo[];
1567
+ }
1568
+ declare function buildStatusSnapshot(options: StatusSnapshotOptions): StatusSnapshot;
1569
+
1570
+ /**
1571
+ * ADHDev Daemon — unified logger (v2)
1572
+ *
1573
+ * log level: DEBUG < INFO < WARN < ERROR
1574
+ *
1575
+ * Features:
1576
+ * 1. daemonLog(category, msg, level) — explicit per-category logging
1577
+ * 2. installGlobalInterceptor() — Auto-intercept console.log (once on daemon start)
1578
+ * 3. Recent log ring buffer — for remote transmission via P2P/WS
1579
+ * 4. File logging — ~/Library/Logs/adhdev/daemon.log (10MB rolling)
1580
+ *
1581
+ * use:
1582
+ * import { daemonLog, LOG } from './daemon-logger';
1583
+ * LOG.info('CDP', 'Connected to cursor on port 9333');
1584
+ * LOG.debug('StatusReport', 'P2P heartbeat sent');
1585
+ * LOG.warn('IdeInstance', 'onTick error: ...');
1586
+ * LOG.error('Server', 'WebSocket disconnected');
1587
+ */
1588
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
1589
+ declare function setLogLevel(level: LogLevel): void;
1590
+ declare function getLogLevel(): LogLevel;
1591
+ interface LogEntry {
1592
+ ts: number;
1593
+ level: LogLevel;
1594
+ category: string;
1595
+ message: string;
1596
+ }
1597
+ /** Get recent N logs (for remote transmission) */
1598
+ declare function getRecentLogs(count?: number, minLevel?: LogLevel): LogEntry[];
1599
+ /**
1600
+ * Scoped logger instance for a specific component.
1601
+ * Created via LOG.forComponent('CDP:cursor').
1602
+ */
1603
+ interface ScopedLogger {
1604
+ debug: (msg: string) => void;
1605
+ info: (msg: string) => void;
1606
+ warn: (msg: string) => void;
1607
+ error: (msg: string) => void;
1608
+ /** Returns a plain (msg: string) => void function at the given level.
1609
+ * Useful as logFn callback for ProviderLoader, DaemonStatusReporter, etc. */
1610
+ asLogFn: (level?: LogLevel) => (msg: string) => void;
1611
+ }
1612
+ /**
1613
+ * LOG — unified logging API
1614
+ *
1615
+ * Usage:
1616
+ * LOG.info('CDP', 'Connected to cursor on port 9333');
1617
+ * LOG.debug('StatusReport', 'P2P heartbeat sent');
1618
+ *
1619
+ * Component-scoped logger:
1620
+ * const log = LOG.forComponent('ACP:cursor');
1621
+ * log.info('Session created');
1622
+ * log.debug('Heartbeat');
1623
+ *
1624
+ * As callback for external components:
1625
+ * new ProviderLoader({ logFn: LOG.forComponent('Provider').asLogFn() });
1626
+ * new DaemonStatusReporter({ logFn: LOG.forComponent('Status').asLogFn() });
1627
+ */
1628
+ declare const LOG: {
1629
+ debug: (category: string, msg: string) => void;
1630
+ info: (category: string, msg: string) => void;
1631
+ warn: (category: string, msg: string) => void;
1632
+ error: (category: string, msg: string) => void;
1633
+ /**
1634
+ * Create a scoped logger for a specific component.
1635
+ * Category is baked in so callers only pass the message.
1636
+ */
1637
+ forComponent(category: string): ScopedLogger;
1638
+ };
1639
+ /**
1640
+ * console.log/warn/error global interceptor install
1641
+ * Prevent recording in places not using daemonLog.
1642
+ * daemon start when 1time call.
1643
+ */
1644
+ declare function installGlobalInterceptor(): void;
1645
+
1646
+ /**
1647
+ * ADHDev Daemon — Command History Logger
1648
+ *
1649
+ * Record all commands from dashboard/WS/P2P/Extension/API to local file.
1650
+ * Per-date JSONL file, 7-day retention, 5MB limit.
1651
+ *
1652
+ * Purpose:
1653
+ * - Debugging: track what command came and when
1654
+ * - Audit: record all commands executed from remote
1655
+ * - Stats: identify frequently used features
1656
+ */
1657
+ interface CommandLogEntry {
1658
+ ts: string;
1659
+ cmd: string;
1660
+ source: 'ws' | 'p2p' | 'ext' | 'api' | 'standalone' | 'unknown';
1661
+ args?: Record<string, unknown>;
1662
+ success?: boolean;
1663
+ error?: string;
1664
+ durationMs?: number;
1665
+ }
1666
+ /**
1667
+ * Log a command received from the dashboard/WS/P2P/extension/API.
1668
+ * Call this at the entry point of command handling.
1669
+ */
1670
+ declare function logCommand(entry: CommandLogEntry): void;
1671
+ /**
1672
+ * Read recent command history (for dashboard display / debugging)
1673
+ */
1674
+ declare function getRecentCommands(count?: number): CommandLogEntry[];
1675
+
1676
+ /**
1677
+ * ADHDev Launcher — IDE Launch/Relaunch with CDP
1678
+ *
1679
+ * Launches IDE with Chrome DevTools Protocol (remote-debugging-port).
1680
+ * If IDE is already running, terminates it and restarts with CDP option.
1681
+ *
1682
+ * Pipeline:
1683
+ * 1. IDE process detection (already running?)
1684
+ * 2. If already running with CDP → reuse as-is
1685
+ * 3. If running without CDP → kill process → wait → restart with CDP
1686
+ * 4. Not running → start fresh with CDP
1687
+ *
1688
+ * Usage:
1689
+ * adhdev launch — Launch configured IDE with CDP port
1690
+ * adhdev launch cursor — Launch Cursor with CDP port
1691
+ * adhdev launch --workspace /path — Open specific workspace
1692
+ */
1693
+ /** Kill IDE process (graceful → force) */
1694
+ declare function killIdeProcess(ideId: string): Promise<boolean>;
1695
+ /** Check if IDE process is running */
1696
+ declare function isIdeRunning(ideId: string): boolean;
1697
+ interface LaunchOptions {
1698
+ ideId?: string;
1699
+ workspace?: string;
1700
+ newWindow?: boolean;
1701
+ }
1702
+ interface LaunchResult {
1703
+ success: boolean;
1704
+ ideId: string;
1705
+ ideName: string;
1706
+ port: number;
1707
+ action: 'started' | 'restarted' | 'reused' | 'failed';
1708
+ message: string;
1709
+ error?: string;
1710
+ }
1711
+ /**
1712
+ * Execute IDE with CDP port (relaunch pipeline)
1713
+ *
1714
+ * 1. IDE detect
1715
+ * 2. per-fixed IDE CDP port determine
1716
+ * 3. CDP not active → reuse
1717
+ * 4. IDE execute during but CDP none → terminate → restart with CDP
1718
+ * 5. IDE not running → start fresh with CDP
1719
+ */
1720
+ declare function launchWithCdp(options?: LaunchOptions): Promise<LaunchResult>;
1721
+ declare function getAvailableIdeIds(): string[];
1722
+
1723
+ declare const DEFAULT_DAEMON_PORT = 19222;
1724
+ declare const DAEMON_WS_PATH = "/ipc";
1725
+
1726
+ /**
1727
+ * Shared helper for forwarding agent stream snapshots into the IDE instance.
1728
+ *
1729
+ * Both cloud and standalone daemons use the same InstanceManager wiring.
1730
+ */
1731
+ declare function forwardAgentStreamsToIdeInstance(instanceManager: {
1732
+ getInstance: (key: string) => any;
1733
+ }, ideType: string, streams: any[]): void;
1734
+
1735
+ /**
1736
+ * ProviderCliAdapter — Script-based CLI Adapter
1737
+ *
1738
+ * All CLI providers use versioned scripts (like IDE providers).
1739
+ * Scripts are Node.js functions that receive PTY buffer data and return structured results.
1740
+ *
1741
+ * Required scripts in scripts/{version}/scripts.js:
1742
+ * - detectStatus(input) → AgentStatus string ('idle' | 'generating' | 'waiting_approval')
1743
+ * - parseOutput(input) → ReadChatResult { messages, status, activeModal, ... }
1744
+ * - parseApproval(input) → ModalInfo | null
1745
+ *
1746
+ * provider.json contract:
1747
+ * type, name, category: 'cli', binary, spawn, approvalKeys
1748
+ * compatibility: [{ ideVersion, scriptDir }] ← versioned scripts
1749
+ */
1750
+
1751
+ interface CliChatMessage {
1752
+ role: 'user' | 'assistant';
1753
+ content: string;
1754
+ timestamp?: number;
1755
+ }
1756
+ interface CliSessionStatus {
1757
+ status: 'idle' | 'generating' | 'waiting_approval' | 'error' | 'stopped' | 'starting';
1758
+ messages: CliChatMessage[];
1759
+ workingDir: string;
1760
+ activeModal: {
1761
+ message: string;
1762
+ buttons: string[];
1763
+ } | null;
1764
+ terminalHistory?: string;
1765
+ }
1766
+ /**
1767
+ * CLI Script Functions.
1768
+ * Unlike IDE scripts (which return JS code strings for CDP evaluate),
1769
+ * CLI scripts are Node.js functions that receive PTY buffer data and return structured results.
1770
+ */
1771
+ interface CliScripts {
1772
+ /** Full PTY buffer → ReadChatResult (messages, status, activeModal) */
1773
+ parseOutput?: (input: CliScriptInput) => any;
1774
+ /** Lightweight status detection (high-frequency polling) → AgentStatus string */
1775
+ detectStatus?: (input: {
1776
+ tail: string;
1777
+ screenText?: string;
1778
+ rawBuffer?: string;
1779
+ }) => string | null;
1780
+ /** Parse approval modal from PTY output → ModalInfo | null */
1781
+ parseApproval?: (input: {
1782
+ buffer: string;
1783
+ rawBuffer?: string;
1784
+ tail: string;
1785
+ }) => {
1786
+ message: string;
1787
+ buttons: string[];
1788
+ } | null;
1789
+ /** Produce a cli-specific prompt from a dashboard action payload */
1790
+ resolveAction?: (data: any) => string;
1791
+ /** Custom scripts */
1792
+ [name: string]: ((input: any) => any) | undefined;
1793
+ }
1794
+ interface CliScriptInput {
1795
+ buffer: string;
1796
+ rawBuffer: string;
1797
+ recentBuffer: string;
1798
+ screenText: string;
1799
+ terminalHistory?: string;
1800
+ messages: CliChatMessage[];
1801
+ partialResponse: string;
1802
+ }
1803
+ interface CliProviderModule {
1804
+ type: string;
1805
+ name: string;
1806
+ category: 'cli';
1807
+ binary: string;
1808
+ sendDelayMs?: number;
1809
+ sendKey?: string;
1810
+ submitStrategy?: 'wait_for_echo' | 'immediate';
1811
+ spawn: {
1812
+ command: string;
1813
+ args: string[];
1814
+ shell: boolean;
1815
+ env: Record<string, string>;
1816
+ };
1817
+ timeouts?: {
1818
+ /** PTY output batch transmit interval (default 50ms) */
1819
+ ptyFlush?: number;
1820
+ /** Wait for startup dialog auto-proceed (default 300ms) */
1821
+ dialogAccept?: number;
1822
+ /** Approval detect cooldown (default 2000ms) */
1823
+ approvalCooldown?: number;
1824
+ /** Check for completion on no-response during generating (default 6000ms) */
1825
+ generatingIdle?: number;
1826
+ /** Check for completion on no-response (default 5000ms) */
1827
+ idleFinish?: number;
1828
+ /** Max response wait (default 300000ms = 5min) */
1829
+ maxResponse?: number;
1830
+ /** shutdown after kill wait (default 1000ms) */
1831
+ shutdownGrace?: number;
1832
+ /** Output settle debounce before evaluating status (default 300ms) */
1833
+ outputSettle?: number;
1834
+ };
1835
+ }
1836
+ declare class ProviderCliAdapter implements CliAdapter {
1837
+ private extraArgs;
1838
+ readonly cliType: string;
1839
+ readonly cliName: string;
1840
+ workingDir: string;
1841
+ private provider;
1842
+ private ptyProcess;
1843
+ private messages;
1844
+ private committedMessages;
1845
+ private structuredMessages;
1846
+ private currentStatus;
1847
+ private onStatusChange;
1848
+ private responseBuffer;
1849
+ private recentOutputBuffer;
1850
+ private isWaitingForResponse;
1851
+ private activeModal;
1852
+ private responseTimeout;
1853
+ private idleTimeout;
1854
+ private ready;
1855
+ private startupBuffer;
1856
+ private startupParseGate;
1857
+ private spawnAt;
1858
+ private onPtyDataCallback;
1859
+ private pendingOutputParseBuffer;
1860
+ private pendingOutputParseTimer;
1861
+ private ptyOutputBuffer;
1862
+ private ptyOutputFlushTimer;
1863
+ private serverConn;
1864
+ private logBuffer;
1865
+ private lastApprovalResolvedAt;
1866
+ private approvalTransitionBuffer;
1867
+ private approvalExitTimeout;
1868
+ private pendingScriptStatus;
1869
+ private pendingScriptStatusSince;
1870
+ private pendingScriptStatusTimer;
1871
+ private settleTimer;
1872
+ private settledBuffer;
1873
+ private submitPendingUntil;
1874
+ private responseSettleIgnoreUntil;
1875
+ private responseEpoch;
1876
+ private submitRetryTimer;
1877
+ private submitRetryUsed;
1878
+ private submitRetryPromptSnippet;
1879
+ private resizeSuppressUntil;
1880
+ private statusHistory;
1881
+ private cliScripts;
1882
+ /** Full accumulated ANSI-stripped PTY output */
1883
+ private accumulatedBuffer;
1884
+ /** Full accumulated raw PTY output (with ANSI) */
1885
+ private accumulatedRawBuffer;
1886
+ /** Current visible terminal screen snapshot */
1887
+ private terminalScreen;
1888
+ /** Rolling append-only terminal transcript built from screen snapshots */
1889
+ private terminalHistory;
1890
+ /** Max accumulated buffer size (last 50KB) */
1891
+ private static readonly MAX_ACCUMULATED_BUFFER;
1892
+ private currentTurnScope;
1893
+ private syncMessageViews;
1894
+ private sliceFromOffset;
1895
+ private buildParseInput;
1896
+ private setStatus;
1897
+ private readonly timeouts;
1898
+ private readonly approvalKeys;
1899
+ private readonly sendDelayMs;
1900
+ private readonly sendKey;
1901
+ private readonly submitStrategy;
1902
+ private static readonly SCRIPT_STATUS_DEBOUNCE_MS;
1903
+ constructor(provider: CliProviderModule, workingDir: string, extraArgs?: string[]);
1904
+ /** Inject CLI scripts after construction (e.g. when resolved by ProviderLoader) */
1905
+ setCliScripts(scripts: CliScripts): void;
1906
+ setServerConn(serverConn: any): void;
1907
+ setOnStatusChange(callback: () => void): void;
1908
+ setOnPtyData(callback: (data: string) => void): void;
1909
+ private flushPendingOutputParse;
1910
+ spawn(): Promise<void>;
1911
+ private handleOutput;
1912
+ private scheduleSettle;
1913
+ private armApprovalExitTimeout;
1914
+ private evaluateSettled;
1915
+ private finishResponse;
1916
+ private commitCurrentTranscript;
1917
+ private runDetectStatus;
1918
+ private runParseApproval;
1919
+ getStatus(): CliSessionStatus;
1920
+ /**
1921
+ * Script-based full parse — returns ReadChatResult.
1922
+ * Called by command handler / dashboard for rich content rendering.
1923
+ */
1924
+ getScriptParsedStatus(): any;
1925
+ private parseCurrentTranscript;
1926
+ /** Whether this adapter has CLI scripts loaded */
1927
+ hasCliScripts(): boolean;
1928
+ /**
1929
+ * Resolves an action (like 'fix' lint error) from the dashboard.
1930
+ * Uses resolveAction script if available, otherwise falls back to standard text.
1931
+ */
1932
+ resolveAction(data: any): Promise<void>;
1933
+ sendMessage(text: string): Promise<void>;
1934
+ getPartialResponse(): string;
1935
+ cancel(): void;
1936
+ shutdown(): void;
1937
+ clearHistory(): void;
1938
+ isProcessing(): boolean;
1939
+ isReady(): boolean;
1940
+ writeRaw(data: string): void;
1941
+ resolveModal(buttonIndex: number): void;
1942
+ resize(cols: number, rows: number): void;
1943
+ getDebugState(): Record<string, any>;
1944
+ }
1945
+
1946
+ /**
1947
+ * CliProviderInstance — Runtime instance for CLI Provider
1948
+ *
1949
+ * Lifecycle layer on top of ProviderCliAdapter.
1950
+ * collectCliData() + status transition logic from daemon-status.ts moved here.
1951
+ */
1952
+
1953
+ declare class CliProviderInstance implements ProviderInstance {
1954
+ private provider;
1955
+ private workingDir;
1956
+ private cliArgs;
1957
+ readonly type: string;
1958
+ readonly category: "cli";
1959
+ private adapter;
1960
+ private context;
1961
+ private events;
1962
+ private lastStatus;
1963
+ private generatingStartedAt;
1964
+ private settings;
1965
+ private monitor;
1966
+ private generatingDebounceTimer;
1967
+ private generatingDebouncePending;
1968
+ private lastApprovalEventAt;
1969
+ private historyWriter;
1970
+ readonly instanceId: string;
1971
+ constructor(provider: ProviderModule, workingDir: string, cliArgs?: string[], instanceId?: string);
1972
+ init(context: InstanceContext): Promise<void>;
1973
+ onTick(): Promise<void>;
1974
+ getState(): ProviderState;
1975
+ onEvent(event: string, data?: any): void;
1976
+ dispose(): void;
1977
+ private completedDebounceTimer;
1978
+ private completedDebouncePending;
1979
+ private detectStatusTransition;
1980
+ private pushEvent;
1981
+ private flushEvents;
1982
+ getAdapter(): ProviderCliAdapter;
1983
+ get cliType(): string;
1984
+ get cliName(): string;
1985
+ }
1986
+
1987
+ /**
1988
+ * AcpProviderInstance — ACP (Agent Client Protocol) Provider runtime instance
1989
+ *
1990
+ * Spawns ACP agent process and communicates via the official ACP SDK.
1991
+ * Uses ClientSideConnection + ndJsonStream for structured protocol communication.
1992
+ *
1993
+ * ACP spec: https://agentclientprotocol.com
1994
+ * ACP SDK: @agentclientprotocol/sdk@0.16.1
1995
+ *
1996
+ * lifecycle:
1997
+ * 1. init() → Spawn agent process + ACP initialize handshake
1998
+ * 2. onTick() → no-op (ACP event based)
1999
+ * 3. getState() → ProviderState return (dashboard for display)
2000
+ * 4. onEvent('send_message') → session/prompt transmit
2001
+ * 5. dispose() → kill process
2002
+ */
2003
+
2004
+ declare class AcpProviderInstance implements ProviderInstance {
2005
+ private cliArgs;
2006
+ readonly type: string;
2007
+ readonly category: "acp";
2008
+ private readonly log;
2009
+ private provider;
2010
+ private context;
2011
+ private settings;
2012
+ private events;
2013
+ private monitor;
2014
+ private process;
2015
+ private connection;
2016
+ private sessionId;
2017
+ private messages;
2018
+ private currentStatus;
2019
+ private lastStatus;
2020
+ private generatingStartedAt;
2021
+ private agentCapabilities;
2022
+ private currentModel;
2023
+ private currentMode;
2024
+ private activeToolCalls;
2025
+ private stopReason;
2026
+ private partialContent;
2027
+ /** Rich content blocks accumulated during streaming */
2028
+ private partialBlocks;
2029
+ /** Tool calls collected during current turn */
2030
+ private turnToolCalls;
2031
+ private errorMessage;
2032
+ private errorReason;
2033
+ private stderrBuffer;
2034
+ private spawnedAt;
2035
+ private configOptions;
2036
+ private availableModes;
2037
+ /** Static config mode — agent doesn't support config/* methods */
2038
+ private useStaticConfig;
2039
+ /** Current config selections (for spawnArgBuilder) */
2040
+ private selectedConfig;
2041
+ private workingDir;
2042
+ private instanceId;
2043
+ constructor(provider: ProviderModule, workingDir: string, cliArgs?: string[]);
2044
+ init(context: InstanceContext): Promise<void>;
2045
+ onTick(): Promise<void>;
2046
+ getState(): AcpProviderState;
2047
+ onEvent(event: string, data?: any): void;
2048
+ getInstanceId(): string;
2049
+ private parseConfigOptions;
2050
+ private parseModes;
2051
+ setConfigOption(category: string, value: string): Promise<void>;
2052
+ setMode(modeId: string): Promise<void>;
2053
+ /** Static config: kill process and restart with new args */
2054
+ private restartWithNewConfig;
2055
+ /** Update settings at runtime (called when user changes settings from dashboard) */
2056
+ updateSettings(newSettings: Record<string, any>): void;
2057
+ dispose(): void;
2058
+ private spawnAgent;
2059
+ private createClient;
2060
+ private initialize;
2061
+ private createSession;
2062
+ sendPrompt(text: string, contentBlocks?: ContentBlock[]): Promise<void>;
2063
+ private cancelSession;
2064
+ private permissionResolvers;
2065
+ private resolvePermission;
2066
+ private handleSessionUpdate;
2067
+ /** Handle legacy session/update formats (pre-standardization compat) */
2068
+ private handleLegacyUpdate;
2069
+ /** Map SDK ToolCallStatus to internal status */
2070
+ private mapToolCallStatus;
2071
+ /** Truncate content for transport (text: 2000 chars, images preserved) */
2072
+ private truncateContent;
2073
+ /** Build ContentBlock[] from current partial state */
2074
+ private buildPartialBlocks;
2075
+ /** Finalize streaming content into an assistant message */
2076
+ private finalizeAssistantMessage;
2077
+ /** Convert ACP ToolCallContent[] to our ToolCallContent[] */
2078
+ private convertToolCallContent;
2079
+ private detectStatusTransition;
2080
+ private pushEvent;
2081
+ private flushEvents;
2082
+ get cliType(): string;
2083
+ get cliName(): string;
2084
+ /** ACP Agent capabilities (available after initialize) */
2085
+ getCapabilities(): Record<string, any>;
2086
+ }
2087
+
2088
+ /**
2089
+ * Dev Server — HTTP API for Provider debugging + script development
2090
+ *
2091
+ * Enabled with `adhdev daemon --dev`
2092
+ * Port: 19280 (fixed)
2093
+ *
2094
+ * API list:
2095
+ * GET /api/providers — loaded provider list
2096
+ * POST /api/providers/:type/script — specific script execute
2097
+ * POST /api/cdp/evaluate — Execute JS expression
2098
+ * POST /api/cdp/dom/query — Test selector
2099
+ * GET /api/cdp/screenshot — screenshot
2100
+ * POST /api/scripts/run — Execute provider script (name + params)
2101
+ * GET /api/status — All status (CDP connection, provider etc)
2102
+ */
2103
+
2104
+ declare class DevServer {
2105
+ private server;
2106
+ private providerLoader;
2107
+ private cdpManagers;
2108
+ private instanceManager;
2109
+ private cliManager;
2110
+ private logFn;
2111
+ private sseClients;
2112
+ private watchScriptPath;
2113
+ private watchScriptName;
2114
+ private watchTimer;
2115
+ private autoImplProcess;
2116
+ private autoImplSSEClients;
2117
+ private autoImplStatus;
2118
+ private cliSSEClients;
2119
+ constructor(options: {
2120
+ providerLoader: ProviderLoader;
2121
+ cdpManagers: Map<string, DaemonCdpManager>;
2122
+ instanceManager?: ProviderInstanceManager;
2123
+ cliManager?: DaemonCliManager;
2124
+ logFn?: (msg: string) => void;
2125
+ });
2126
+ private log;
2127
+ private readonly routes;
2128
+ private matchRoute;
2129
+ private getEndpointList;
2130
+ start(port?: number): Promise<void>;
2131
+ stop(): void;
2132
+ private handleListProviders;
2133
+ private handleProviderConfig;
2134
+ private handleSpawnTest;
2135
+ private handleRunScript;
2136
+ private handleCdpEvaluate;
2137
+ private handleCdpClick;
2138
+ private handleCdpDomQuery;
2139
+ private handleScreenshot;
2140
+ private handleScriptsRun;
2141
+ private handleStatus;
2142
+ private handleReload;
2143
+ private getConsoleDistDir;
2144
+ private serveConsole;
2145
+ private static MIME_MAP;
2146
+ private serveStaticAsset;
2147
+ private handleSSE;
2148
+ private sendSSE;
2149
+ private handleWatchStart;
2150
+ private handleWatchStop;
2151
+ /** Find the provider directory on disk */
2152
+ private findProviderDir;
2153
+ /** GET /api/providers/:type/files — list all files in provider directory */
2154
+ private handleListFiles;
2155
+ /** GET /api/providers/:type/file?path=scripts.js — read a file */
2156
+ private handleReadFile;
2157
+ /** POST /api/providers/:type/file — write a file { path, content } */
2158
+ private handleWriteFile;
2159
+ private handleSource;
2160
+ private handleSave;
2161
+ private handleTypeAndSend;
2162
+ private handleTypeAndSendAt;
2163
+ private handleScriptHints;
2164
+ private handleValidate;
2165
+ private handleAcpChat;
2166
+ private handleCdpTargets;
2167
+ private handleScaffold;
2168
+ private handleDetectVersions;
2169
+ private handleDomInspect;
2170
+ private handleDomChildren;
2171
+ private handleDomAnalyze;
2172
+ private handleFindCommon;
2173
+ private handleFindByText;
2174
+ private handleDomContext;
2175
+ private getDefaultAutoImplReference;
2176
+ private resolveAutoImplReference;
2177
+ private getLatestScriptVersionDir;
2178
+ private resolveAutoImplWritableProviderDir;
2179
+ private loadAutoImplReferenceScripts;
2180
+ private handleAutoImplement;
2181
+ private buildAutoImplPrompt;
2182
+ private buildCliAutoImplPrompt;
2183
+ private handleAutoImplSSE;
2184
+ private handleAutoImplCancel;
2185
+ private sendAutoImplSSE;
2186
+ /** Get CDP manager — matching IDE when ideType specified, first connected one otherwise.
2187
+ * DevServer is a debugging tool so first-connected fallback is acceptable,
2188
+ * but callers should pass ideType when possible. */
2189
+ private getCdp;
2190
+ private json;
2191
+ private readBody;
2192
+ /** GET /api/cli/status — list all running CLI/ACP instances with state */
2193
+ private handleCliStatus;
2194
+ private findCliTarget;
2195
+ /** POST /api/cli/launch — launch a CLI agent { type, workingDir?, args? } */
2196
+ private handleCliLaunch;
2197
+ /** POST /api/cli/send — send message to a running CLI { type, text } */
2198
+ private handleCliSend;
2199
+ /** POST /api/cli/stop — stop a running CLI { type } */
2200
+ private handleCliStop;
2201
+ /** GET /api/cli/events — SSE stream of CLI status events */
2202
+ private handleCliSSE;
2203
+ private sendCliSSE;
2204
+ /** GET /api/cli/debug/:type — full internal debug state of a CLI adapter */
2205
+ private handleCliDebug;
2206
+ /** POST /api/cli/resolve — resolve an approval modal { type, buttonIndex } */
2207
+ private handleCliResolve;
2208
+ /** POST /api/cli/raw — send raw keystrokes to PTY { type, keys } */
2209
+ private handleCliRaw;
2210
+ }
2211
+
2212
+ /**
2213
+ * ADHDev Launcher — Extension Installer
2214
+ *
2215
+ * Installs VS Code extensions via CLI commands.
2216
+ * Supports installing user-selected AI extensions.
2217
+ */
2218
+
2219
+ interface ExtensionInfo {
2220
+ id: string;
2221
+ name: string;
2222
+ displayName: string;
2223
+ marketplaceId: string;
2224
+ description: string;
2225
+ category: 'ai-agent' | 'utility';
2226
+ icon: string;
2227
+ recommended: boolean;
2228
+ requiresApiKey?: boolean;
2229
+ apiKeyName?: string;
2230
+ website?: string;
2231
+ vsixUrl?: string;
2232
+ }
2233
+ interface InstallResult {
2234
+ extensionId: string;
2235
+ marketplaceId: string;
2236
+ success: boolean;
2237
+ alreadyInstalled: boolean;
2238
+ error?: string;
2239
+ }
2240
+ /**
2241
+ * Check if an extension is already installed
2242
+ */
2243
+ declare function isExtensionInstalled(ide: IDEInfo, marketplaceId: string): boolean;
2244
+ /**
2245
+ * Install multiple extensions sequentially
2246
+ */
2247
+ declare function installExtensions(ide: IDEInfo, extensions: ExtensionInfo[], onProgress?: (current: number, total: number, ext: ExtensionInfo, result: InstallResult) => void): Promise<InstallResult[]>;
2248
+ /**
2249
+ * Get AI agent extensions
2250
+ */
2251
+ declare function getAIExtensions(): ExtensionInfo[];
2252
+ /**
2253
+ * Launch IDE after installation
2254
+ */
2255
+ declare function launchIDE(ide: IDEInfo, workspacePath?: string): boolean;
2256
+
2257
+ /**
2258
+ * Daemon Lifecycle — Shared init + shutdown logic
2259
+ *
2260
+ * initDaemonComponents(): Creates all core daemon components in correct order.
2261
+ * shutdownDaemonComponents(): Graceful shutdown of all components.
2262
+ *
2263
+ * Transport-specific setup (ServerConnection, P2P, HTTP/WS) remains in each daemon.
2264
+ */
2265
+
2266
+ interface DaemonInitConfig {
2267
+ /** ProviderLoader log function */
2268
+ providerLogFn?: (msg: string) => void;
2269
+ /** CLI Manager deps (transport-specific) */
2270
+ cliManagerDeps: {
2271
+ getServerConn: () => any;
2272
+ getP2p: () => any;
2273
+ onStatusChange: () => void;
2274
+ removeAgentTracking: (key: string) => void;
2275
+ };
2276
+ /** CDP config */
2277
+ enabledIdes?: string[];
2278
+ /** Router transport-specific callbacks */
2279
+ onStatusChange?: () => void;
2280
+ onPostChatCommand?: () => void;
2281
+ getCdpLogFn?: (ideType: string) => (msg: string) => void;
2282
+ /** Additional callback after CDP manager created (transport-specific extras) */
2283
+ onCdpManagerSetup?: (ideType: string, manager: DaemonCdpManager, managerKey: string) => void | Promise<void>;
2284
+ /** Poller callback (transport-specific) */
2285
+ onStreamsUpdated?: (ideType: string, streams: any[]) => void;
2286
+ /** Instance ticking interval (ms), default 5000 */
2287
+ tickIntervalMs?: number;
2288
+ /** CDP scan interval (ms), default 30000 */
2289
+ cdpScanIntervalMs?: number;
2290
+ }
2291
+ interface DaemonComponents {
2292
+ providerLoader: ProviderLoader;
2293
+ instanceManager: ProviderInstanceManager;
2294
+ cliManager: DaemonCliManager;
2295
+ commandHandler: DaemonCommandHandler;
2296
+ agentStreamManager: DaemonAgentStreamManager;
2297
+ router: DaemonCommandRouter;
2298
+ poller: AgentStreamPoller;
2299
+ cdpInitializer: DaemonCdpInitializer;
2300
+ cdpManagers: Map<string, DaemonCdpManager>;
2301
+ sessionRegistry: SessionRegistry;
2302
+ detectedIdes: {
2303
+ value: any[];
2304
+ };
2305
+ }
2306
+ interface DaemonDevSupportOptions {
2307
+ components: DaemonComponents;
2308
+ logFn?: (msg: string) => void;
2309
+ }
2310
+ /**
2311
+ * Initialize all daemon core components.
2312
+ *
2313
+ * Order:
2314
+ * 1. Global log interceptor
2315
+ * 2. ProviderLoader
2316
+ * 3. InstanceManager + CliManager
2317
+ * 4. Detect IDEs
2318
+ * 5. CdpInitializer → connectAll + periodic scan + discovery
2319
+ * 6. CommandHandler + AgentStreamManager
2320
+ * 7. Router + Poller
2321
+ * 8. Start instance ticking
2322
+ */
2323
+ declare function initDaemonComponents(config: DaemonInitConfig): Promise<DaemonComponents>;
2324
+ /**
2325
+ * Start shared dev-only helpers:
2326
+ * - DevServer on port 19280
2327
+ * - Provider hot-reload watcher
2328
+ */
2329
+ declare function startDaemonDevSupport(options: DaemonDevSupportOptions): Promise<DevServer>;
2330
+ /**
2331
+ * Graceful shutdown of all daemon components.
2332
+ *
2333
+ * Order:
2334
+ * 1. Stop timers (poller, cdpInitializer)
2335
+ * 2. Dispose agent stream
2336
+ * 3. Shutdown CLIs
2337
+ * 4. Dispose instances
2338
+ * 5. Disconnect CDPs
2339
+ */
2340
+ declare function shutdownDaemonComponents(components: DaemonComponents): Promise<void>;
2341
+
2342
+ export { AcpProviderInstance, AcpProviderState, AgentStreamPoller, type AgentStreamPollerDeps, AvailableProviderInfo, CdpDomHandlers, type CdpInitializerConfig, type CdpScannerOptions, type CdpSetupContext, CdpTargetFilter, type CliAdapter, CliProviderInstance, type CommandContext, type CommandResult$1 as CommandResult, type CommandRouterDeps, type CommandRouterResult, CommandResult$2 as CoreCommandResult, DAEMON_WS_PATH, DEFAULT_DAEMON_PORT, DaemonAgentStreamManager, DaemonCdpInitializer, DaemonCdpManager, DaemonCdpScanner, DaemonCliManager, DaemonCommandHandler, DaemonCommandRouter, type DaemonComponents, type DaemonCoreOptions, type DaemonDevSupportOptions, DaemonEvent, type DaemonInitConfig, DaemonStatusReporter, DevServer, type HostMemorySnapshot, type IDEInfo, type IDaemonCore, IdeProviderInstance, type ExtensionInfo as InstallerExtensionInfo, LOG, type LogEntry, type LogLevel, ProviderCliAdapter, ProviderInstanceManager, ProviderLoader, ProviderModule, type ProviderVersionInfo, type ScopedLogger, SessionEntry, SessionTransport, type SetupIdeInstanceOptions, StatusReportPayload, StatusResponse, type StatusSnapshot, type StatusSnapshotOptions, VersionArchive, type VersionHistory, buildSessionEntries, buildStatusSnapshot, connectCdpManager, detectAllVersions, detectCLIs, detectIDEs, findCdpManager, forwardAgentStreamsToIdeInstance, getAIExtensions, getAvailableIdeIds, getHostMemorySnapshot, getLogLevel, getRecentCommands, getRecentLogs, hasCdpManager, initDaemonComponents, installExtensions, installGlobalInterceptor, isCdpConnected, isExtensionInstalled, isIdeRunning, killIdeProcess, launchIDE, launchWithCdp, logCommand, probeCdpPort, readChatHistory, registerExtensionProviders, setLogLevel, setupIdeInstance, shutdownDaemonComponents, startDaemonDevSupport };