@developerz.ai/ui-debugger-mcp 1.9.0 → 1.10.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 (201) hide show
  1. package/README.md +56 -44
  2. package/dist/adapters/android/adb.d.ts +19 -7
  3. package/dist/adapters/android/adb.js +50 -13
  4. package/dist/adapters/android/adb.js.map +1 -1
  5. package/dist/adapters/android/android-adapter.d.ts +42 -2
  6. package/dist/adapters/android/android-adapter.js +366 -36
  7. package/dist/adapters/android/android-adapter.js.map +1 -1
  8. package/dist/adapters/android/commands.js.map +1 -1
  9. package/dist/adapters/android/ports.js.map +1 -1
  10. package/dist/adapters/android/sdk.d.ts +65 -0
  11. package/dist/adapters/android/sdk.js +107 -0
  12. package/dist/adapters/android/sdk.js.map +1 -0
  13. package/dist/adapters/android/uiautomator.d.ts +23 -7
  14. package/dist/adapters/android/uiautomator.js +31 -7
  15. package/dist/adapters/android/uiautomator.js.map +1 -1
  16. package/dist/adapters/availability.d.ts +39 -0
  17. package/dist/adapters/availability.js +62 -0
  18. package/dist/adapters/availability.js.map +1 -0
  19. package/dist/adapters/browser/browser-adapter.d.ts +11 -22
  20. package/dist/adapters/browser/browser-adapter.js +98 -67
  21. package/dist/adapters/browser/browser-adapter.js.map +1 -1
  22. package/dist/adapters/browser/cdp.d.ts +15 -7
  23. package/dist/adapters/browser/cdp.js +25 -3
  24. package/dist/adapters/browser/cdp.js.map +1 -1
  25. package/dist/adapters/browser/filters.d.ts +1 -1
  26. package/dist/adapters/browser/filters.js.map +1 -1
  27. package/dist/adapters/browser/geometry.js.map +1 -1
  28. package/dist/adapters/browser/launch.d.ts +14 -5
  29. package/dist/adapters/browser/launch.js +14 -5
  30. package/dist/adapters/browser/launch.js.map +1 -1
  31. package/dist/adapters/browser/lifecycle.d.ts +58 -0
  32. package/dist/adapters/browser/lifecycle.js +98 -0
  33. package/dist/adapters/browser/lifecycle.js.map +1 -0
  34. package/dist/adapters/browser/log-filters.d.ts +2 -2
  35. package/dist/adapters/browser/log-filters.js.map +1 -1
  36. package/dist/adapters/browser/log-format.d.ts +14 -23
  37. package/dist/adapters/browser/log-format.js +16 -55
  38. package/dist/adapters/browser/log-format.js.map +1 -1
  39. package/dist/adapters/browser/tab-context.d.ts +30 -0
  40. package/dist/adapters/browser/tab-context.js +41 -0
  41. package/dist/adapters/browser/tab-context.js.map +1 -0
  42. package/dist/adapters/contract.d.ts +91 -5
  43. package/dist/adapters/contract.js +7 -2
  44. package/dist/adapters/contract.js.map +1 -1
  45. package/dist/adapters/desktop/atspi-busctl.d.ts +26 -0
  46. package/dist/adapters/desktop/atspi-busctl.js +330 -0
  47. package/dist/adapters/desktop/atspi-busctl.js.map +1 -0
  48. package/dist/adapters/desktop/atspi-parse.d.ts +39 -0
  49. package/dist/adapters/desktop/atspi-parse.js +155 -0
  50. package/dist/adapters/desktop/atspi-parse.js.map +1 -0
  51. package/dist/adapters/desktop/atspi.d.ts +75 -50
  52. package/dist/adapters/desktop/atspi.js +64 -285
  53. package/dist/adapters/desktop/atspi.js.map +1 -1
  54. package/dist/adapters/desktop/capture.d.ts +11 -20
  55. package/dist/adapters/desktop/capture.js +68 -37
  56. package/dist/adapters/desktop/capture.js.map +1 -1
  57. package/dist/adapters/desktop/desktop-adapter.d.ts +20 -2
  58. package/dist/adapters/desktop/desktop-adapter.js +91 -9
  59. package/dist/adapters/desktop/desktop-adapter.js.map +1 -1
  60. package/dist/adapters/desktop/input.d.ts +18 -4
  61. package/dist/adapters/desktop/input.js +15 -10
  62. package/dist/adapters/desktop/input.js.map +1 -1
  63. package/dist/adapters/desktop/proc.d.ts +32 -4
  64. package/dist/adapters/desktop/proc.js +33 -6
  65. package/dist/adapters/desktop/proc.js.map +1 -1
  66. package/dist/adapters/factory.d.ts +12 -5
  67. package/dist/adapters/factory.js +29 -3
  68. package/dist/adapters/factory.js.map +1 -1
  69. package/dist/adapters/log-format.d.ts +32 -0
  70. package/dist/adapters/log-format.js +39 -0
  71. package/dist/adapters/log-format.js.map +1 -0
  72. package/dist/agent/belt/act.d.ts +421 -21
  73. package/dist/agent/belt/act.js +4 -4
  74. package/dist/agent/belt/act.js.map +1 -1
  75. package/dist/agent/belt/look.d.ts +471 -14
  76. package/dist/agent/belt/look.js +74 -12
  77. package/dist/agent/belt/look.js.map +1 -1
  78. package/dist/agent/belt/observe.d.ts +663 -42
  79. package/dist/agent/belt/observe.js +76 -12
  80. package/dist/agent/belt/observe.js.map +1 -1
  81. package/dist/agent/belt/report.d.ts +754 -48
  82. package/dist/agent/belt/report.js +121 -38
  83. package/dist/agent/belt/report.js.map +1 -1
  84. package/dist/agent/belt/trail.d.ts +44 -16
  85. package/dist/agent/belt/trail.js +46 -11
  86. package/dist/agent/belt/trail.js.map +1 -1
  87. package/dist/agent/capabilities.js.map +1 -1
  88. package/dist/agent/fallback.d.ts +33 -0
  89. package/dist/agent/fallback.js +84 -0
  90. package/dist/agent/fallback.js.map +1 -0
  91. package/dist/agent/loop.d.ts +54 -52
  92. package/dist/agent/loop.js +173 -176
  93. package/dist/agent/loop.js.map +1 -1
  94. package/dist/agent/models.d.ts +10 -6
  95. package/dist/agent/models.js +15 -9
  96. package/dist/agent/models.js.map +1 -1
  97. package/dist/agent/prompts/compose.d.ts +1 -1
  98. package/dist/agent/prompts/debug-agent.js +45 -8
  99. package/dist/agent/prompts/debug-agent.js.map +1 -1
  100. package/dist/agent/prompts/web-addendum.d.ts +1 -1
  101. package/dist/agent/prompts/web-addendum.js +15 -3
  102. package/dist/agent/prompts/web-addendum.js.map +1 -1
  103. package/dist/agent/provider.d.ts +38 -0
  104. package/dist/agent/provider.js +55 -3
  105. package/dist/agent/provider.js.map +1 -1
  106. package/dist/boot.d.ts +64 -0
  107. package/dist/boot.js +145 -0
  108. package/dist/boot.js.map +1 -0
  109. package/dist/cli/chromium-libs.d.ts +262 -0
  110. package/dist/cli/chromium-libs.js +522 -0
  111. package/dist/cli/chromium-libs.js.map +1 -0
  112. package/dist/cli/control.js +51 -9
  113. package/dist/cli/control.js.map +1 -1
  114. package/dist/cli/init.d.ts +52 -3
  115. package/dist/cli/init.js +62 -10
  116. package/dist/cli/init.js.map +1 -1
  117. package/dist/config/load.d.ts +25 -8
  118. package/dist/config/load.js +40 -13
  119. package/dist/config/load.js.map +1 -1
  120. package/dist/config/schema.d.ts +18 -6
  121. package/dist/config/schema.js +22 -7
  122. package/dist/config/schema.js.map +1 -1
  123. package/dist/errors.d.ts +14 -0
  124. package/dist/errors.js +18 -0
  125. package/dist/errors.js.map +1 -1
  126. package/dist/findings/schema.d.ts +44 -6
  127. package/dist/findings/schema.js +39 -3
  128. package/dist/findings/schema.js.map +1 -1
  129. package/dist/index.d.ts +1 -1
  130. package/dist/index.js +1 -1
  131. package/dist/index.js.map +1 -1
  132. package/dist/main.js +4 -82
  133. package/dist/main.js.map +1 -1
  134. package/dist/mcp/server.js.map +1 -1
  135. package/dist/mcp/tools/describe.d.ts +5 -4
  136. package/dist/mcp/tools/describe.js +14 -10
  137. package/dist/mcp/tools/describe.js.map +1 -1
  138. package/dist/mcp/tools/end-session.d.ts +3 -1
  139. package/dist/mcp/tools/end-session.js +7 -3
  140. package/dist/mcp/tools/end-session.js.map +1 -1
  141. package/dist/mcp/tools/output.d.ts +5 -4
  142. package/dist/mcp/tools/output.js +10 -2
  143. package/dist/mcp/tools/output.js.map +1 -1
  144. package/dist/mcp/tools/result.d.ts +10 -1
  145. package/dist/mcp/tools/result.js +8 -6
  146. package/dist/mcp/tools/result.js.map +1 -1
  147. package/dist/mcp/tools/start-debug.js +7 -5
  148. package/dist/mcp/tools/start-debug.js.map +1 -1
  149. package/dist/redact.d.ts +28 -0
  150. package/dist/redact.js +51 -0
  151. package/dist/redact.js.map +1 -0
  152. package/dist/services/catalog.d.ts +28 -0
  153. package/dist/services/catalog.js +65 -0
  154. package/dist/services/catalog.js.map +1 -0
  155. package/dist/services/debug-api.d.ts +172 -0
  156. package/dist/services/debug-api.js +9 -0
  157. package/dist/services/debug-api.js.map +1 -0
  158. package/dist/services/debug-service.d.ts +25 -173
  159. package/dist/services/debug-service.js +108 -175
  160. package/dist/services/debug-service.js.map +1 -1
  161. package/dist/services/login.d.ts +7 -2
  162. package/dist/services/login.js +203 -29
  163. package/dist/services/login.js.map +1 -1
  164. package/dist/services/retained-snapshot.d.ts +36 -0
  165. package/dist/services/retained-snapshot.js +63 -0
  166. package/dist/services/retained-snapshot.js.map +1 -0
  167. package/dist/services/session-builder.d.ts +26 -0
  168. package/dist/services/session-builder.js +46 -19
  169. package/dist/services/session-builder.js.map +1 -1
  170. package/dist/services/start-guards.d.ts +32 -0
  171. package/dist/services/start-guards.js +50 -0
  172. package/dist/services/start-guards.js.map +1 -0
  173. package/dist/services/summarize.d.ts +12 -3
  174. package/dist/services/summarize.js +13 -5
  175. package/dist/services/summarize.js.map +1 -1
  176. package/dist/session/cleanup.js.map +1 -1
  177. package/dist/session/findings-store.d.ts +2 -1
  178. package/dist/session/findings-store.js +30 -2
  179. package/dist/session/findings-store.js.map +1 -1
  180. package/dist/session/live-pointer.d.ts +19 -0
  181. package/dist/session/live-pointer.js +41 -0
  182. package/dist/session/live-pointer.js.map +1 -0
  183. package/dist/session/manager.d.ts +11 -1
  184. package/dist/session/manager.js +46 -2
  185. package/dist/session/manager.js.map +1 -1
  186. package/dist/session/owner-lock.d.ts +208 -0
  187. package/dist/session/owner-lock.js +499 -0
  188. package/dist/session/owner-lock.js.map +1 -0
  189. package/dist/session/process-identity.js.map +1 -1
  190. package/dist/session/session.js +61 -7
  191. package/dist/session/session.js.map +1 -1
  192. package/dist/session/state-file.d.ts +74 -14
  193. package/dist/session/state-file.js +203 -21
  194. package/dist/session/state-file.js.map +1 -1
  195. package/package.json +7 -7
  196. package/dist/adapters/android/android-adapter.test-helpers.d.ts +0 -52
  197. package/dist/adapters/android/android-adapter.test-helpers.js +0 -115
  198. package/dist/adapters/android/android-adapter.test-helpers.js.map +0 -1
  199. package/dist/mcp/server.test-helpers.d.ts +0 -23
  200. package/dist/mcp/server.test-helpers.js +0 -49
  201. package/dist/mcp/server.test-helpers.js.map +0 -1
