@developerz.ai/ui-debugger-mcp 1.0.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 (162) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +295 -0
  3. package/dist/adapters/android/adb.d.ts +38 -0
  4. package/dist/adapters/android/adb.js +72 -0
  5. package/dist/adapters/android/adb.js.map +1 -0
  6. package/dist/adapters/android/android-adapter.d.ts +63 -0
  7. package/dist/adapters/android/android-adapter.js +306 -0
  8. package/dist/adapters/android/android-adapter.js.map +1 -0
  9. package/dist/adapters/android/commands.d.ts +59 -0
  10. package/dist/adapters/android/commands.js +178 -0
  11. package/dist/adapters/android/commands.js.map +1 -0
  12. package/dist/adapters/android/uiautomator.d.ts +81 -0
  13. package/dist/adapters/android/uiautomator.js +296 -0
  14. package/dist/adapters/android/uiautomator.js.map +1 -0
  15. package/dist/adapters/browser/browser-adapter.d.ts +72 -0
  16. package/dist/adapters/browser/browser-adapter.js +434 -0
  17. package/dist/adapters/browser/browser-adapter.js.map +1 -0
  18. package/dist/adapters/browser/cdp.d.ts +83 -0
  19. package/dist/adapters/browser/cdp.js +308 -0
  20. package/dist/adapters/browser/cdp.js.map +1 -0
  21. package/dist/adapters/browser/query.d.ts +25 -0
  22. package/dist/adapters/browser/query.js +85 -0
  23. package/dist/adapters/browser/query.js.map +1 -0
  24. package/dist/adapters/contract.d.ts +159 -0
  25. package/dist/adapters/contract.js +22 -0
  26. package/dist/adapters/contract.js.map +1 -0
  27. package/dist/adapters/desktop/atspi.d.ts +95 -0
  28. package/dist/adapters/desktop/atspi.js +359 -0
  29. package/dist/adapters/desktop/atspi.js.map +1 -0
  30. package/dist/adapters/desktop/capture.d.ts +35 -0
  31. package/dist/adapters/desktop/capture.js +67 -0
  32. package/dist/adapters/desktop/capture.js.map +1 -0
  33. package/dist/adapters/desktop/desktop-adapter.d.ts +60 -0
  34. package/dist/adapters/desktop/desktop-adapter.js +215 -0
  35. package/dist/adapters/desktop/desktop-adapter.js.map +1 -0
  36. package/dist/adapters/desktop/input.d.ts +67 -0
  37. package/dist/adapters/desktop/input.js +191 -0
  38. package/dist/adapters/desktop/input.js.map +1 -0
  39. package/dist/adapters/desktop/proc.d.ts +23 -0
  40. package/dist/adapters/desktop/proc.js +38 -0
  41. package/dist/adapters/desktop/proc.js.map +1 -0
  42. package/dist/adapters/factory.d.ts +23 -0
  43. package/dist/adapters/factory.js +45 -0
  44. package/dist/adapters/factory.js.map +1 -0
  45. package/dist/agent/belt/act.d.ts +100 -0
  46. package/dist/agent/belt/act.js +166 -0
  47. package/dist/agent/belt/act.js.map +1 -0
  48. package/dist/agent/belt/look.d.ts +98 -0
  49. package/dist/agent/belt/look.js +160 -0
  50. package/dist/agent/belt/look.js.map +1 -0
  51. package/dist/agent/belt/observe.d.ts +102 -0
  52. package/dist/agent/belt/observe.js +185 -0
  53. package/dist/agent/belt/observe.js.map +1 -0
  54. package/dist/agent/belt/report.d.ts +133 -0
  55. package/dist/agent/belt/report.js +112 -0
  56. package/dist/agent/belt/report.js.map +1 -0
  57. package/dist/agent/loop.d.ts +136 -0
  58. package/dist/agent/loop.js +173 -0
  59. package/dist/agent/loop.js.map +1 -0
  60. package/dist/agent/models.d.ts +26 -0
  61. package/dist/agent/models.js +22 -0
  62. package/dist/agent/models.js.map +1 -0
  63. package/dist/agent/prompts/android-addendum.d.ts +12 -0
  64. package/dist/agent/prompts/android-addendum.js +76 -0
  65. package/dist/agent/prompts/android-addendum.js.map +1 -0
  66. package/dist/agent/prompts/compose.d.ts +30 -0
  67. package/dist/agent/prompts/compose.js +52 -0
  68. package/dist/agent/prompts/compose.js.map +1 -0
  69. package/dist/agent/prompts/debug-agent.d.ts +9 -0
  70. package/dist/agent/prompts/debug-agent.js +102 -0
  71. package/dist/agent/prompts/debug-agent.js.map +1 -0
  72. package/dist/agent/prompts/desktop-addendum.d.ts +10 -0
  73. package/dist/agent/prompts/desktop-addendum.js +66 -0
  74. package/dist/agent/prompts/desktop-addendum.js.map +1 -0
  75. package/dist/agent/prompts/web-addendum.d.ts +9 -0
  76. package/dist/agent/prompts/web-addendum.js +70 -0
  77. package/dist/agent/prompts/web-addendum.js.map +1 -0
  78. package/dist/agent/provider.d.ts +17 -0
  79. package/dist/agent/provider.js +29 -0
  80. package/dist/agent/provider.js.map +1 -0
  81. package/dist/cli/control.d.ts +19 -0
  82. package/dist/cli/control.js +152 -0
  83. package/dist/cli/control.js.map +1 -0
  84. package/dist/cli/help.d.ts +9 -0
  85. package/dist/cli/help.js +41 -0
  86. package/dist/cli/help.js.map +1 -0
  87. package/dist/cli/init.d.ts +20 -0
  88. package/dist/cli/init.js +119 -0
  89. package/dist/cli/init.js.map +1 -0
  90. package/dist/config/load.d.ts +64 -0
  91. package/dist/config/load.js +105 -0
  92. package/dist/config/load.js.map +1 -0
  93. package/dist/config/schema.d.ts +105 -0
  94. package/dist/config/schema.js +62 -0
  95. package/dist/config/schema.js.map +1 -0
  96. package/dist/errors.d.ts +41 -0
  97. package/dist/errors.js +90 -0
  98. package/dist/errors.js.map +1 -0
  99. package/dist/findings/schema.d.ts +64 -0
  100. package/dist/findings/schema.js +27 -0
  101. package/dist/findings/schema.js.map +1 -0
  102. package/dist/index.d.ts +2 -0
  103. package/dist/index.js +4 -0
  104. package/dist/index.js.map +1 -0
  105. package/dist/main.d.ts +2 -0
  106. package/dist/main.js +95 -0
  107. package/dist/main.js.map +1 -0
  108. package/dist/mcp/server.d.ts +25 -0
  109. package/dist/mcp/server.js +31 -0
  110. package/dist/mcp/server.js.map +1 -0
  111. package/dist/mcp/tools/describe.d.ts +12 -0
  112. package/dist/mcp/tools/describe.js +32 -0
  113. package/dist/mcp/tools/describe.js.map +1 -0
  114. package/dist/mcp/tools/end-session.d.ts +11 -0
  115. package/dist/mcp/tools/end-session.js +27 -0
  116. package/dist/mcp/tools/end-session.js.map +1 -0
  117. package/dist/mcp/tools/get-findings.d.ts +12 -0
  118. package/dist/mcp/tools/get-findings.js +42 -0
  119. package/dist/mcp/tools/get-findings.js.map +1 -0
  120. package/dist/mcp/tools/index.d.ts +17 -0
  121. package/dist/mcp/tools/index.js +24 -0
  122. package/dist/mcp/tools/index.js.map +1 -0
  123. package/dist/mcp/tools/result.d.ts +10 -0
  124. package/dist/mcp/tools/result.js +20 -0
  125. package/dist/mcp/tools/result.js.map +1 -0
  126. package/dist/mcp/tools/send-message.d.ts +11 -0
  127. package/dist/mcp/tools/send-message.js +31 -0
  128. package/dist/mcp/tools/send-message.js.map +1 -0
  129. package/dist/mcp/tools/start-debug.d.ts +12 -0
  130. package/dist/mcp/tools/start-debug.js +50 -0
  131. package/dist/mcp/tools/start-debug.js.map +1 -0
  132. package/dist/services/debug-service.d.ts +133 -0
  133. package/dist/services/debug-service.js +163 -0
  134. package/dist/services/debug-service.js.map +1 -0
  135. package/dist/services/replay.d.ts +102 -0
  136. package/dist/services/replay.js +184 -0
  137. package/dist/services/replay.js.map +1 -0
  138. package/dist/services/session-builder.d.ts +65 -0
  139. package/dist/services/session-builder.js +198 -0
  140. package/dist/services/session-builder.js.map +1 -0
  141. package/dist/services/summarize.d.ts +59 -0
  142. package/dist/services/summarize.js +93 -0
  143. package/dist/services/summarize.js.map +1 -0
  144. package/dist/session/findings-store.d.ts +52 -0
  145. package/dist/session/findings-store.js +176 -0
  146. package/dist/session/findings-store.js.map +1 -0
  147. package/dist/session/manager.d.ts +47 -0
  148. package/dist/session/manager.js +66 -0
  149. package/dist/session/manager.js.map +1 -0
  150. package/dist/session/process-identity.d.ts +45 -0
  151. package/dist/session/process-identity.js +81 -0
  152. package/dist/session/process-identity.js.map +1 -0
  153. package/dist/session/session.d.ts +156 -0
  154. package/dist/session/session.js +309 -0
  155. package/dist/session/session.js.map +1 -0
  156. package/dist/session/state-file.d.ts +72 -0
  157. package/dist/session/state-file.js +104 -0
  158. package/dist/session/state-file.js.map +1 -0
  159. package/dist/session/workspace.d.ts +60 -0
  160. package/dist/session/workspace.js +75 -0
  161. package/dist/session/workspace.js.map +1 -0
  162. package/package.json +53 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Debug service — the business logic behind the five outer MCP tools.
