@causyne/agent 1.20.22 → 1.20.25

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,37 @@
1
+ ---
2
+ name: agp-9-upgrade
3
+ description: Upgrade and configure Android Gradle Plugin 9.x and modern build toolchains. Use when modernizing build scripts, fixing deprecated AGP APIs, or updating Java/Kotlin compatibility.
4
+ ---
5
+
6
+ # Android Gradle Plugin Modernization
7
+
8
+ Migrate Android builds to modern Android Gradle Plugin (AGP) standards, Kotlin DSL, Java 17/21 toolchains, and Declarative Gradle configurations.
9
+
10
+ ## Workflow
11
+
12
+ 1. Update AGP and Gradle wrapper versions.
13
+ - Run `./gradlew wrapper --gradle-version=<target> --distribution-type=bin` to align Gradle with the required AGP compatibility matrix.
14
+ - Update `com.android.application` and `com.android.library` plugin versions in `gradle/libs.versions.toml`.
15
+ - **Done when:** `./gradlew --version` reports the target Gradle and JVM versions.
16
+
17
+ 2. Migrate build scripts to Kotlin DSL and modern DSL blocks.
18
+ - Replace deprecated `compileSdkVersion` with `compileSdk = <version>`.
19
+ - Replace deprecated `targetSdkVersion` with `targetSdk = <version>`.
20
+ - Configure JVM toolchain: `kotlin { jvmToolchain(17) }` or `java { toolchain { languageVersion = JavaLanguageVersion.of(17) } }`.
21
+ - **Done when:** module `build.gradle.kts` files use modern AGP DSL syntax with zero deprecation warnings.
22
+
23
+ 3. Adapt to AGP Artifact and Variant API changes.
24
+ - Replace legacy `applicationVariants.all` mutations with modern `androidComponents { onVariants { ... } }` hooks.
25
+ - Use artifact transformations and `ScopedArtifacts` when injecting bytecode or inspecting compiled classes.
26
+ - **Done when:** custom Gradle tasks hook into AGP build phases through modern variant APIs.
27
+
28
+ 4. Verify build performance and cache compatibility.
29
+ - Enable configuration cache in `gradle.properties`: `org.gradle.configuration-cache=true`.
30
+ - Run `./gradlew assembleDebug --configuration-cache` to ensure all custom tasks declare inputs and outputs properly.
31
+ - **Done when:** consecutive builds report configuration cache re-used with sub-second initialization.
32
+
33
+ ## Verification
34
+
35
+ - Clean build executes and succeeds with `./gradlew assembleDebug`.
36
+ - Configuration cache stores and reloads cache entries on incremental builds.
37
+ - App installs and launches on connected emulators with modern runtime compatibility.
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: android-cli
3
+ description: Use the official Google Android CLI to inspect layouts, capture screens, manage emulators, install APKs, and query Android documentation. Use when debugging app UI or controlling devices.
4
+ ---
5
+
6
+ # Android CLI Specialist
7
+
8
+ Use the official Google `android` command-line tool for device interaction, UI layout inspection, screenshot capture, emulator control, and rapid delta APK installations.
9
+
10
+ ## Workflow
11
+
12
+ 1. Verify environment and device connectivity.
13
+ - Run `android info` to verify Android SDK location, detected tools, and attached physical or virtual devices.
14
+ - If `android` is not present, ensure `~/.local/bin` and `$ANDROID_HOME/platform-tools` are loaded in `PATH`.
15
+ - **Done when:** `android info` returns valid SDK paths and lists connected devices or running emulators.
16
+
17
+ 2. Inspect UI layouts and element hierarchies.
18
+ - Run `android layout` to dump a structured JSON representation of all on-screen UI elements (resource IDs, bounds, accessibility labels, and interaction flags).
19
+ - Use `android layout --diff` after triggering an action to output only the UI elements that changed since the last inspection, keeping context compact.
20
+ - If an element is marked `"off-screen": true`, perform scrolling before attempting interactions.
21
+ - **Done when:** target UI components and their coordinate bounds are parsed from the layout output.
22
+
23
+ 3. Capture and resolve visual coordinates from screen captures.
24
+ - Run `android screen capture -o /tmp/screen.png` to inspect complex Canvas or WebView screens visually.
25
+ - Run `android screen capture --annotate -o /tmp/annotated.png` and `android screen resolve --screen /tmp/annotated.png --string "#N"` to convert visual numeric labels into exact center `(X, Y)` tap coordinates.
26
+ - **Done when:** visual inspection confirms screen state and element centers are converted to tap coordinates.
27
+
28
+ 4. Install and execute APK packages with delta acceleration.
29
+ - Run `android run --apks=<path-to-apk> --activity=<MainActivity>` to build, deploy, and launch an app with fast delta-install.
30
+ - When managing multiple devices, pass `--device=<serial>` explicitly to avoid multi-device targeting collisions.
31
+ - **Done when:** the APK is installed and the activity is launched in the foreground.
32
+
33
+ 5. Query official Android documentation and developer guidance.
34
+ - Run `android docs <query>` to retrieve authoritative guidance, API references, and sample patterns directly from Google's Android Knowledge Base.
35
+ - **Done when:** authoritative documentation confirms API usage and migration constraints.
36
+
37
+ ## Verification
38
+
39
+ - `android layout` returns the expected Activity layout hierarchy and element bounds.
40
+ - UI tap or input events correctly navigate the application to the target state.
41
+ - Screen capture visually confirms the application is rendered properly without crash dialogs.
@@ -0,0 +1,45 @@
1
+ ---
2
+ name: android-debugging-and-testing
3
+ description: Diagnose, debug, install, and verify Android applications and emulators via ADB. Use when deploying APKs, handling multiple emulators, resolving exit codes, or analyzing app crashes.
4
+ ---
5
+
6
+ # Android Debugging and Device Testing
7
+
8
+ Diagnose runtime issues, stream-install APKs, launch activities, and capture crash forensics on connected Android devices and emulators.
9
+
10
+ ## Workflow
11
+
12
+ 1. Query attached devices and lock the target serial.
13
+ - Run `adb devices -l` before executing device commands.
14
+ - When more than one device or emulator is present (for example `emulator-5554` and `emulator-5556`), always set `export ANDROID_SERIAL=<serial>` or include `-s <serial>` in every `adb` command to prevent `adb: more than one device/emulator` errors.
15
+ - **Done when:** `adb -s <serial> get-state` returns `device`.
16
+
17
+ 2. Perform streamed package installation.
18
+ - Run `adb -s <serial> install -r -d -t <path/to/app-debug.apk>`.
19
+ - Flags: `-r` replaces existing application while preserving data, `-d` allows version code downgrade, `-t` allows test APKs.
20
+ - Check standard output for `Success`. If `INSTALL_FAILED_ALREADY_EXISTS` occurs, use `-r` or uninstall first via `adb -s <serial> uninstall <package>`.
21
+ - **Done when:** `adb install` output explicitly returns `Performing Streamed Install` and `Success`.
22
+
23
+ 3. Launch and verify foreground Activity lifecycle.
24
+ - Run `adb -s <serial> shell am start -n <package>/<activity>`.
25
+ - Do not rely on chaining `sleep && pidof` in compound expressions, as timing differences cause exit code 1. Instead, query the activity manager directly:
26
+ `adb -s <serial> shell dumpsys activity activities | grep -E "mResumedActivity|topResumedActivity"`
27
+ - Confirm the target activity matches the resumed activity record.
28
+ - **Done when:** `dumpsys activity` confirms the target Activity is topResumedActivity in the foreground.
29
+
30
+ 4. Capture logcat crash traces and ANR logs.
31
+ - Run `adb -s <serial> logcat -b crash -d` to inspect recent uncaught exceptions and native aborts.
32
+ - Run `adb -s <serial> logcat -d --pid=$(adb -s <serial> shell pidof <package>)` to inspect logs scoped to the app process.
33
+ - Check `/data/anr/traces.txt` via `adb -s <serial> shell "ls -t /data/anr/ 2>/dev/null"` if the application encounters an Application Not Responding freeze.
34
+ - **Done when:** stack traces and FATAL EXCEPTION logs are extracted with offending file names and line numbers.
35
+
36
+ 5. Configure port forwarding and network proxying when required.
37
+ - Use `adb -s <serial> reverse tcp:<port> tcp:<port>` so the emulator can access local host development servers running on `localhost:<port>`.
38
+ - **Done when:** `adb reverse --list` confirms port mapping between emulator and host.
39
+
40
+ ## Verification
41
+
42
+ - `adb devices` confirms the target device is online and responsive.
43
+ - The APK installs with `Success` without signature or manifest errors.
44
+ - `dumpsys activity` confirms the app is running in the foreground.
45
+ - `adb logcat -b crash -d` outputs zero unhandled exceptions.
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: android-profiler
3
+ description: Profile Android application CPU, memory allocations, thread contention, and memory leaks. Use when an app experiences frame drops, jank, high memory footprint, or slow startup.
4
+ ---
5
+
6
+ # Android Application Profiling and Performance
7
+
8
+ Profile Android CPU cycles, memory allocations, garbage collection pauses, and frame rendering bottlenecks using Android profiling tools.
9
+
10
+ ## Workflow
11
+
12
+ 1. Configure profiling instrumentation and build variants.
13
+ - Build a debuggable or profileable release APK using `android:profileable` in `AndroidManifest.xml` so production-representative optimizations remain active.
14
+ - Run `./gradlew assembleDebug` or `./gradlew assembleRelease`.
15
+ - **Done when:** the target APK is packaged with profileable or debuggable flags enabled.
16
+
17
+ 2. Record CPU traces and detect UI thread stalls.
18
+ - Trace method execution and thread contention using `adb shell am profile start --sampling <interval> <package> /data/local/tmp/cpu.trace`.
19
+ - Perform the target user interactions, then stop profiling with `adb shell am profile stop <package>`.
20
+ - Pull the trace file with `adb pull /data/local/tmp/cpu.trace` and inspect with Perfetto or Android Profiler.
21
+ - **Done when:** CPU call trees identify methods spending excessive time on the main UI thread.
22
+
23
+ 3. Inspect memory heaps and diagnose object leaks.
24
+ - Trigger garbage collection and dump heap with `adb shell am dumpheap <package> /data/local/tmp/heap.hprof`.
25
+ - Pull and convert the heap dump: `hprof-conv /data/local/tmp/heap.hprof heap_converted.hprof`.
26
+ - Analyze retained size and identify destroyed Activities or Composables retained by static references, singletons, or uncancelled Coroutines.
27
+ - **Done when:** leaking instances and their strong reference paths to GC roots are identified.
28
+
29
+ 4. Measure frame rendering latency and jank statistics.
30
+ - Run `adb shell dumpsys gfxinfo <package> framestats` to capture frame render times.
31
+ - Check the 90th and 99th percentile frame times; ensure frames complete within 16.6ms (60 FPS) or 8.3ms (120 FPS).
32
+ - **Done when:** `gfxinfo` confirms 0% janky frames during smooth scrolling interactions.
33
+
34
+ ## Verification
35
+
36
+ - CPU profiling trace identifies hotspots and verifies offloading to background threads.
37
+ - Heap dump analysis confirms no retained Activity or ViewModel leaks after configuration change.
38
+ - `dumpsys gfxinfo` reports frame render times within target refresh rate budgets.
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: anr-audit-and-fix
3
+ description: Investigate and resolve Android Application Not Responding (ANR) freezes. Use when an app triggers an ANR dialog, blocks the main UI thread, or deadlocks on background operations.
4
+ ---
5
+
6
+ # Android ANR Audit and Remediation
7
+
8
+ Diagnose, reproduce, and resolve Application Not Responding (ANR) occurrences caused by main thread contention, long-running disk/network I/O, lock deadlocks, or slow BroadcastReceivers.
9
+
10
+ ## Workflow
11
+
12
+ 1. Extract and inspect ANR trace dumps.
13
+ - Run `adb bugreport bugreport.zip` or pull `/data/anr/traces.txt` using:
14
+ `adb shell "cat /data/anr/anr_* 2>/dev/null || cat /data/anr/traces.txt 2>/dev/null" > /tmp/anr_trace.txt`.
15
+ - Locate the `"main"` thread section in the dump and inspect its state (`SUSPENDED`, `BLOCKED`, `MONITOR`, or `TIMED_WAIT`).
16
+ - Identify the stack trace at the exact moment of the ANR trigger.
17
+ - **Done when:** the blocking call or synchronized lock in the main thread stack trace is identified.
18
+
19
+ 2. Audit main-thread disk, database, and network operations.
20
+ - Configure `StrictMode` in debug builds:
21
+ `StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build())`.
22
+ - Wrap Room database transactions, Datastore accesses, and JSON serialization calls with `withContext(Dispatchers.IO)`.
23
+ - **Done when:** all blocking file, network, and database operations run on background dispatcher threads.
24
+
25
+ 3. Resolve synchronization deadlocks and contention.
26
+ - Replace blocking `runBlocking { ... }` calls on the main thread with proper Coroutine lifecycle scopes (`viewModelScope.launch` or `lifecycleScope.launch`).
27
+ - Prevent worker threads holding locks required by the main UI thread during state updates.
28
+ - **Done when:** `runBlocking` is eliminated from UI components and mutex locks are released promptly.
29
+
30
+ 4. Enforce BroadcastReceiver time budgets.
31
+ - Limit `onReceive()` execution to under 5 seconds by delegating heavy tasks to Android Jetpack `WorkManager`.
32
+ - Use `goAsync()` if asynchronous handling is strictly required within the receiver lifecycle.
33
+ - **Done when:** `onReceive()` returns immediately after scheduling background work.
34
+
35
+ ## Verification
36
+
37
+ - ANR traces in `/data/anr/` show zero recent occurrences for the application package.
38
+ - `StrictMode` logs in `adb logcat` verify zero main-thread disk or network violations.
39
+ - UI remains responsive and fluid during intensive data synchronization operations.
@@ -0,0 +1,42 @@
1
+ ---
2
+ name: r8-analyzer
3
+ description: Analyze, configure, and troubleshoot R8 minification and ProGuard keep rules. Use when a release build crashes with ClassNotFoundException, NoSuchMethodError, or reflection failures.
4
+ ---
5
+
6
+ # Android R8 and ProGuard Minification Rules
7
+
8
+ Configure R8 shrinking, obfuscation, and resource optimization while preserving reflection-based libraries, serialization schemas, and native JNI bindings.
9
+
10
+ ## Workflow
11
+
12
+ 1. Enable shrinking and configure rule files.
13
+ - In `app/build.gradle.kts`, enable `isMinifyEnabled = true` and `isShrinkResources = true` in the `release` build type.
14
+ - Reference standard Android default rules and project rules:
15
+ `proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")`.
16
+ - **Done when:** release build compiles with R8 shrinking active.
17
+
18
+ 2. Preserve data classes and serialization schemas.
19
+ - Add keep rules for classes serialized via Gson, Moshi, or Kotlinx Serialization:
20
+ `-keepclassmembers class * { @com.google.gson.annotations.SerializedName <fields>; }`
21
+ `-keep,allowobfuscation,allowshrinking class com.example.models.** { *; }`.
22
+ - Keep enum values and Serializable classes from being stripped or renamed improperly.
23
+ - **Done when:** JSON serialization and deserialization function identically between debug and release variants.
24
+
25
+ 3. Preserve native JNI bindings and reflection entrypoints.
26
+ - Keep classes and methods called via JNI from C/C++ code:
27
+ `-keepclasseswithmembernames class * { native <methods>; }`.
28
+ - Keep custom View constructors invoked by XML layout inflation:
29
+ `-keep public class * extends android.view.View { public <init>(android.content.Context); public <init>(android.content.Context, android.util.AttributeSet); }`.
30
+ - **Done when:** custom views inflate properly and JNI native calls link without UnsatisfiedLinkError.
31
+
32
+ 4. Inspect R8 mapping and usage artifacts.
33
+ - Inspect `app/build/outputs/mapping/release/usage.txt` to verify which classes and methods were removed.
34
+ - Inspect `app/build/outputs/mapping/release/mapping.txt` to deobfuscate crash traces reported in production.
35
+ - Use `./gradlew checkReleaseDuplicateClasses` to detect dependency clashes.
36
+ - **Done when:** `usage.txt` confirms expected removals and `mapping.txt` is retained for crash deobfuscation.
37
+
38
+ ## Verification
39
+
40
+ - The release APK builds successfully and is significantly smaller than the unminified debug APK.
41
+ - Launching the release APK on a device triggers no `ClassNotFoundException` or `NoSuchMethodError`.
42
+ - Crash traces can be remapped to original line numbers using `retrace` and `mapping.txt`.
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: testing-setup
3
+ description: Configure and execute automated Android unit and instrumentation tests. Use when setting up ComposeTestRule, Espresso, Robolectric, or verifying UI journeys on an emulator.
4
+ ---
5
+
6
+ # Android Automated Testing and Verification
7
+
8
+ Configure test harnesses, author Jetpack Compose UI tests, and execute local unit tests and on-device instrumentation tests through Gradle.
9
+
10
+ ## Workflow
11
+
12
+ 1. Configure test dependencies in Gradle version catalog.
13
+ - Declare dependencies in `gradle/libs.versions.toml`:
14
+ `androidx-compose-ui-test-junit4`, `androidx-compose-ui-test-manifest`, `androidx-test-ext-junit`, `androidx-test-espresso-core`, `robolectric`, and `kotlinx-coroutines-test`.
15
+ - In `app/build.gradle.kts`, configure `testImplementation` and `androidTestImplementation`.
16
+ - **Done when:** Gradle dependencies resolve cleanly without version conflicts.
17
+
18
+ 2. Structure Jetpack Compose UI tests.
19
+ - Use `createAndroidComposeRule<MainActivity>()` or `createComposeRule()` in `androidTest`.
20
+ - Find elements by semantics or test tags: `composeTestRule.onNodeWithText("...").performClick()`.
21
+ - Assert element states: `composeTestRule.onNodeWithTag("submit_button").assertIsEnabled()`.
22
+ - **Done when:** Compose test cases exercise user interactions and assert resulting UI states.
23
+
24
+ 3. Run local JVM unit tests.
25
+ - Execute `./gradlew testDebugUnitTest` for fast headless verification.
26
+ - Use Robolectric or mock Android framework classes when unit tests reference Android Context or resources.
27
+ - **Done when:** `./gradlew testDebugUnitTest` finishes with `BUILD SUCCESSFUL` and 100% test pass rate.
28
+
29
+ 4. Execute on-device instrumentation tests.
30
+ - Ensure an active emulator or connected physical device is online via `adb devices`.
31
+ - Run `./gradlew connectedDebugAndroidTest` to execute tests inside the Android runtime.
32
+ - Inspect XML test results in `app/build/reports/androidTests/connected/`.
33
+ - **Done when:** all connected on-device tests pass and generate green HTML/XML test reports.
34
+
35
+ ## Verification
36
+
37
+ - `./gradlew testDebugUnitTest` passes with zero assertion errors.
38
+ - `./gradlew connectedDebugAndroidTest` passes on the connected emulator without timeouts.
39
+ - Test coverage reports confirm critical user journeys are validated.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.22",
3
+ "version": "1.20.25",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -856,6 +856,10 @@ export class AgentLoop {
856
856
  let universalSkillsContext = '';
857
857
  try {
858
858
  const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
859
+ const promptText = (this.taskPrompt || '').toLowerCase();
860
+ if (!detectedDomains.includes('android') && /\b(android|apk|adb|emulator|gradle|gradlew|compose|kotlin)\b/i.test(promptText)) {
861
+ detectedDomains.push('android');
862
+ }
859
863
  if (detectedDomains.length > 0) {
860
864
  this.debugLog(`detected workspace domains: ${detectedDomains.join(', ')}`);
861
865
  for (const domain of detectedDomains) {
@@ -1744,6 +1748,7 @@ export class AgentLoop {
1744
1748
  let planHandoffRecoveries = 0;
1745
1749
  let incompleteTurnContinuations = 0;
1746
1750
  let toolRoutingRecoveries = 0;
1751
+ let emptyResponseRecoveries = 0;
1747
1752
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1748
1753
  while (!this.stopRequested) {
1749
1754
  if (this.stopRequested) {
@@ -4033,6 +4038,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
4033
4038
  this.emitEvent({ type: 'error', message: 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4034
4039
  break;
4035
4040
  }
4041
+ if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
4042
+ || (typeof e?.message === 'string' && e.message.includes('returned no response'))) {
4043
+ if (emptyResponseRecoveries++ < 5) {
4044
+ this.emitEvent({
4045
+ type: 'notice',
4046
+ message: `Peer connection was interrupted or returned no response (${emptyResponseRecoveries}/5). Auto-reconnecting session and resuming task…`
4047
+ });
4048
+ auditLog.log({ event: 'peer_empty_response_recovery', taskId: this.taskId, attempt: emptyResponseRecoveries, error: e.message });
4049
+ const planNotice = this._implementationPlan?.length > 0
4050
+ ? ` Active plan has ${this._implementationPlan.filter((s) => s.status === 'completed' || s.completed).length}/${this._implementationPlan.length} steps completed.`
4051
+ : '';
4052
+ this.messages.push({
4053
+ role: 'system',
4054
+ content: `[RECONNECTION RECOVERY: The previous peer turn disconnected or returned no response.${planNotice} Disk files and modifications are preserved. Do NOT repeat completed work. Continue executing the next unfinished step of the task directly.]`
4055
+ });
4056
+ this.memoryManager.saveHistory(this.messages);
4057
+ await this.backoff(emptyResponseRecoveries);
4058
+ continue;
4059
+ }
4060
+ }
4036
4061
  if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
4037
4062
  this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
4038
4063
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
package/src/agentLoop.ts CHANGED
@@ -967,6 +967,10 @@ export class AgentLoop {
967
967
  let universalSkillsContext = '';
968
968
  try {
969
969
  const detectedDomains = detectWorkspaceDomains(this.workspaceRoot);
970
+ const promptText = (this.taskPrompt || '').toLowerCase();
971
+ if (!detectedDomains.includes('android') && /\b(android|apk|adb|emulator|gradle|gradlew|compose|kotlin)\b/i.test(promptText)) {
972
+ detectedDomains.push('android');
973
+ }
970
974
  if (detectedDomains.length > 0) {
971
975
  this.debugLog(`detected workspace domains: ${detectedDomains.join(', ')}`);
972
976
  for (const domain of detectedDomains) {
@@ -1841,6 +1845,7 @@ export class AgentLoop {
1841
1845
  let planHandoffRecoveries = 0;
1842
1846
  let incompleteTurnContinuations = 0;
1843
1847
  let toolRoutingRecoveries = 0;
1848
+ let emptyResponseRecoveries = 0;
1844
1849
 
1845
1850
  // The core loop governed by Sovereign Human-in-the-Loop Checkpoints
1846
1851
  while (!this.stopRequested) {
@@ -4282,6 +4287,27 @@ You are operating in a text-and-code modality without direct image pixel renderi
4282
4287
  'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
4283
4288
  break;
4284
4289
  }
4290
+ if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
4291
+ || (typeof e?.message === 'string' && e.message.includes('returned no response'))) {
4292
+ if (emptyResponseRecoveries++ < 5) {
4293
+ this.emitEvent({
4294
+ type: 'notice',
4295
+ message: `Peer connection was interrupted or returned no response (${emptyResponseRecoveries}/5). Auto-reconnecting session and resuming task…`
4296
+ });
4297
+ auditLog.log({ event: 'peer_empty_response_recovery', taskId: this.taskId, attempt: emptyResponseRecoveries, error: e.message });
4298
+
4299
+ const planNotice = this._implementationPlan?.length > 0
4300
+ ? ` Active plan has ${this._implementationPlan.filter((s: any) => s.status === 'completed' || s.completed).length}/${this._implementationPlan.length} steps completed.`
4301
+ : '';
4302
+ this.messages.push({
4303
+ role: 'system',
4304
+ content: `[RECONNECTION RECOVERY: The previous peer turn disconnected or returned no response.${planNotice} Disk files and modifications are preserved. Do NOT repeat completed work. Continue executing the next unfinished step of the task directly.]`
4305
+ });
4306
+ this.memoryManager.saveHistory(this.messages);
4307
+ await this.backoff(emptyResponseRecoveries);
4308
+ continue;
4309
+ }
4310
+ }
4285
4311
  if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
4286
4312
  this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
4287
4313
  auditLog.log({ event: 'task_interrupted', taskId: this.taskId });