@@ -9,10 +9,10 @@
9
9
  * any mid-run messages (the smart agent's `send_message`) into a standing
10
10
  * instruction block re-appended to EVERY turn (the SDK rebuilds each step's
11
11
  * prompt from scratch), so the driver adapts without restarting or forgetting.
12
- * - **incremental findings** — `onStepFinish` snapshots the shared act trail
13
- * (`act` records each step as it happens) plus `look`'s visual issues and
14
- * error-level console rows, and flushes them as `status: 'running'` findings,
15
- * so `get_findings` streams findings before the verdict lands, and a run that
12
+ * - **incremental findings** — `onStepFinish` snapshots the shared evidence
13
+ * trail (the belt's tools record each step, console error and look issue as
14
+ * it happens) and flushes it as `status: 'running'` findings, so
15
+ * `get_findings` streams findings before the verdict lands, and a run that
16
16
  * crashes, aborts or hits the step cap keeps everything surfaced so far.
17
17
  *
18
18
  * Adapter-blind and model-blind like the belt: the loop never touches a protocol
@@ -23,7 +23,8 @@
23
23
  * aborted run rejects loud (wired to `end_session`), never a silent half-finish.
24
24
  */
25
25
  import { type LanguageModel, type ModelMessage, type Tool, ToolLoopAgent } from 'ai';
26
- import type { Bug, Findings, Step, VisualIssue } from '../findings/schema.js';
26
+ import type { Findings } from '../findings/schema.js';
27
+ import type { ActTrail, TrailEvidence } from './belt/trail.js';
27
28
  /**
28
29
  * Safety cap on driver steps before the loop force-stops (paired with the
29
30
  * report-RESULT stop condition in {@link createDebugAgent}).
@@ -85,24 +86,45 @@ export interface FinishedStep {
85
86
  * into `standing` — the run-long list of caller instructions — then, while any
86
87
  * exist, appends ONE user message rebuilt from the whole list.
87
88
  *
88
- * Rebuilt on EVERY step, not just the drain step: the SDK composes each step's
89
- * prompt fresh from `[...initialMessages, ...responseMessages]` and never persists
90
- * a `prepareStep` messages override, so an instruction injected once would reach
91
- * the driver for exactly one step and then vanish. Because the base `messages`
92
- * arrive without the previous step's injection, re-appending the single rebuilt
93
- * block never accumulates duplicates. Returns `{}` when no instructions exist.
89
+ * Rebuilt on EVERY step, not just the drain step: an instruction injected once
90
+ * must reach the driver on every later step too. AI SDK 7 persists the previous
91
+ * step's `prepareStep` override into the running transcript
92
+ * (`messagesForNextStep = [...stepMessages, ...stepResponseMessages]`), so the
93
+ * caller strips last step's fold/nudge first ({@link stripInjectedStepMessages})
94
+ * and this re-appends exactly one fresh block — never accumulation. Returns
95
+ * `{}` when no instructions exist.
94
96
  */
95
97
  export declare function foldInstructionsIntoStep(inbox: LoopInbox, standing: string[], messages: ModelMessage[]): {
96
98
  messages: ModelMessage[];
97
99
  } | Record<string, never>;
100
+ /**
101
+ * Drop the fold/nudge messages a PREVIOUS step's `prepareStep` injected.
102
+ *
103
+ * AI SDK 7 persists the override into the running transcript
104
+ * (`messagesForNextStep = [...stepMessages, ...stepResponseMessages]` in
105
+ * `generateText`); AI SDK 6 rebuilt each step's prompt from response messages
106
+ * alone and discarded it. Without stripping, the re-appended instruction fold
107
+ * duplicates one copy per step, and a stale earlier nudge precedes the fresh
108
+ * one (breaking fold-before-nudge ordering). Stripping first restores exactly
109
+ * the AI SDK 6 chain this loop was written against, so the rebuilt override is
110
+ * correct whether the SDK persists it or not.
111
+ */
112
+ export declare function stripInjectedStepMessages(messages: ModelMessage[]): ModelMessage[];
98
113
  /** What a pruned frame collapses to — tells the driver how to get a fresh one. */
99
114
  export declare const STALE_FRAME_NOTE = "[stale frame removed \u2014 call look again for a fresh screenshot]";
100
115
  /**
101
116
  * Keep only the NEWEST self-look frame in the transcript. The SDK re-sends every
102
117
  * tool result on every step, so each `look` image would otherwise ride along for
103
118
  * the rest of the run — N looks × M steps of image tokens. Rebuilt per step in
104
- * `prepareStep` (overrides never persist), like the instruction fold. Returns the
105
- * SAME array when there is at most one frame, preserving the no-change fast path.
119
+ * `prepareStep`, over the stripped chain (see {@link stripInjectedStepMessages}).
120
+ *
121
+ * Counts FRAMES, not messages: AI SDK 6 collects ALL of a step's tool results
122
+ * into ONE `tool`-role message, so a step that looked twice holds two frames in
123
+ * a single message. The newest frame (last in transcript order) stays live and
124
+ * every older one collapses to {@link STALE_FRAME_NOTE}; the rest of each
125
+ * tool-result (its own text, a sibling `act` result) is left exactly as it was.
126
+ * Returns the SAME array when the transcript holds at most ONE frame, keeping
127
+ * the no-change fast path.
106
128
  */
107
129
  export declare function pruneStaleFrames(messages: ModelMessage[]): ModelMessage[];
108
130
  /** Steps left at or below which the driver is nudged to wrap up and `report`. */
@@ -114,43 +136,21 @@ export declare const BUDGET_WARN = 6;
114
136
  * budget. `stepNumber` is the 0-based index of the step about to run.
115
137
  */
116
138
  export declare function budgetNudge(stepNumber: number, maxSteps: number): string | null;
117
- /**
118
- * Lift a finished step's `look` results into visual findings — each issue the
119
- * vision guy flagged, carrying the frame it was judged on as evidence.
120
- */
121
- export declare function visualFrom(toolResults: FinishedStep['toolResults']): VisualIssue[];
122
- /**
123
- * Lift a finished step's `observe` console reads into bugs — ERROR rows only
124
- * (warn/log/info are working noise, not findings). The console channel is a ring
125
- * buffer read non-destructively, so a re-read returns rows already lifted;
126
- * {@link progressForStep} dedupes by message before they land.
127
- */
128
- export declare function consoleBugsFrom(toolResults: FinishedStep['toolResults']): Bug[];
129
- /**
130
- * The run-long accumulators the running flush reads: the shared act-`steps` trail
131
- * (the SAME array the `act` and `report` tools hold) plus the findings streamed off
132
- * the belt — `look`'s visual issues and error-level console rows. Streaming those
133
- * is what keeps a crashed, aborted or step-capped run's findings file complete;
134
- * before, they lived only in model context until `report`.
135
- */
136
- export interface RunTrail {
137
- /** Ordered act trail, written by `act` as each act finishes (shared with `report`). */
138
- steps: Step[];
139
- /** Console bugs seen so far, deduped by message. */
140
- bugs: Bug[];
141
- /** Visual issues seen so far, deduped by issue + location. */
142
- visual: VisualIssue[];
143
- }
144
139
  /**
145
140
  * Decide the running-findings write for a finished step. Steps aside for the
146
141
  * terminal `report` step (it owns the verdict, and already merged the trail — see
147
- * `belt/report.ts`); otherwise appends this step's NEW `look` issues and console
148
- * errors to `running` (mutated in place) and returns the `running` findings to
149
- * persist — act steps are already on `running.steps`, recorded by `act` itself.
150
- * `null` when the step surfaced nothing new — no act, and every issue/error
151
- * already streamed.
142
+ * `belt/report.ts`); otherwise, when ANY evidence stream grew past what the last
143
+ * flush already persisted, return the running findings to persist — a snapshot
144
+ * COPY of the trail ({@link TrailEvidence}). `null` when the step surfaced
145
+ * nothing new: no act recorded, every issue/error already streamed.
146
+ *
147
+ * Growth is read off the trail, not off the step's own tool results: the belt
148
+ * records AT TOOL TIME — a FAILED act still lands on the trail (`belt/act.ts`
149
+ * records `ok: false` then rethrows, and AI SDK 6 routes a rejected call to a
150
+ * `tool-error` content part, never `toolResults`) — so the trail's growth is the
151
+ * one signal that covers successes, failures and streamed findings alike.
152
152
  */
153
- export declare function progressForStep(step: FinishedStep, running: RunTrail): Findings | null;
153
+ export declare function progressForStep(step: FinishedStep, evidence: TrailEvidence, flushed: TrailEvidence): Findings | null;
154
154
  /** Everything the loop needs to run one debug session. */
155
155
  export interface DebugAgentOptions {
156
156
  /** fast guy — the blind text driver running the high-frequency click loop. */
@@ -166,12 +166,14 @@ export interface DebugAgentOptions {
166
166
  /** Optional sink for a human-readable step trail (`logs/agent.log`). */
167
167
  log?: AgentLog;
168
168
  /**
169
- * Shared act-trail the `act` tool writes, the running flush snapshots and the
170
- * `report` tool merges into the verdict's `steps` — pass the SAME array the
171
- * belt's act trail holds so the write and its counts agree. Defaults to a fresh
172
- * array (an unwired loop then flushes no steps).
169
+ * Shared evidence trail the belt's tools record into — `act` writes each step
170
+ * as it finishes, `look` each flagged issue, `observe` each error-level console
171
+ * row — the running flush snapshots it after every step, and the `report` tool
172
+ * merges all three streams into the verdict. Pass the SAME trail the belt's
173
+ * tools were built with so the write, the flushes and their counts agree.
174
+ * Defaults to none: an unwired loop then has nothing to flush.
173
175
  */
174
- trail?: Step[];
176
+ trail?: ActTrail;
175
177
  /** Step safety cap; defaults to {@link DEFAULT_MAX_STEPS}. */
176
178
  maxSteps?: number;
177
179
  }
@@ -209,4 +211,4 @@ export interface RunDebugLoopOptions {
209
211
  * driver reports (or the step cap trips); rejects if aborted (fail loud — the
210
212
  * session decides what an aborted run means).
211
213
  */
212
- export declare function runDebugLoop(options: RunDebugLoopOptions): Promise<import("ai").GenerateTextResult<BeltTools, never>>;
214
+ export declare function runDebugLoop(options: RunDebugLoopOptions): Promise<import("ai").GenerateTextResult<BeltTools, import("@ai-sdk/provider-utils").Context, never>>;
@@ -9,10 +9,10 @@
9
9
  * any mid-run messages (the smart agent's `send_message`) into a standing
10
10
  * instruction block re-appended to EVERY turn (the SDK rebuilds each step's
11
11
  * prompt from scratch), so the driver adapts without restarting or forgetting.
12
- * - **incremental findings** — `onStepFinish` snapshots the shared act trail
13
- * (`act` records each step as it happens) plus `look`'s visual issues and
14
- * error-level console rows, and flushes them as `status: 'running'` findings,
15
- * so `get_findings` streams findings before the verdict lands, and a run that
12
+ * - **incremental findings** — `onStepFinish` snapshots the shared evidence
13
+ * trail (the belt's tools record each step, console error and look issue as
14
+ * it happens) and flushes it as `status: 'running'` findings, so
15
+ * `get_findings` streams findings before the verdict lands, and a run that
16
16
  * crashes, aborts or hits the step cap keeps everything surfaced so far.
17
17
  *
18
18
  * Adapter-blind and model-blind like the belt: the loop never touches a protocol
@@ -23,7 +23,7 @@
23
23
  * aborted run rejects loud (wired to `end_session`), never a silent half-finish.
24
24
  */
25
25
  import { stepCountIs, ToolLoopAgent } from 'ai';
26
- import { z } from 'zod';
26
+ import { EMPTY_EVIDENCE } from './belt/report.js';
27
27
  /**
28
28
  * Safety cap on driver steps before the loop force-stops (paired with the
29
29
  * report-RESULT stop condition in {@link createDebugAgent}).
@@ -38,40 +38,18 @@ import { z } from 'zod';
38
38
  export const DEFAULT_MAX_STEPS = 60;
39
39
  /** Kickoff turn — the story lives in `instructions`; this nudges the driver to start the loop. */
40
40
  export const KICKOFF_PROMPT = 'Begin. Work toward the goal with observe/act/look, then call report exactly once with your verdict.';
41
- /**
42
- * The `look` result fields lifted into streamed visual findings: the vision guy's
43
- * `issues[]` and the frame it judged (see `belt/look.ts`). A SELF-look result (a
44
- * multimodal driver judging the frame with its own eyes) carries no `issues`, so
45
- * it contributes nothing here — those issues reach findings via `report`.
46
- */
47
- const LookVisualSchema = z.object({
48
- screenshot: z.string().optional(),
49
- issues: z
50
- .array(z.object({
51
- what: z.string(),
52
- where: z.string(),
53
- severity: z.enum(['low', 'medium', 'high']),
54
- }))
55
- .default([]),
56
- });
57
- /** The `observe` console rows lifted into streamed bugs (see `belt/observe.ts`). */
58
- const ConsoleObserveSchema = z.object({
59
- kind: z.literal('console'),
60
- entries: z
61
- .array(z.object({ level: z.string(), text: z.string(), location: z.string().optional() }))
62
- .default([]),
63
- });
64
41
  /**
65
42
  * `prepareStep`: fold mid-run messages into the next model turn. Drains the inbox
66
43
  * into `standing` — the run-long list of caller instructions — then, while any
67
44
  * exist, appends ONE user message rebuilt from the whole list.
68
45
  *
69
- * Rebuilt on EVERY step, not just the drain step: the SDK composes each step's
70
- * prompt fresh from `[...initialMessages, ...responseMessages]` and never persists
71
- * a `prepareStep` messages override, so an instruction injected once would reach
72
- * the driver for exactly one step and then vanish. Because the base `messages`
73
- * arrive without the previous step's injection, re-appending the single rebuilt
74
- * block never accumulates duplicates. Returns `{}` when no instructions exist.
46
+ * Rebuilt on EVERY step, not just the drain step: an instruction injected once
47
+ * must reach the driver on every later step too. AI SDK 7 persists the previous
48
+ * step's `prepareStep` override into the running transcript
49
+ * (`messagesForNextStep = [...stepMessages, ...stepResponseMessages]`), so the
50
+ * caller strips last step's fold/nudge first ({@link stripInjectedStepMessages})
51
+ * and this re-appends exactly one fresh block — never accumulation. Returns
52
+ * `{}` when no instructions exist.
75
53
  */
76
54
  export function foldInstructionsIntoStep(inbox, standing, messages) {
77
55
  standing.push(...inbox.drain());
@@ -85,57 +63,136 @@ export function foldInstructionsIntoStep(inbox, standing, messages) {
85
63
  };
86
64
  return { messages: [...messages, injected] };
87
65
  }
66
+ /** The exact prefixes of every user message `prepareStep` itself injects. */
67
+ const INJECTED_PREFIXES = [
68
+ 'Mid-run instructions from the caller',
69
+ 'Step budget almost spent',
70
+ 'This is your final step',
71
+ ];
72
+ /**
73
+ * True for the fold/nudge messages `prepareStep` appends — and ONLY those: the
74
+ * content must be a plain string starting with one of the exact prefixes above,
75
+ * so a driver-authored message that merely mentions them never matches.
76
+ */
77
+ function isInjectedStepMessage(message) {
78
+ const { content } = message;
79
+ if (message.role !== 'user' || typeof content !== 'string')
80
+ return false;
81
+ return INJECTED_PREFIXES.some((prefix) => content.startsWith(prefix));
82
+ }
83
+ /**
84
+ * Drop the fold/nudge messages a PREVIOUS step's `prepareStep` injected.
85
+ *
86
+ * AI SDK 7 persists the override into the running transcript
87
+ * (`messagesForNextStep = [...stepMessages, ...stepResponseMessages]` in
88
+ * `generateText`); AI SDK 6 rebuilt each step's prompt from response messages
89
+ * alone and discarded it. Without stripping, the re-appended instruction fold
90
+ * duplicates one copy per step, and a stale earlier nudge precedes the fresh
91
+ * one (breaking fold-before-nudge ordering). Stripping first restores exactly
92
+ * the AI SDK 6 chain this loop was written against, so the rebuilt override is
93
+ * correct whether the SDK persists it or not.
94
+ */
95
+ export function stripInjectedStepMessages(messages) {
96
+ if (!messages.some(isInjectedStepMessage))
97
+ return messages;
98
+ return messages.filter((message) => !isInjectedStepMessage(message));
99
+ }
88
100
  /** What a pruned frame collapses to — tells the driver how to get a fresh one. */
89
101
  export const STALE_FRAME_NOTE = '[stale frame removed — call look again for a fresh screenshot]';
90
- /** Whether a tool-result part carries a self-look frame (`content` output with `file-data`). */
91
- function isLookFrame(part) {
92
- if (typeof part !== 'object' || part === null)
93
- return false;
94
- const p = part;
95
- return (p.type === 'tool-result' &&
96
- p.toolName === 'look' &&
97
- p.output?.type === 'content' &&
98
- Array.isArray(p.output.value) &&
99
- p.output.value.some((v) => v?.type === 'file-data'));
102
+ /** The content parts of a message as a plain array (empty for string content). */
103
+ function partsOf(message) {
104
+ return Array.isArray(message.content) ? message.content : [];
100
105
  }
101
- /** Collapse every `file-data` part of a look tool-result to the stale-frame note. */
102
- function stripFrame(message) {
103
- if (!Array.isArray(message.content))
104
- return message;
105
- const content = message.content.map((part) => {
106
- if (!isLookFrame(part))
107
- return part;
108
- const p = part;
109
- return {
110
- ...part,
111
- output: {
112
- ...p.output,
113
- value: p.output.value.map((v) => v?.type === 'file-data' ? { type: 'text', text: STALE_FRAME_NOTE } : v),
114
- },
115
- };
106
+ /**
107
+ * Every self-look frame in the transcript, in transcript order (message →
108
+ * content part → output value).
109
+ *
110
+ * A frame is ONE `file-data` value part of a look tool-result. AI SDK 6 puts ALL
111
+ * of a step's tool results into ONE `tool`-role message, so a step that called
112
+ * `look` twice carries TWO frames inside a SINGLE message — counting messages
113
+ * instead of frames let both survive and stacked the driver's images.
114
+ */
115
+ function findFrames(messages) {
116
+ const frames = [];
117
+ messages.forEach((message, messageIndex) => {
118
+ partsOf(message).forEach((part, partIndex) => {
119
+ // A content array may hold a null/undefined part — skip it instead of
120
+ // dereferencing it and killing the whole run inside `prepareStep`.
121
+ if (typeof part !== 'object' || part === null)
122
+ return;
123
+ const p = part;
124
+ if (p.type !== 'tool-result' || p.toolName !== 'look')
125
+ return;
126
+ const output = p.output;
127
+ if (output?.type !== 'content')
128
+ return;
129
+ const values = output.value;
130
+ if (!Array.isArray(values))
131
+ return;
132
+ values.forEach((value, valueIndex) => {
133
+ if (value?.type === 'file-data') {
134
+ frames.push({ messageIndex, partIndex, valueIndex });
135
+ }
136
+ });
137
+ });
116
138
  });
117
- return { ...message, content };
139
+ return frames;
140
+ }
141
+ /** Collapse the stale frames of ONE tool-result part to the stale-frame note. */
142
+ function collapseStaleFrames(part, staleValues) {
143
+ const p = part;
144
+ const values = (p.output?.value ?? []);
145
+ return {
146
+ ...p,
147
+ output: {
148
+ ...p.output,
149
+ value: values.map((value, valueIndex) => staleValues.has(valueIndex) ? { type: 'text', text: STALE_FRAME_NOTE } : value),
150
+ },
151
+ };
118
152
  }
119
153
  /**
120
154
  * Keep only the NEWEST self-look frame in the transcript. The SDK re-sends every
121
155
  * tool result on every step, so each `look` image would otherwise ride along for
122
156
  * the rest of the run — N looks × M steps of image tokens. Rebuilt per step in
123
- * `prepareStep` (overrides never persist), like the instruction fold. Returns the
124
- * SAME array when there is at most one frame, preserving the no-change fast path.
157
+ * `prepareStep`, over the stripped chain (see {@link stripInjectedStepMessages}).
158
+ *
159
+ * Counts FRAMES, not messages: AI SDK 6 collects ALL of a step's tool results
160
+ * into ONE `tool`-role message, so a step that looked twice holds two frames in
161
+ * a single message. The newest frame (last in transcript order) stays live and
162
+ * every older one collapses to {@link STALE_FRAME_NOTE}; the rest of each
163
+ * tool-result (its own text, a sibling `act` result) is left exactly as it was.
164
+ * Returns the SAME array when the transcript holds at most ONE frame, keeping
165
+ * the no-change fast path.
125
166
  */
126
167
  export function pruneStaleFrames(messages) {
127
- const frameIndexes = [];
128
- messages.forEach((message, index) => {
129
- if (message.role === 'tool' &&
130
- Array.isArray(message.content) &&
131
- message.content.some(isLookFrame)) {
132
- frameIndexes.push(index);
168
+ const frames = findFrames(messages);
169
+ if (frames.length <= 1)
170
+ return messages;
171
+ // Every frame but the LAST is stale — group them by the part they live in.
172
+ const staleByMessage = new Map();
173
+ for (const frame of frames.slice(0, -1)) {
174
+ let parts = staleByMessage.get(frame.messageIndex);
175
+ if (!parts) {
176
+ parts = new Map();
177
+ staleByMessage.set(frame.messageIndex, parts);
178
+ }
179
+ let values = parts.get(frame.partIndex);
180
+ if (!values) {
181
+ values = new Set();
182
+ parts.set(frame.partIndex, values);
133
183
  }
184
+ values.add(frame.valueIndex);
185
+ }
186
+ return messages.map((message, messageIndex) => {
187
+ const staleParts = staleByMessage.get(messageIndex);
188
+ if (!staleParts)
189
+ return message;
190
+ const content = partsOf(message).map((part, partIndex) => {
191
+ const staleValues = staleParts.get(partIndex);
192
+ return staleValues ? collapseStaleFrames(part, staleValues) : part;
193
+ });
194
+ return { ...message, content };
134
195
  });
135
- if (frameIndexes.length <= 1)
136
- return messages;
137
- const stale = new Set(frameIndexes.slice(0, -1));
138
- return messages.map((message, index) => (stale.has(index) ? stripFrame(message) : message));
139
196
  }
140
197
  /** Steps left at or below which the driver is nudged to wrap up and `report`. */
141
198
  export const BUDGET_WARN = 6;
@@ -154,84 +211,21 @@ export function budgetNudge(stepNumber, maxSteps) {
154
211
  }
155
212
  return `Step budget almost spent: ~${remaining} of ${maxSteps} steps left. Finish exploring and call \`report\` soon with all findings; an unreported run is wasted.`;
156
213
  }
157
- /**
158
- * Lift a finished step's `look` results into visual findings — each issue the
159
- * vision guy flagged, carrying the frame it was judged on as evidence.
160
- */
161
- export function visualFrom(toolResults) {
162
- const issues = [];
163
- for (const result of toolResults) {
164
- if (result.toolName !== 'look')
165
- continue;
166
- const parsed = LookVisualSchema.safeParse(result.output);
167
- if (!parsed.success)
168
- continue;
169
- const { screenshot } = parsed.data;
170
- for (const issue of parsed.data.issues) {
171
- issues.push({
172
- issue: issue.what,
173
- where: issue.where,
174
- severity: issue.severity,
175
- ...(screenshot !== undefined && { screenshot }),
176
- });
177
- }
178
- }
179
- return issues;
180
- }
181
- /**
182
- * Lift a finished step's `observe` console reads into bugs — ERROR rows only
183
- * (warn/log/info are working noise, not findings). The console channel is a ring
184
- * buffer read non-destructively, so a re-read returns rows already lifted;
185
- * {@link progressForStep} dedupes by message before they land.
186
- */
187
- export function consoleBugsFrom(toolResults) {
188
- const bugs = [];
189
- for (const result of toolResults) {
190
- if (result.toolName !== 'observe')
191
- continue;
192
- const parsed = ConsoleObserveSchema.safeParse(result.output);
193
- if (!parsed.success)
194
- continue;
195
- for (const entry of parsed.data.entries) {
196
- if (entry.level !== 'error')
197
- continue;
198
- bugs.push({
199
- kind: 'console',
200
- detail: entry.text,
201
- ...(entry.location !== undefined && { evidence: entry.location }),
202
- });
203
- }
204
- }
205
- return bugs;
206
- }
207
- /** Dedupe key for a streamed finding — its message, case- and whitespace-insensitive. */
208
- function messageKey(...parts) {
209
- return parts.join(' @ ').trim().toLowerCase().replace(/\s+/g, ' ');
210
- }
211
- /** Append the `fresh` entries whose key is not already present; returns how many landed. */
212
- function appendNew(into, fresh, key) {
213
- const seen = new Set(into.map(key));
214
- let added = 0;
215
- for (const item of fresh) {
216
- const k = key(item);
217
- if (seen.has(k))
218
- continue;
219
- seen.add(k);
220
- into.push(item);
221
- added += 1;
222
- }
223
- return added;
224
- }
225
214
  /**
226
215
  * Decide the running-findings write for a finished step. Steps aside for the
227
216
  * terminal `report` step (it owns the verdict, and already merged the trail — see
228
- * `belt/report.ts`); otherwise appends this step's NEW `look` issues and console
229
- * errors to `running` (mutated in place) and returns the `running` findings to
230
- * persist — act steps are already on `running.steps`, recorded by `act` itself.
231
- * `null` when the step surfaced nothing new — no act, and every issue/error
232
- * already streamed.
217
+ * `belt/report.ts`); otherwise, when ANY evidence stream grew past what the last
218
+ * flush already persisted, return the running findings to persist — a snapshot
219
+ * COPY of the trail ({@link TrailEvidence}). `null` when the step surfaced
220
+ * nothing new: no act recorded, every issue/error already streamed.
221
+ *
222
+ * Growth is read off the trail, not off the step's own tool results: the belt
223
+ * records AT TOOL TIME — a FAILED act still lands on the trail (`belt/act.ts`
224
+ * records `ok: false` then rethrows, and AI SDK 6 routes a rejected call to a
225
+ * `tool-error` content part, never `toolResults`) — so the trail's growth is the
226
+ * one signal that covers successes, failures and streamed findings alike.
233
227
  */
234
- export function progressForStep(step, running) {
228
+ export function progressForStep(step, evidence, flushed) {
235
229
  // Gated on the report RESULT, not the report CALL. A `report` whose arguments
236
230
  // fail the Zod schema is never executed (AI SDK 6 marks it `invalid` and feeds
237
231
  // the driver a tool-error), yet it still appears in `toolCalls` — so a call-gated
@@ -239,23 +233,18 @@ export function progressForStep(step, running) {
239
233
  // of a verdict that was never written.
240
234
  if (step.toolResults.some((result) => result.toolName === 'report'))
241
235
  return null;
242
- // Checked against `toolCalls`, NOT `toolResults`: a FAILED act still lands on
243
- // `running.steps` (`act` records `ok: false` at act time, then rethrows — see
244
- // `belt/act.ts`), but AI SDK 6 routes a rejected tool call to a `tool-error`
245
- // content part, never `toolResults` (see `describeStep` above). Gating on
246
- // `toolResults` would miss every failed act — exactly the step a crashed run
247
- // most needs preserved — unless the same step happened to also add a bug or
248
- // visual issue.
249
- const acted = step.toolCalls.some((call) => call.toolName === 'act');
250
- const bugs = appendNew(running.bugs, consoleBugsFrom(step.toolResults), (bug) => messageKey(bug.detail));
251
- const visual = appendNew(running.visual, visualFrom(step.toolResults), (issue) => messageKey(issue.issue, issue.where));
252
- if (!acted && bugs === 0 && visual === 0)
236
+ // The arrays only ever grow (append + dedupe), so a length past the last flush
237
+ // is exactly "this step surfaced something new".
238
+ const grew = evidence.steps.length > flushed.steps.length ||
239
+ evidence.bugs.length > flushed.bugs.length ||
240
+ evidence.visual.length > flushed.visual.length;
241
+ if (!grew)
253
242
  return null;
254
243
  return {
255
244
  status: 'running',
256
- steps: [...running.steps],
257
- bugs: [...running.bugs],
258
- visual: [...running.visual],
245
+ steps: [...evidence.steps],
246
+ bugs: [...evidence.bugs],
247
+ visual: [...evidence.visual],
259
248
  };
260
249
  }
261
250
  /** Summarize a finished step for `logs/agent.log`: the tools it called (+ input) + any error text. */
@@ -324,16 +313,15 @@ function withUndeliveredInbox(report, inbox) {
324
313
  * trail (skipping the `report` step, which writes the final verdict itself).
325
314
  */
326
315
  export function createDebugAgent(options) {
327
- const { model, tools, instructions, inbox, progress, log, maxSteps = DEFAULT_MAX_STEPS, trail = [], } = options;
316
+ const { model, tools, instructions, inbox, progress, log, maxSteps = DEFAULT_MAX_STEPS, trail, } = options;
328
317
  let stepIndex = 0;
329
318
  // Run-long list of mid-run caller instructions: drained from the inbox once,
330
- // re-folded into EVERY step's prompt (the SDK never persists a prepareStep override).
319
+ // re-folded into EVERY step's prompt (AI SDK 7 persists the previous override;
320
+ // `stripInjectedStepMessages` drops it before the re-fold).
331
321
  const standing = [];
332
- // The running flush's accumulators. `steps` IS the shared act trail (same array
333
- // the `act` and `report` tools hold — `act` writes it at act time); bugs/visual
334
- // accumulate here only — they are streamed evidence, and the driver owns the
335
- // terminal verdict's own arrays.
336
- const running = { steps: trail, bugs: [], visual: [] };
322
+ // What the running flush has already persisted. The trail's arrays only grow,
323
+ // so growth past these lengths is exactly "this step surfaced something new".
324
+ let flushed = EMPTY_EVIDENCE;
337
325
  return new ToolLoopAgent({
338
326
  model,
339
327
  tools: { ...tools, report: withUndeliveredInbox(tools.report, inbox) },
@@ -350,28 +338,37 @@ export function createDebugAgent(options) {
350
338
  ({ steps }) => steps.at(-1)?.toolResults.some((r) => r.toolName === 'report') ?? false,
351
339
  ],
352
340
  prepareStep: ({ messages, stepNumber }) => {
341
+ // AI SDK 7 persists the previous step's override into `messages` — strip
342
+ // its fold/nudge so both rebuild fresh: the fold never duplicates, the
343
+ // nudge reflects THIS step's remaining budget.
344
+ const stripped = stripInjectedStepMessages(messages);
353
345
  // Self-look frame hygiene first: only the newest screenshot stays live.
354
- const pruned = pruneStaleFrames(messages);
346
+ const pruned = pruneStaleFrames(stripped);
355
347
  const withInbox = foldInstructionsIntoStep(inbox, standing, pruned);
356
348
  const base = 'messages' in withInbox ? withInbox.messages : pruned;
357
349
  const nudge = budgetNudge(stepNumber, maxSteps);
358
350
  if (nudge)
359
351
  return { messages: [...base, { role: 'user', content: nudge }] };
360
- if (base === messages)
352
+ if (base === stripped)
361
353
  return {};
362
354
  return { messages: base };
363
355
  },
364
356
  onStepFinish: async (step) => {
365
357
  stepIndex += 1;
366
358
  log?.(describeStep(step, stepIndex));
367
- // Stream this step's new `look` issues + console errors and flush a running
368
- // snapshot of the shared trail (`act` already recorded its own steps there).
369
- // The terminal `report` step writes its own verdict — with that same trail
370
- // merged into `steps` (see `createReportTool`) — so the running flush steps
371
- // aside for it (`progressForStep` returns null on the report step).
372
- const snapshot = progressForStep(step, running);
373
- if (snapshot)
359
+ // Stream whatever grew on the shared evidence trail this step (the belt's
360
+ // tools already recorded it). The terminal `report` step writes its own
361
+ // verdict — with that same trail merged in (see `createReportTool`) — so
362
+ // the running flush steps aside for it (`progressForStep` returns null).
363
+ const snapshot = progressForStep(step, trail ?? EMPTY_EVIDENCE, flushed);
364
+ if (snapshot) {
374
365
  await progress.writeFindings(snapshot);
366
+ flushed = {
367
+ steps: snapshot.steps,
368
+ bugs: snapshot.bugs,
369
+ visual: snapshot.visual,
370
+ };
371
+ }
375
372
  },
376
373
  });
377
374
  }