3
+ *
4
+ * One conversational surface over one project (cwd): start a run, talk to it
5
+ * mid-flight, poll its findings, list targets, end it. Holds the cwd-keyed
6
+ * {@link SessionManager} (the one-run-per-project gate) and the resolved config,
7
+ * and delegates the heavy session assembly to an injected {@link SessionBuilder}
8
+ * seam — so the orchestration here unit-tests with no browser or network. The MCP
9
+ * handlers stay thin: validate input, call straight through to a method here.
10
+ *
11
+ * Sessions are keyed by cwd, but the tools speak `session_id`. Every id-bearing
12
+ * call resolves the active session for the cwd and fails loud
13
+ * ({@link SessionNotFoundError}) when the id does not match, so a stale id never
14
+ * silently drives the wrong run.
15
+ */
16
+ import { SessionBusyError, SessionNotFoundError, TargetNotFoundError } from '../errors.js';
17
+ import { noopStatePort } from '../session/state-file.js';
18
+ import { generateSessionId } from '../session/workspace.js';
19
+ /** Default wall-clock cap on a debug run before it auto-ends (overridable per run). */
20
+ export const DEFAULT_SESSION_TIMEOUT_MS = 300_000;
21
+ export class DebugService {
22
+ #manager;
23
+ #config;
24
+ #cwd;
25
+ #build;
26
+ #state;
27
+ #defaultTimeoutMs;
28
+ #now;
29
+ /** Live wall-clock timer for the active run; cleared when the run ends. */
30
+ #timer;
31
+ constructor(deps) {
32
+ this.#manager = deps.manager;
33
+ this.#config = deps.config;
34
+ this.#cwd = deps.cwd;
35
+ this.#build = deps.build;
36
+ this.#state = deps.state ?? noopStatePort;
37
+ this.#defaultTimeoutMs = deps.defaultTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;
38
+ this.#now = deps.now ?? (() => Date.now());
39
+ }
40
+ /**
41
+ * Open a run: assemble the session, take the profile lock, point the adapter at
42
+ * the target, and kick the loop off in the background. Fails loud if a run is
43
+ * already active for this cwd ({@link SessionBusyError}); never leaks a launched
44
+ * browser — a lost lock race or a failed `open` tears the session back down.
45
+ */
46
+ async start({ target, goal, criteria, timeoutMs }) {
47
+ const cwd = this.#cwd;
48
+ if (this.#manager.has(cwd)) {
49
+ throw new SessionBusyError(`A debug session ('${this.#manager.get(cwd).id}') is already active for '${cwd}'. ` +
50
+ 'End it before starting another — one run per project at a time.');
51
+ }
52
+ const id = generateSessionId(this.#now());
53
+ const built = await this.#build({ id, target, goal, criteria });
54
+ try {
55
+ this.#manager.start(cwd, built.session);
56
+ }
57
+ catch (err) {
58
+ await built.session.close().catch(() => undefined);
59
+ throw err;
60
+ }
61
+ try {
62
+ await built.open();
63
+ built.session.start(built.run);
64
+ }
65
+ catch (err) {
66
+ await this.#manager.end(cwd).catch(() => undefined);
67
+ throw err;
68
+ }
69
+ await this.#state.record({ sessionId: id, target, goal });
70
+ this.#armTimeout(timeoutMs ?? this.#defaultTimeoutMs);
71
+ return { session_id: id };
72
+ }
73
+ /** Arm the wall-clock cap: auto-end the run when it fires (replaces any prior timer). */
74
+ #armTimeout(ms) {
75
+ this.#clearTimeout();
76
+ this.#timer = setTimeout(() => {
77
+ this.#timer = undefined;
78
+ void this.endActive().catch(() => undefined);
79
+ }, ms);
80
+ }
81
+ /** Cancel the active run's wall-clock timer, if any. */
82
+ #clearTimeout() {
83
+ if (this.#timer !== undefined) {
84
+ clearTimeout(this.#timer);
85
+ this.#timer = undefined;
86
+ }
87
+ }
88
+ /** Queue a mid-run instruction for the active run's driver. */
89
+ send({ session_id, message }) {
90
+ this.#require(session_id).pushMessage(message);
91
+ return { ok: true, session_id };
92
+ }
93
+ /** Snapshot the run's findings — optionally long-poll (`wait`) and/or project a subset (`fields`). */
94
+ async getFindings({ session_id, wait, fields, }) {
95
+ const session = this.#require(session_id);
96
+ return fields && fields.length > 0
97
+ ? session.snapshot(fields, wait)
98
+ : session.snapshot(undefined, wait);
99
+ }
100
+ /** List configured targets (the whole catalog, or one when named) plus resolved models/workspace. */
101
+ describe({ target }) {
102
+ const entries = Object.entries(this.#config.targets);
103
+ const selected = target === undefined ? entries : entries.filter(([name]) => name === target);
104
+ if (target !== undefined && selected.length === 0) {
105
+ throw new TargetNotFoundError(`target '${target}' not found in config.targets`);
106
+ }
107
+ return {
108
+ targets: selected.map(([name, config]) => describeTarget(name, config)),
109
+ models: this.#config.models,
110
+ workspace: this.#config.workspace,
111
+ };
112
+ }
113
+ /** End the active run: abort the loop, close the adapter, free the profile lock. */
114
+ async end({ session_id }) {
115
+ this.#require(session_id);
116
+ this.#clearTimeout();
117
+ await this.#manager.end(this.#cwd);
118
+ await this.#state.clear();
119
+ return { ok: true, session_id };
120
+ }
121
+ /**
122
+ * End whatever run is active for this cwd, if any — the graceful-shutdown path
123
+ * for a SIGTERM/SIGINT, a CLI `stop`, or the wall-clock timeout firing. No-op
124
+ * when nothing is running.
125
+ */
126
+ async endActive() {
127
+ this.#clearTimeout();
128
+ if (!this.#manager.has(this.#cwd))
129
+ return;
130
+ await this.#manager.end(this.#cwd);
131
+ await this.#state.clear();
132
+ }
133
+ /** Resolve the active session for this cwd, asserting its id matches the caller's. */
134
+ #require(session_id) {
135
+ const session = this.#manager.get(this.#cwd);
136
+ if (session.id !== session_id) {
137
+ throw new SessionNotFoundError(`No active debug session '${session_id}' for '${this.#cwd}' (active session is '${session.id}').`);
138
+ }
139
+ return session;
140
+ }
141
+ }
142
+ /** Whether a target is in attach mode (connects to a running instance, never start/stop). */
143
+ function isAttach(target) {
144
+ if (target.adapter === 'browser')
145
+ return target.cdpUrl != null;
146
+ if (target.adapter === 'android')
147
+ return target.adbSerial != null;
148
+ return false;
149
+ }
150
+ /** Project one configured target onto its public {@link TargetInfo} (no secrets). */
151
+ function describeTarget(name, target) {
152
+ const base = {
153
+ name,
154
+ adapter: target.adapter,
155
+ mode: isAttach(target) ? 'attach' : 'managed',
156
+ operational: target.adapter === 'browser' || target.adapter === 'desktop',
157
+ };
158
+ if (target.adapter === 'browser') {
159
+ return { ...base, url: target.url, headless: target.headless };
160
+ }
161
+ return base;
162
+ }
163
+ //# sourceMappingURL=debug-service.js.map
@@ -0,0 +1 @@
1
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@@
1
+ /**
2
+ * `replay` — stitch a run's ordered screenshots into a short captioned `replay.mp4`.
3
+ *
4
+ * The session keeps every screenshot ordered on disk (`screenshots/NNN-<label>.png`).
5
+ * At the end of a run this service turns them into one scannable video — PR evidence
6
+ * a reviewer (human or agent) watches in ~10s instead of pulling the branch and
7
+ * clicking through (see `idea/workspace.md`). Each frame holds for a beat with its
8
+ * step label burned in as a caption, so the clip narrates itself.
9
+ *
10
+ * The ffmpeg invocation hides behind a small {@link ReplayEncoder} exec seam, so the
11
+ * arg-building ({@link buildFfmpegArgs}) is a pure function the tests assert against
12
+ * with no subprocess — the same shape as `summarize`'s model seam and `look`'s vision
13
+ * seam. {@link createReplayStep} binds the real `spawn('ffmpeg', …)` plus a resolved
14
+ * caption font into the {@link ReplayStep} the session runs once the verdict settles.
15
+ *
16
+ * ffmpeg is optional tooling, so {@link createReplayStep} probes for the binary
17
+ * ({@link ffmpegOnPath}) BEFORE stitching: absent, it skips cleanly with a note the
18
+ * session folds into the findings and a loud line in `agent.log` — never a crash.
19
+ * When ffmpeg IS present this layer fails loud — a non-zero exit throws a
20
+ * {@link ReplayError} — and the session decides to swallow it. The session wraps the
21
+ * whole step fail-soft (a missing ffmpeg or font must never block teardown). When no
22
+ * caption font is installed the stitch still runs, just without burned-in captions.
23
+ */
24
+ import type { ScreenshotFrame } from '../session/findings-store.js';
25
+ import type { ReplayStep } from '../session/session.js';
26
+ /** One frame to stitch: the PNG path plus the caption burned onto it. */
27
+ export interface ReplayFrame {
28
+ /** Absolute path to the source PNG. */
29
+ path: string;
30
+ /** Short human caption (the step label). */
31
+ caption: string;
32
+ }
33
+ /** Resolved stitch tunables `buildFfmpegArgs` reads (no defaults — fully specified). */
34
+ export interface RenderConfig {
35
+ /** Seconds each frame holds on screen. */
36
+ secondsPerFrame: number;
37
+ /** Canvas the frames are scaled+padded into (even px). */
38
+ width: number;
39
+ /** Canvas height (even px). */
40
+ height: number;
41
+ /** Output frame rate. */
42
+ fps: number;
43
+ /** TrueType font for burned-in captions; omit to stitch without captions. */
44
+ fontFile?: string;
45
+ }
46
+ /**
47
+ * The exec seam {@link renderReplay} drives — runs ffmpeg with the built args,
48
+ * resolving on success and throwing on failure. {@link createReplayStep} binds it to
49
+ * a real `spawn`; tests pass a fake that records the args.
50
+ */
51
+ export type ReplayEncoder = (args: readonly string[]) => Promise<void>;
52
+ /**
53
+ * Build the full ffmpeg arg list for the stitch — pure and deterministic, so the
54
+ * tests assert it directly. Each PNG becomes a looped, time-limited input; every
55
+ * input is scaled into a uniform letterboxed canvas (so differing screenshot sizes
56
+ * never break the concat), optionally captioned, then concatenated into one stream.
57
+ */
58
+ export declare function buildFfmpegArgs(frames: readonly ReplayFrame[], output: string, cfg: RenderConfig): string[];
59
+ /**
60
+ * Stitch `frames` into `output` over the {@link ReplayEncoder} seam. Returns the
61
+ * output path on success, or `null` when there are no frames (nothing to stitch).
62
+ * Pure over the seam, so it unit-tests against a fake with no subprocess.
63
+ * @throws {ReplayError} propagated from the encoder when ffmpeg fails.
64
+ */
65
+ export declare function renderReplay(encode: ReplayEncoder, frames: readonly ReplayFrame[], output: string, cfg: RenderConfig): Promise<string | null>;
66
+ /** First installed caption font, or `undefined` when none is found (→ stitch without captions). */
67
+ export declare function resolveFontFile(): string | undefined;
68
+ /**
69
+ * True when the ffmpeg binary is resolvable: a path-like `bin` (absolute or relative)
70
+ * is checked directly; a bare command is searched across `PATH`. Pure and synchronous
71
+ * (no subprocess), so {@link createReplayStep} can probe before stitching and skip
72
+ * cleanly when ffmpeg is absent — never spawning a process that won't exist.
73
+ */
74
+ export declare function ffmpegOnPath(bin: string): boolean;
75
+ /** What {@link createReplayStep} needs to stitch one session's replay. */
76
+ export interface ReplayStepDeps {
77
+ /** Lists the run's ordered screenshot frames (the `FindingsStore` satisfies this). */
78
+ screenshots: {
79
+ listScreenshots(): Promise<ScreenshotFrame[]>;
80
+ };
81
+ /** Absolute path to write the stitched video (`sessionPaths.replayMp4`). */
82
+ output: string;
83
+ /** ffmpeg binary; defaults to `ffmpeg` (resolved on PATH). */
84
+ ffmpegBin?: string;
85
+ /** Override stitch tunables (frame duration, canvas, fps). */
86
+ render?: Partial<Omit<RenderConfig, 'fontFile'>>;
87
+ /** Loud breadcrumb sink (`agent.log`); defaults to a no-op. Surfaces an absent ffmpeg. */
88
+ log?: (line: string) => void;
89
+ /** Probe whether ffmpeg is installed; defaults to {@link ffmpegOnPath}. A seam for tests. */
90
+ hasFfmpeg?: (bin: string) => boolean;
91
+ }
92
+ /**
93
+ * Bind {@link renderReplay} to the real ffmpeg spawn + a resolved caption font,
94
+ * yielding the {@link ReplayStep} the session runs after the verdict settles. The
95
+ * session stays tool- and path-blind; everything ffmpeg-shaped lives here.
96
+ *
97
+ * Probes for ffmpeg first (graceful when it is not installed): no frames → a silent
98
+ * skip; ffmpeg absent → a skip carrying a `note` the session records in the findings,
99
+ * plus a loud line in `agent.log` so the missing `replay.mp4` is never a mystery; a
100
+ * stitched clip → its path for `findings.evidence`.
101
+ */
102
+ export declare function createReplayStep(deps: ReplayStepDeps): ReplayStep;
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `replay` — stitch a run's ordered screenshots into a short captioned `replay.mp4`.
3
+ *
4
+ * The session keeps every screenshot ordered on disk (`screenshots/NNN-<label>.png`).
5
+ * At the end of a run this service turns them into one scannable video — PR evidence
6
+ * a reviewer (human or agent) watches in ~10s instead of pulling the branch and
7
+ * clicking through (see `idea/workspace.md`). Each frame holds for a beat with its
8
+ * step label burned in as a caption, so the clip narrates itself.
9
+ *
10
+ * The ffmpeg invocation hides behind a small {@link ReplayEncoder} exec seam, so the
11
+ * arg-building ({@link buildFfmpegArgs}) is a pure function the tests assert against
12
+ * with no subprocess — the same shape as `summarize`'s model seam and `look`'s vision
13
+ * seam. {@link createReplayStep} binds the real `spawn('ffmpeg', …)` plus a resolved
14
+ * caption font into the {@link ReplayStep} the session runs once the verdict settles.
15
+ *
16
+ * ffmpeg is optional tooling, so {@link createReplayStep} probes for the binary
17
+ * ({@link ffmpegOnPath}) BEFORE stitching: absent, it skips cleanly with a note the
18
+ * session folds into the findings and a loud line in `agent.log` — never a crash.
19
+ * When ffmpeg IS present this layer fails loud — a non-zero exit throws a
20
+ * {@link ReplayError} — and the session decides to swallow it. The session wraps the
21
+ * whole step fail-soft (a missing ffmpeg or font must never block teardown). When no
22
+ * caption font is installed the stitch still runs, just without burned-in captions.
23
+ */
24
+ import { spawn } from 'node:child_process';
25
+ import { existsSync } from 'node:fs';
26
+ import { delimiter, join } from 'node:path';
27
+ import { ReplayError } from '../errors.js';
28
+ /** Stitch defaults — 2s/frame at 720p30 makes a calm, scannable clip. */
29
+ const DEFAULTS = { secondsPerFrame: 2, width: 1280, height: 720, fps: 30 };
30
+ /** Common installed font paths probed for burned-in captions (Linux + macOS). */
31
+ const FONT_CANDIDATES = [
32
+ '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
33
+ '/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf',
34
+ '/usr/share/fonts/dejavu/DejaVuSans.ttf',
35
+ '/usr/share/fonts/TTF/DejaVuSans.ttf',
36
+ '/System/Library/Fonts/Supplemental/Arial.ttf',
37
+ '/Library/Fonts/Arial.ttf',
38
+ ];
39
+ /**
40
+ * Constrain a caption to `[a-z0-9 ]` so it drops cleanly into the ffmpeg filtergraph
41
+ * (no `:`, `,`, `\`, `'` or `%` to escape). Labels already arrive de-slugged; this
42
+ * just guards. Empties fall back to `step`.
43
+ */
44
+ function sanitizeCaption(caption) {
45
+ const clean = caption
46
+ .toLowerCase()
47
+ .replace(/[^a-z0-9 ]+/g, ' ')
48
+ .replace(/\s+/g, ' ')
49
+ .trim();
50
+ return clean || 'step';
51
+ }
52
+ /** One `drawtext` filter that burns `caption` into a centred bottom bar. */
53
+ function drawtext(caption, fontFile) {
54
+ return [
55
+ `drawtext=fontfile=${fontFile}`,
56
+ `text=${sanitizeCaption(caption)}`,
57
+ 'fontcolor=white',
58
+ 'fontsize=28',
59
+ 'box=1',
60
+ 'boxcolor=black@0.5',
61
+ 'boxborderw=12',
62
+ 'x=(w-text_w)/2',
63
+ 'y=h-th-32',
64
+ ].join(':');
65
+ }
66
+ /**
67
+ * Build the full ffmpeg arg list for the stitch — pure and deterministic, so the
68
+ * tests assert it directly. Each PNG becomes a looped, time-limited input; every
69
+ * input is scaled into a uniform letterboxed canvas (so differing screenshot sizes
70
+ * never break the concat), optionally captioned, then concatenated into one stream.
71
+ */
72
+ export function buildFfmpegArgs(frames, output, cfg) {
73
+ const { secondsPerFrame, width, height, fps, fontFile } = cfg;
74
+ const inputs = [];
75
+ const chains = [];
76
+ frames.forEach((frame, i) => {
77
+ inputs.push('-loop', '1', '-t', String(secondsPerFrame), '-i', frame.path);
78
+ const steps = [
79
+ `scale=${width}:${height}:force_original_aspect_ratio=decrease`,
80
+ `pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2:color=black`,
81
+ 'setsar=1',
82
+ ];
83
+ if (fontFile !== undefined)
84
+ steps.push(drawtext(frame.caption, fontFile));
85
+ chains.push(`[${i}:v]${steps.join(',')}[v${i}]`);
86
+ });
87
+ const concatInputs = frames.map((_, i) => `[v${i}]`).join('');
88
+ const filter = `${chains.join(';')};${concatInputs}concat=n=${frames.length}:v=1:a=0[out]`;
89
+ return [
90
+ '-y',
91
+ ...inputs,
92
+ '-filter_complex',
93
+ filter,
94
+ '-map',
95
+ '[out]',
96
+ '-r',
97
+ String(fps),
98
+ '-pix_fmt',
99
+ 'yuv420p',
100
+ output,
101
+ ];
102
+ }
103
+ /**
104
+ * Stitch `frames` into `output` over the {@link ReplayEncoder} seam. Returns the
105
+ * output path on success, or `null` when there are no frames (nothing to stitch).
106
+ * Pure over the seam, so it unit-tests against a fake with no subprocess.
107
+ * @throws {ReplayError} propagated from the encoder when ffmpeg fails.
108
+ */
109
+ export async function renderReplay(encode, frames, output, cfg) {
110
+ if (frames.length === 0)
111
+ return null;
112
+ await encode(buildFfmpegArgs(frames, output, cfg));
113
+ return output;
114
+ }
115
+ /** First installed caption font, or `undefined` when none is found (→ stitch without captions). */
116
+ export function resolveFontFile() {
117
+ return FONT_CANDIDATES.find((path) => existsSync(path));
118
+ }
119
+ /**
120
+ * True when the ffmpeg binary is resolvable: a path-like `bin` (absolute or relative)
121
+ * is checked directly; a bare command is searched across `PATH`. Pure and synchronous
122
+ * (no subprocess), so {@link createReplayStep} can probe before stitching and skip
123
+ * cleanly when ffmpeg is absent — never spawning a process that won't exist.
124
+ */
125
+ export function ffmpegOnPath(bin) {
126
+ if (bin.includes('/'))
127
+ return existsSync(bin);
128
+ const dirs = (process.env.PATH ?? '').split(delimiter).filter((dir) => dir.length > 0);
129
+ return dirs.some((dir) => existsSync(join(dir, bin)));
130
+ }
131
+ /** The real encoder: spawn ffmpeg, resolve on exit 0, throw {@link ReplayError} otherwise. */
132
+ function spawnFfmpeg(bin) {
133
+ return (args) => new Promise((resolve, reject) => {
134
+ const child = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] });
135
+ let stderr = '';
136
+ child.stderr?.on('data', (chunk) => {
137
+ stderr += chunk.toString();
138
+ });
139
+ child.on('error', (err) => reject(new ReplayError(`ffmpeg ('${bin}') failed to launch: ${err.message}`)));
140
+ child.on('close', (code) => {
141
+ if (code === 0)
142
+ resolve();
143
+ else
144
+ reject(new ReplayError(`ffmpeg exited ${code ?? 'null'}: ${stderr.trim().slice(-400)}`));
145
+ });
146
+ });
147
+ }
148
+ /**
149
+ * Bind {@link renderReplay} to the real ffmpeg spawn + a resolved caption font,
150
+ * yielding the {@link ReplayStep} the session runs after the verdict settles. The
151
+ * session stays tool- and path-blind; everything ffmpeg-shaped lives here.
152
+ *
153
+ * Probes for ffmpeg first (graceful when it is not installed): no frames → a silent
154
+ * skip; ffmpeg absent → a skip carrying a `note` the session records in the findings,
155
+ * plus a loud line in `agent.log` so the missing `replay.mp4` is never a mystery; a
156
+ * stitched clip → its path for `findings.evidence`.
157
+ */
158
+ export function createReplayStep(deps) {
159
+ const bin = deps.ffmpegBin ?? 'ffmpeg';
160
+ const log = deps.log ?? (() => undefined);
161
+ const hasFfmpeg = deps.hasFfmpeg ?? ffmpegOnPath;
162
+ const encode = spawnFfmpeg(bin);
163
+ const cfg = {
164
+ secondsPerFrame: deps.render?.secondsPerFrame ?? DEFAULTS.secondsPerFrame,
165
+ width: deps.render?.width ?? DEFAULTS.width,
166
+ height: deps.render?.height ?? DEFAULTS.height,
167
+ fps: deps.render?.fps ?? DEFAULTS.fps,
168
+ fontFile: resolveFontFile(),
169
+ };
170
+ return async () => {
171
+ const frames = await deps.screenshots.listScreenshots();
172
+ if (frames.length === 0)
173
+ return { kind: 'skipped' }; // nothing to stitch
174
+ if (!hasFfmpeg(bin)) {
175
+ const note = `ffmpeg not found ('${bin}'); replay.mp4 was not generated — install ffmpeg to enable replay video`;
176
+ log(`replay: ${note}`);
177
+ return { kind: 'skipped', note };
178
+ }
179
+ const replayFrames = frames.map((f) => ({ path: f.path, caption: f.label }));
180
+ const path = await renderReplay(encode, replayFrames, deps.output, cfg);
181
+ return path === null ? { kind: 'skipped' } : { kind: 'rendered', path };
182
+ };
183
+ }
184
+ //# sourceMappingURL=replay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay.js","sourceRoot":"","sources":["../../src/services/replay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAiC3C,yEAAyE;AACzE,MAAM,QAAQ,GAAG,EAAE,eAAe,EAAE,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAW,CAAC;AAEpF,iFAAiF;AACjF,MAAM,e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,SAAS,EAAE,IAAI,EAAE,CAAC;QACnC,CAAC;QACD,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAC7E,MAAM,IAAI,GAAG,MAAM,YAAY,CAAC,MAAM,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QACxE,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;IAC1E,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Session builder — assemble one debug run from the resolved config.
3
+ *
4
+ * The heavy wiring behind `start_debug`, in one focused place: resolve the
5
+ * target adapter (CDP browser today), build the inner belt
6
+ * (`observe`/`act`/`look`/`report`) over it, compose the system prompt, and
7
+ * bundle the loop runner the {@link Session} drives in the background. All of it
8
+ * binds to a single per-run {@link FindingsStore} so the running progress trail
9
+ * and the terminal `report` write to the same `findings.json`.
10
+ *
11
+ * Returns an *un-registered* session plus the `open`/`run` seams the service
12
+ * fires only AFTER it has taken the project's profile lock — so a busy race never
13
+ * leaks a launched browser. The builder stays adapter- and model-blind past this
14
+ * seam; swapping the driver model or the target never touches the service.
15
+ */
16
+ import type { LanguageModel } from 'ai';
17
+ import type { ResolvedConfig } from '../config/load.js';
18
+ import { type LoopRunner, Session } from '../session/session.js';
19
+ import { type WorkspacePaths } from '../session/workspace.js';
20
+ /** The three actors the belt + loop + post-verdict step bind to, resolved once and shared across runs. */
21
+ export interface BuilderModels {
22
+ /** fast guy — the blind text driver running the click loop. */
23
+ driver: LanguageModel;
24
+ /** vision guy — the multimodal eyes `look` calls through. */
25
+ vision: LanguageModel;
26
+ /** summary guy — condenses the terminal findings into one paragraph for the smart agent. */
27
+ summary: LanguageModel;
28
+ }
29
+ /** What the builder needs that does not change between runs. */
30
+ export interface SessionBuilderDeps {
31
+ config: ResolvedConfig;
32
+ models: BuilderModels;
33
+ workspace: WorkspacePaths;
34
+ }
35
+ /** The per-run inputs `start_debug` hands over. */
36
+ export interface BuildSessionParams {
37
+ /** Stable session id (from `generateSessionId`). */
38
+ id: string;
39
+ /** Target name — a key in `config.targets` (e.g. `web`). */
40
+ target: string;
41
+ /** The story the smart agent wants done. */
42
+ goal: string;
43
+ /** Optional pass/fail criteria, one rule per line. */
44
+ criteria?: string;
45
+ }
46
+ /** A built-but-unregistered session plus the seams the service fires post-lock. */
47
+ export interface BuiltSession {
48
+ /** Ready to register with the manager; not yet opened or started. */
49
+ session: Session;
50
+ /** Navigate the adapter to the target (launches/attaches the browser page). */
51
+ open(): Promise<void>;
52
+ /** The background loop runner handed to `session.start()`. */
53
+ run: LoopRunner;
54
+ }
55
+ /** The builder seam the service calls through; the default binds {@link buildSession}. */
56
+ export type SessionBuilder = (params: BuildSessionParams) => Promise<BuiltSession>;
57
+ /** Bind {@link buildSession} to its shared deps, yielding the per-run {@link SessionBuilder}. */
58
+ export declare function makeSessionBuilder(deps: SessionBuilderDeps): SessionBuilder;
59
+ /**
60
+ * Assemble a debug run: adapter + belt + composed prompt + loop runner, all bound
61
+ * to a fresh {@link FindingsStore}. Throws {@link TargetNotFoundError} if `target`
62
+ * is not configured — BEFORE any device or browser launches, so a bad request never
63
+ * leaks a process.
64
+ */
65
+ export declare function buildSession(deps: SessionBuilderDeps, params: BuildSessionParams): Promise<BuiltSession>;