@gajae-code/coding-agent 0.22.2 → 0.22.3

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 (122) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/types/cli/append-system-prompt.d.ts +7 -0
  3. package/dist/types/cli/doctor/session-owners.d.ts +8 -2
  4. package/dist/types/cli/public-command-errors.d.ts +1 -0
  5. package/dist/types/cli/session-picker.d.ts +16 -3
  6. package/dist/types/cli/update-cli.d.ts +0 -2
  7. package/dist/types/cli-ordinary.d.ts +1 -1
  8. package/dist/types/commands/sdk.d.ts +2 -0
  9. package/dist/types/config/machine-identity.d.ts +11 -0
  10. package/dist/types/config/model-registry.d.ts +9 -0
  11. package/dist/types/config/settings-schema.d.ts +84 -4
  12. package/dist/types/lsp/client.d.ts +9 -0
  13. package/dist/types/lsp/types.d.ts +2 -0
  14. package/dist/types/main.d.ts +40 -3
  15. package/dist/types/modes/components/session-held-warning.d.ts +27 -0
  16. package/dist/types/modes/components/session-selector.d.ts +32 -1
  17. package/dist/types/modes/controllers/selector-controller.d.ts +8 -1
  18. package/dist/types/modes/interactive-mode.d.ts +12 -1
  19. package/dist/types/sdk/broker/broker.d.ts +3 -0
  20. package/dist/types/sdk/broker/lifecycle-ledger.d.ts +5 -2
  21. package/dist/types/sdk/broker/lifecycle.d.ts +2 -0
  22. package/dist/types/sdk/broker/session-index.d.ts +11 -0
  23. package/dist/types/sdk/bus/index.d.ts +1 -1
  24. package/dist/types/sdk/host/control/dispatch.d.ts +3 -0
  25. package/dist/types/sdk/host/registration-test-hold.d.ts +7 -0
  26. package/dist/types/sdk/index.d.ts +1 -0
  27. package/dist/types/sdk/lifecycle/service.d.ts +3 -0
  28. package/dist/types/sdk/session-api-key.d.ts +11 -4
  29. package/dist/types/sdk/session-readonly/format.d.ts +7 -0
  30. package/dist/types/sdk/session.d.ts +11 -0
  31. package/dist/types/sdk/startup-capability.d.ts +11 -2
  32. package/dist/types/session/agent-session.d.ts +1 -2
  33. package/dist/types/session/internal/managed-session-storage.d.ts +1 -1
  34. package/dist/types/session/internal/session-claim-set.d.ts +168 -13
  35. package/dist/types/session/session-handover.d.ts +62 -0
  36. package/dist/types/session/session-manager.d.ts +75 -15
  37. package/dist/types/session/session-owner-holder.d.ts +77 -0
  38. package/dist/types/session/session-ownership-mode.d.ts +45 -2
  39. package/dist/types/session/session-ownership.d.ts +25 -29
  40. package/dist/types/session/yield-queue.d.ts +13 -0
  41. package/dist/types/tools/bash.d.ts +7 -0
  42. package/dist/types/tools/browser/deferred-profile-cleanup.d.ts +3 -0
  43. package/dist/types/tools/browser/launch.d.ts +24 -1
  44. package/dist/types/tools/index.d.ts +6 -0
  45. package/dist/types/tools/output-meta.d.ts +17 -11
  46. package/dist/types/tools/tool-result.d.ts +1 -0
  47. package/package.json +9 -7
  48. package/scripts/compile-args.ts +6 -3
  49. package/scripts/run-acp-conformance.ts +36 -10
  50. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  51. package/src/cli/append-system-prompt.ts +34 -0
  52. package/src/cli/auth-broker-cli.ts +5 -1
  53. package/src/cli/doctor/session-owners.ts +8 -2
  54. package/src/cli/public-command-errors.ts +4 -0
  55. package/src/cli/session-picker.ts +57 -7
  56. package/src/cli/update-cli.ts +0 -22
  57. package/src/cli-ordinary.ts +2 -17
  58. package/src/commands/sdk.ts +37 -15
  59. package/src/config/machine-identity.ts +31 -2
  60. package/src/config/model-registry.ts +40 -6
  61. package/src/config/settings-schema.ts +50 -6
  62. package/src/config/settings.ts +65 -3
  63. package/src/gjc-runtime/launch-tmux.ts +4 -1
  64. package/src/internal-urls/docs-index.generated.ts +12 -12
  65. package/src/lsp/client.ts +60 -6
  66. package/src/lsp/index.ts +2 -6
  67. package/src/lsp/types.ts +2 -0
  68. package/src/main.ts +364 -93
  69. package/src/modes/DESIGN.md +36 -0
  70. package/src/modes/acp/acp-agent.ts +215 -31
  71. package/src/modes/components/session-held-warning.ts +62 -0
  72. package/src/modes/components/session-selector.ts +234 -11
  73. package/src/modes/controllers/goal-mode-controller.ts +14 -2
  74. package/src/modes/controllers/selector-controller.ts +192 -3
  75. package/src/modes/interactive-mode.ts +40 -2
  76. package/src/prompts/tools/bash.md +1 -1
  77. package/src/prompts/tools/monitor.md +1 -1
  78. package/src/runtime-mcp/manager.ts +5 -1
  79. package/src/sdk/acp/adapter.ts +2 -0
  80. package/src/sdk/broker/broker.ts +29 -2
  81. package/src/sdk/broker/lifecycle-ledger.ts +9 -7
  82. package/src/sdk/broker/lifecycle.ts +280 -39
  83. package/src/sdk/broker/session-index.ts +24 -0
  84. package/src/sdk/bus/index.ts +1 -0
  85. package/src/sdk/bus/lifecycle-commands.ts +4 -0
  86. package/src/sdk/cli/session-cli.ts +8 -0
  87. package/src/sdk/host/control/dispatch.ts +18 -0
  88. package/src/sdk/host/host.ts +5 -0
  89. package/src/sdk/host/registration-test-hold.ts +51 -0
  90. package/src/sdk/host/session-runtime.test.ts +42 -0
  91. package/src/sdk/index.ts +10 -0
  92. package/src/sdk/lifecycle/service.ts +33 -10
  93. package/src/sdk/prompt-failure.ts +4 -0
  94. package/src/sdk/protocol/operation-registry.ts +7 -1
  95. package/src/sdk/session-api-key.ts +31 -16
  96. package/src/sdk/session-readonly/format.ts +10 -0
  97. package/src/sdk/session-readonly/scope.ts +2 -1
  98. package/src/sdk/session.ts +60 -7
  99. package/src/sdk/startup-capability.ts +27 -2
  100. package/src/session/agent-session.ts +411 -58
  101. package/src/session/internal/managed-session-storage.ts +16 -2
  102. package/src/session/internal/session-claim-set.ts +527 -49
  103. package/src/session/session-handover.ts +283 -0
  104. package/src/session/session-manager.ts +907 -148
  105. package/src/session/session-owner-holder.ts +177 -0
  106. package/src/session/session-ownership-mode.ts +84 -12
  107. package/src/session/session-ownership.ts +115 -89
  108. package/src/session/yield-queue.ts +43 -0
  109. package/src/session-import/provider-service.ts +8 -0
  110. package/src/setup/provider-onboarding.ts +5 -5
  111. package/src/task/executor.ts +2 -0
  112. package/src/tools/bash.ts +10 -0
  113. package/src/tools/browser/deferred-profile-cleanup.ts +20 -0
  114. package/src/tools/browser/launch.ts +133 -14
  115. package/src/tools/browser/registry.ts +72 -19
  116. package/src/tools/index.ts +10 -1
  117. package/src/tools/monitor.ts +267 -29
  118. package/src/tools/output-meta.ts +61 -28
  119. package/src/tools/tool-catalog.generated.ts +2 -2
  120. package/src/tools/tool-result.ts +5 -0
  121. package/dist/types/cli/macos-community-app.d.ts +0 -41
  122. package/src/cli/macos-community-app.ts +0 -1449
@@ -11,6 +11,12 @@ export interface YieldDispatcher<P> {
11
11
  * another origin (review thread P2).
12
12
  */
13
13
  groupKey?(entry: P): string;
14
+ /**
15
+ * Whether the entry may be delivered at a step boundary of a running turn
16
+ * (see {@link YieldQueue.drainStepBoundary}). Entries without this predicate,
17
+ * or for which it returns false, keep the before-yield and idle paths.
18
+ */
19
+ deliverAtStepBoundary?(entry: P): boolean;
14
20
  /** Produce one batched AgentMessage from non-stale entries. Return null to skip. */
15
21
  build(survivors: P[]): AgentMessage | null;
16
22
  }
@@ -52,6 +58,7 @@ type YieldFlushMode = "streaming" | "idle";
52
58
  interface StoredDispatcher {
53
59
  isStale?: (entry: unknown) => boolean;
54
60
  groupKey?: (entry: unknown) => string;
61
+ deliverAtStepBoundary?: (entry: unknown) => boolean;
55
62
  build: (survivors: unknown[]) => AgentMessage | null;
56
63
  }
57
64
 
@@ -74,6 +81,9 @@ export class YieldQueue {
74
81
  const stored: StoredDispatcher = {
75
82
  ...(dispatcher.isStale ? { isStale: entry => dispatcher.isStale?.(entry as P) ?? false } : {}),
76
83
  ...(dispatcher.groupKey ? { groupKey: entry => dispatcher.groupKey?.(entry as P) ?? "default" } : {}),
84
+ ...(dispatcher.deliverAtStepBoundary
85
+ ? { deliverAtStepBoundary: entry => dispatcher.deliverAtStepBoundary?.(entry as P) ?? false }
86
+ : {}),
77
87
  build: survivors => dispatcher.build(survivors as P[]),
78
88
  };
79
89
  this.#dispatchers.set(kind, stored);
@@ -139,6 +149,39 @@ export class YieldQueue {
139
149
  await this.#flushEntries(mode, signal);
140
150
  }
141
151
 
152
+ /**
153
+ * Drain and build every entry whose dispatcher allows step-boundary delivery,
154
+ * returning the messages for the running turn to consume directly. Ineligible
155
+ * entries stay queued in order for the before-yield or idle flush, so each
156
+ * entry is delivered by exactly one path.
157
+ */
158
+ drainStepBoundary(): AgentMessage[] {
159
+ const messages: AgentMessage[] = [];
160
+ for (const [kind, dispatcher] of this.#dispatchers) {
161
+ const predicate = dispatcher.deliverAtStepBoundary;
162
+ if (!predicate) continue;
163
+ const entries = this.#entries.get(kind);
164
+ if (!entries || entries.length === 0) continue;
165
+ const eligible: unknown[] = [];
166
+ const retained: unknown[] = [];
167
+ for (const entry of entries) {
168
+ let deliverNow: boolean;
169
+ try {
170
+ deliverNow = predicate(entry);
171
+ } catch (error) {
172
+ logger.warn("Yield queue step-boundary check failed", { kind, error: formatError(error) });
173
+ deliverNow = false;
174
+ }
175
+ (deliverNow ? eligible : retained).push(entry);
176
+ }
177
+ if (eligible.length === 0) continue;
178
+ if (retained.length > 0) this.#entries.set(kind, retained);
179
+ else this.#entries.delete(kind);
180
+ messages.push(...(this.#build(kind, dispatcher, eligible) ?? []));
181
+ }
182
+ return messages;
183
+ }
184
+
142
185
  async #flushEntries(mode: YieldFlushMode, signal?: AbortSignal): Promise<void> {
143
186
  const idleMessages: AgentMessage[] = [];
144
187
  for (const [kind, dispatcher] of this.#dispatchers) {
@@ -3,6 +3,7 @@ import * as nodeFs from "node:fs";
3
3
  import * as fsp from "node:fs/promises";
4
4
  import * as path from "node:path";
5
5
  import { canContinuePersistedHistory } from "@gajae-code/agent-core";
6
+ import { sessionClaimSetOf } from "../session/internal/session-claim-set";
6
7
  import { type SessionDestinationInput, SessionManager } from "../session/session-manager";
7
8
  import { parseClaudeCodeTranscript, parseClaudeExport } from "./claude";
8
9
  import { detectSessionImportFormat } from "./detect";
@@ -374,6 +375,13 @@ export async function materializeExternalSessionImport(
374
375
  }
375
376
  const importedAt = (options.now?.() ?? new Date()).toISOString();
376
377
  const manager = SessionManager.create(options.cwd, options.destination);
378
+ // The import's claim gate: enforce refuses a failed claim of the new id here, before any write.
379
+ const claims = sessionClaimSetOf(manager);
380
+ const refusal = claims.claiming ? await claims.refusal() : undefined;
381
+ if (refusal) {
382
+ await manager.close().catch(() => {});
383
+ throw new SessionImportError("io_failed", "persist", refusal.operatorMessage);
384
+ }
377
385
  const destination = manager.getDestinationForFork();
378
386
  const sessionFile = manager.getSessionFile();
379
387
  if (!sessionFile) {
@@ -299,11 +299,11 @@ function providerCredentialRecoveryHint(providerId: string): string {
299
299
  * old literal key. OAuth rows are never touched, and rows are soft-disabled
300
300
  * (`gjc accounts list` shows them as `disabled`) rather than deleted.
301
301
  *
302
- * Only a confirmed disable (`disableCredentialById` returning `true`) counts:
303
- * the store can swallow errors, and this count is what the user reasons about
304
- * in a path that cannot restore the rows. Persistence is verified by
305
- * re-reading the store, because remote (broker-owned) stores reject disables
306
- * outright and a reload is the only proof the rows no longer resolve.
302
+ * Only a confirmed disable (`disableCredentialById` returning `true`) counts,
303
+ * and this count is what the user reasons about in a path that cannot restore
304
+ * the rows. A failed store write throws and is reported as a refused disable.
305
+ * Persistence is still verified by re-reading the store, because a reload is
306
+ * the only proof the rows no longer resolve.
307
307
  */
308
308
  async function removeStoredApiKeyCredentials(store: ProviderSetupCredentialStore, providerId: string): Promise<number> {
309
309
  const selectApiKeyRows = () =>
@@ -2058,6 +2058,8 @@ export async function runSubprocessOnce(options: ExecutorOptions): Promise<Singl
2058
2058
  ? "disabled"
2059
2059
  : "copy-retain",
2060
2060
  subagentSettings.get("sessionMemory.mode"),
2061
+ // Subagent children claim nothing yet (single-owner design §13 L2).
2062
+ "exempt",
2061
2063
  ),
2062
2064
  )
2063
2065
  : SessionManager.inMemory(worktree ?? cwd);
package/src/tools/bash.ts CHANGED
@@ -1033,6 +1033,7 @@ export class BashTool implements AgentTool<BashToolSchema, BashToolDetails> {
1033
1033
  }
1034
1034
  const resultBuilder = toolResult(details)
1035
1035
  .text(outputText)
1036
+ .retention("bash")
1036
1037
  .truncationFromSummary(result, {
1037
1038
  direction: "tail",
1038
1039
  ...(shortArtifactInBody ? { noticeOwner: "body" } : {}),
@@ -1057,6 +1058,7 @@ export class BashTool implements AgentTool<BashToolSchema, BashToolDetails> {
1057
1058
  const details: BashToolDetails = {
1058
1059
  timeoutSeconds: timeoutSec,
1059
1060
  async: { state: "running", jobId, type: "bash" },
1061
+ meta: { retention: "bash" },
1060
1062
  };
1061
1063
  // A folded client terminal keeps its remote handle, so the editor's live
1062
1064
  // terminal card stays bound to the same id after the fold.
@@ -1722,6 +1724,13 @@ export class BashTool implements AgentTool<BashToolSchema, BashToolDetails> {
1722
1724
  onRawLine?: (line: string, jobId: string) => void;
1723
1725
  shouldAcceptRawLine?: (jobId: string) => boolean;
1724
1726
  lifecycle?: import("../async").AsyncJobLifecycleCleanup;
1727
+ /**
1728
+ * Asked once when the command exits successfully. Returning true
1729
+ * acknowledges the job's own completion delivery before the manager
1730
+ * settles it, so no async-result is enqueued: the caller's stdout
1731
+ * notifications already reported the run (#7993).
1732
+ */
1733
+ shouldAcknowledgeCompletion?: () => boolean;
1725
1734
  } = {},
1726
1735
  ): Promise<{ jobId: string; label: string; commandCwd: string }> {
1727
1736
  const manager = this.#resolveOwnedJobManager();
@@ -1817,6 +1826,7 @@ export class BashTool implements AgentTool<BashToolSchema, BashToolDetails> {
1817
1826
  flushTrailingLine();
1818
1827
  const resultText = appendArtifactDetails(result.output || "(no output)", result);
1819
1828
  this.#buildResultText(result, prepared.timeoutSec, resultText);
1829
+ if (opts.shouldAcknowledgeCompletion?.()) manager.acknowledgeDeliveries([id]);
1820
1830
  return resultText;
1821
1831
  } catch (error) {
1822
1832
  flushTrailingLine();
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Profile directories whose removal failed with EBUSY after a failed browser launch.
3
+ *
4
+ * Kept free of `@gajae-code/utils` and native imports because `launch.ts` is part of
5
+ * the tab-worker runtime graph, which must stay native-free. The registry drains this
6
+ * set opportunistically (on browser acquire) once Chrome has released the files.
7
+ */
8
+ const deferredProfileDirs = new Set<string>();
9
+
10
+ export function deferProfileDirCleanup(dir: string): void {
11
+ deferredProfileDirs.add(dir);
12
+ }
13
+
14
+ export function deferredProfileDirSnapshot(): string[] {
15
+ return Array.from(deferredProfileDirs);
16
+ }
17
+
18
+ export function forgetDeferredProfileDir(dir: string): void {
19
+ deferredProfileDirs.delete(dir);
20
+ }
@@ -25,6 +25,7 @@ import stealthWorkerScript from "../puppeteer/13_stealth_worker.txt" with { type
25
25
  import stealthPermissionsScript from "../puppeteer/14_stealth_permissions.txt" with { type: "text" };
26
26
  import stealthWebrtcScript from "../puppeteer/15_stealth_webrtc.txt" with { type: "text" };
27
27
  import { ToolError } from "../tool-errors";
28
+ import * as deferredProfileCleanup from "./deferred-profile-cleanup";
28
29
 
29
30
  export const DEFAULT_VIEWPORT = { width: 1365, height: 768, deviceScaleFactor: 1.25 };
30
31
 
@@ -398,7 +399,70 @@ export interface LaunchHeadlessOptions {
398
399
  geo?: { timezone?: string; locale?: string };
399
400
  }
400
401
 
401
- export async function launchHeadlessBrowser(opts: LaunchHeadlessOptions): Promise<Browser> {
402
+ export interface LaunchHeadlessResult {
403
+ browser: Browser;
404
+ /**
405
+ * The userDataDir gjc created when profileWarmupDir was not provided.
406
+ * undefined if profileWarmupDir was used (caller-supplied dir).
407
+ * When set, gjc owns this dir and must remove it after Chrome exits.
408
+ */
409
+ createdUserDataDir?: string;
410
+ }
411
+
412
+ /**
413
+ * Attempt to remove a profile directory with bounded retry on transient EBUSY errors.
414
+ * Chrome may still hold files when launch fails or during disconnection, so retry
415
+ * with brief delays before giving up. Returns explicit result indicating success or failure.
416
+ *
417
+ * On EBUSY after exhausting retries, throws to signal to caller that deferral may be needed.
418
+ * On other errors after first attempt, logs but returns {removed: false, error}.
419
+ */
420
+ export async function cleanupProfileDirWithRetry(
421
+ dir: string,
422
+ maxRetries = 10,
423
+ delay = 50,
424
+ ): Promise<{ removed: true } | { removed: false; error: Error }> {
425
+ let lastErr: Error | undefined;
426
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
427
+ try {
428
+ fs.rmSync(dir, { recursive: true, force: true });
429
+ if (attempt > 0) {
430
+ logger.debug("Successfully cleaned up headless profile dir after retry", {
431
+ dir,
432
+ attempt,
433
+ });
434
+ }
435
+ return { removed: true };
436
+ } catch (err) {
437
+ lastErr = err as Error;
438
+ const isEBUSY = lastErr.message.includes("EBUSY");
439
+ if (!isEBUSY) {
440
+ // Not a transient EBUSY. Log and return failure.
441
+ logger.debug("Failed to clean up headless profile dir (non-transient error)", {
442
+ dir,
443
+ attempt,
444
+ error: lastErr.message,
445
+ });
446
+ return { removed: false, error: lastErr };
447
+ }
448
+ if (attempt === maxRetries) {
449
+ // Exhausted retries on EBUSY. Log and rethrow to signal deferral.
450
+ logger.debug("Exhausted retries for profile dir cleanup due to EBUSY", {
451
+ dir,
452
+ attempt,
453
+ error: lastErr.message,
454
+ });
455
+ throw lastErr;
456
+ }
457
+ // Transient EBUSY: wait a bit and retry
458
+ await Bun.sleep(delay);
459
+ }
460
+ }
461
+ // Fallthrough (should not reach here with current loop logic)
462
+ return { removed: false, error: lastErr ?? new Error("Cleanup failed with unknown error") };
463
+ }
464
+
465
+ export async function launchHeadlessBrowser(opts: LaunchHeadlessOptions): Promise<LaunchHeadlessResult> {
402
466
  const vp = opts.viewport ?? DEFAULT_VIEWPORT;
403
467
  const initialViewport = {
404
468
  width: vp.width,
@@ -406,6 +470,17 @@ export async function launchHeadlessBrowser(opts: LaunchHeadlessOptions): Promis
406
470
  deviceScaleFactor: vp.deviceScaleFactor ?? DEFAULT_VIEWPORT.deviceScaleFactor,
407
471
  };
408
472
  const puppeteer = await loadPuppeteer();
473
+
474
+ // Create userDataDir if not provided. This prevents puppeteer from creating
475
+ // its own temp profile which can fail to clean up with EBUSY on Windows (#8076).
476
+ // When we pass userDataDir to puppeteer.launch(), it won't try to remove it.
477
+ let userDataDir = opts.profileWarmupDir;
478
+ let createdUserDataDir: string | undefined;
479
+ if (!userDataDir) {
480
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "gjc-headless-profile-"));
481
+ createdUserDataDir = userDataDir;
482
+ }
483
+
409
484
  const launchArgs = [
410
485
  "--no-sandbox",
411
486
  "--disable-setuid-sandbox",
@@ -415,11 +490,8 @@ export async function launchHeadlessBrowser(opts: LaunchHeadlessOptions): Promis
415
490
  // interface only; 15_stealth_webrtc.txt adds a candidate-level guard.
416
491
  "--force-webrtc-ip-handling-policy=default_public_interface_only",
417
492
  `--window-size=${initialViewport.width},${initialViewport.height}`,
493
+ `--user-data-dir=${userDataDir}`,
418
494
  ];
419
- if (opts.profileWarmupDir) {
420
- // Isolated copy only (caller guarantees). Never point this at a live profile.
421
- launchArgs.push(`--user-data-dir=${opts.profileWarmupDir}`);
422
- }
423
495
  const proxy = trustedBrowserEnv("PUPPETEER_PROXY");
424
496
  if (proxy) {
425
497
  launchArgs.push(`--proxy-server=${proxy}`);
@@ -442,15 +514,62 @@ export async function launchHeadlessBrowser(opts: LaunchHeadlessOptions): Promis
442
514
  // cannot load into Chromium.
443
515
  const launchEnv: Record<string, string> = projectSafeSpawnEnv();
444
516
  if (opts.geo?.timezone) launchEnv.TZ = opts.geo.timezone;
445
- return await puppeteer.launch({
446
- headless: opts.headless,
447
- defaultViewport: opts.headless ? initialViewport : null,
448
- executablePath: await ensureChromiumExecutable(),
449
- args: launchArgs,
450
- env: launchEnv,
451
- ignoreDefaultArgs: [...STEALTH_IGNORE_DEFAULT_ARGS],
452
- protocolTimeout: BROWSER_PROTOCOL_TIMEOUT_MS,
453
- });
517
+
518
+ try {
519
+ const browser = await puppeteer.launch({
520
+ headless: opts.headless,
521
+ userDataDir,
522
+ defaultViewport: opts.headless ? initialViewport : null,
523
+ executablePath: await ensureChromiumExecutable(),
524
+ args: launchArgs,
525
+ env: launchEnv,
526
+ ignoreDefaultArgs: [...STEALTH_IGNORE_DEFAULT_ARGS],
527
+ protocolTimeout: BROWSER_PROTOCOL_TIMEOUT_MS,
528
+ });
529
+ return { browser, createdUserDataDir };
530
+ } catch (err) {
531
+ // If launch fails and we created or were given a userDataDir, attempt cleanup with retry.
532
+ // Chrome may still be starting up and holding files when launch fails,
533
+ // so a transient EBUSY error should trigger a bounded retry, not abandon cleanup.
534
+ // If cleanup fails with EBUSY even after retries, hand off to deferred cleanup
535
+ // to prevent leaking temp directories. Preserve the original launch error regardless
536
+ // of cleanup outcome.
537
+ const dirToCleanup = createdUserDataDir || opts.profileWarmupDir;
538
+ if (dirToCleanup) {
539
+ try {
540
+ const cleanupResult = await cleanupProfileDirWithRetry(dirToCleanup);
541
+ if (!cleanupResult.removed) {
542
+ logger.debug("Failed to clean up profile directory after launch failure", {
543
+ dir: dirToCleanup,
544
+ error: cleanupResult.error.message,
545
+ });
546
+ }
547
+ } catch (cleanupErr) {
548
+ // If cleanup failed with EBUSY despite retries, defer the cleanup
549
+ const cleanupError = cleanupErr as Error;
550
+ if (cleanupError.message.includes("EBUSY")) {
551
+ try {
552
+ deferredProfileCleanup.deferProfileDirCleanup(dirToCleanup);
553
+ logger.debug("Deferred profile directory cleanup due to EBUSY", {
554
+ dir: dirToCleanup,
555
+ });
556
+ } catch (deferErr) {
557
+ logger.warn("Failed to defer profile directory cleanup", {
558
+ dir: dirToCleanup,
559
+ error: (deferErr as Error).message,
560
+ });
561
+ }
562
+ } else {
563
+ // Not EBUSY but some other error that wasn't caught above, just log it
564
+ logger.debug("Unexpected error from cleanup retry", {
565
+ dir: dirToCleanup,
566
+ error: cleanupError.message,
567
+ });
568
+ }
569
+ }
570
+ }
571
+ throw err;
572
+ }
454
573
  }
455
574
 
456
575
  export async function applyViewport(
@@ -14,9 +14,11 @@ import {
14
14
  killExistingByPath,
15
15
  waitForCdp,
16
16
  } from "./attach";
17
+ import { deferredProfileDirSnapshot, forgetDeferredProfileDir } from "./deferred-profile-cleanup";
17
18
  import {
18
19
  BROWSER_PROTOCOL_TIMEOUT_MS,
19
20
  canDecryptProfileCookies,
21
+ cleanupProfileDirWithRetry,
20
22
  headlessExecutableForProfileReuse,
21
23
  launchHeadlessBrowser,
22
24
  loadPuppeteer,
@@ -143,6 +145,29 @@ export function createOwnedWarmupDirForTest(handle: BrowserHandle): string {
143
145
  return dir;
144
146
  }
145
147
 
148
+ /**
149
+ * Attempt to clean up deferred dirs that may no longer be held by Chrome processes.
150
+ * Best-effort: logs failures but does not throw.
151
+ *
152
+ * @internal Called opportunistically during acquire and disposal
153
+ */
154
+ async function processDeferredCleanup(): Promise<void> {
155
+ const dirs = deferredProfileDirSnapshot();
156
+ for (const dir of dirs) {
157
+ try {
158
+ const result = await cleanupProfileDirWithRetry(dir);
159
+ if (result.removed) {
160
+ forgetDeferredProfileDir(dir);
161
+ }
162
+ } catch (err) {
163
+ logger.debug("Failed to clean up deferred profile dir (EBUSY after retries)", {
164
+ dir,
165
+ error: (err as Error).message,
166
+ });
167
+ }
168
+ }
169
+ }
170
+
146
171
  export async function acquireBrowser(kind: BrowserKind, opts: AcquireBrowserOptions): Promise<BrowserHandle> {
147
172
  const geo = kind.kind === "headless" ? normalizeGeo(opts.geo) : undefined;
148
173
  const key = browserKey(kind, geo, opts.profileReuse);
@@ -155,6 +180,10 @@ export async function acquireBrowser(kind: BrowserKind, opts: AcquireBrowserOpti
155
180
  const pending = browserOpenPromises.get(key);
156
181
  if (pending) return await pending;
157
182
 
183
+ // Opportunistically clean up any deferred dirs when acquiring a new browser.
184
+ // This ensures they don't pile up across multiple browser sessions.
185
+ await processDeferredCleanup();
186
+
158
187
  const opening = openBrowserHandle(kind, opts, geo, key).then(handle => {
159
188
  browsers.set(key, handle);
160
189
  return handle;
@@ -199,17 +228,37 @@ async function openBrowserHandle(
199
228
  }
200
229
  }
201
230
  let browser: Browser;
231
+ let createdUserDataDir: string | undefined;
202
232
  try {
203
- browser = await launchHeadlessBrowser({
233
+ const launchResult = await launchHeadlessBrowser({
204
234
  headless: kind.headless,
205
235
  viewport: opts.viewport,
206
236
  profileWarmupDir,
207
237
  ...(geo ? { geo } : {}),
208
238
  });
239
+ browser = launchResult.browser;
240
+ createdUserDataDir = launchResult.createdUserDataDir;
209
241
  } catch (error) {
210
- // Launch failed after the warm-up copy landed: drop the temp dir here,
211
- // because no handle will exist to carry it into releaseBrowser().
212
- removeWarmupDir(profileWarmupDir);
242
+ // Launch failed: drop the warm-up copy or created temp dir here,
243
+ // because no handle will exist to carry them into releaseBrowser().
244
+ // Use retry cleanup in case Chrome is still holding files from startup.
245
+ if (profileWarmupDir) {
246
+ try {
247
+ const cleanupResult = await cleanupProfileDirWithRetry(profileWarmupDir);
248
+ if (!cleanupResult.removed) {
249
+ logger.debug("Failed to clean up profile warmup dir after launch failure", {
250
+ dir: profileWarmupDir,
251
+ error: cleanupResult.error.message,
252
+ });
253
+ }
254
+ } catch (cleanupErr) {
255
+ // EBUSY after retries: log but don't mask original error
256
+ logger.debug("Failed to clean up profile warmup dir (EBUSY after retries)", {
257
+ dir: profileWarmupDir,
258
+ error: (cleanupErr as Error).message,
259
+ });
260
+ }
261
+ }
213
262
  throw error;
214
263
  }
215
264
  const handle: BrowserHandle = {
@@ -224,8 +273,10 @@ async function openBrowserHandle(
224
273
  };
225
274
  // Record ownership only here, where this module created the dir. Disposal
226
275
  // deletes solely what this map holds, so a caller-supplied path is never
227
- // a deletion target.
228
- if (profileWarmupDir) ownedWarmupDirs.set(handle, profileWarmupDir);
276
+ // a deletion target. Track both profileWarmupDir (caller-supplied) and
277
+ // createdUserDataDir (gjc-created) under the same ownership key.
278
+ const ownedDir = createdUserDataDir || profileWarmupDir;
279
+ if (ownedDir) ownedWarmupDirs.set(handle, ownedDir);
229
280
  return handle;
230
281
  }
231
282
  if (kind.kind === "connected") {
@@ -485,25 +536,26 @@ export async function releaseBrowser(handle: BrowserHandle, opts: { kill: boolea
485
536
  * Delete the warm-up dir this module created for `handle`, if any.
486
537
  *
487
538
  * The path comes from `ownedWarmupDirs`, never from the caller, so recursive deletion
488
- * can only ever target a dir this registry made. The entry is consumed first, making a
489
- * second call a no-op even if disposal runs twice.
539
+ * can only ever target a dir this registry made. The entry is consumed only after
540
+ * removal succeeds, ensuring a failed removal can be retried.
490
541
  *
491
542
  * Best-effort: a leftover temp dir is preferable to a teardown that throws.
543
+ * Uses bounded retry on transient EBUSY errors to handle Chrome still holding files.
492
544
  */
493
- function removeOwnedWarmupDir(handle: BrowserHandle): void {
545
+ async function removeOwnedWarmupDir(handle: BrowserHandle): Promise<void> {
494
546
  const dir = ownedWarmupDirs.get(handle);
495
547
  if (dir === undefined) return;
496
- ownedWarmupDirs.delete(handle);
497
- removeWarmupDir(dir);
498
- }
499
-
500
- /** Delete a dir this module created. Callers must have proven ownership first. */
501
- function removeWarmupDir(dir: string | undefined): void {
502
- if (!dir) return;
548
+ // Use retry cleanup in case Chrome is still holding files after close().
549
+ // Only delete the entry after successful removal. If removal fails even with retry,
550
+ // log and move on (best-effort cleanup to avoid propagating errors during teardown).
503
551
  try {
504
- fs.rmSync(dir, { recursive: true, force: true });
552
+ const cleanupResult = await cleanupProfileDirWithRetry(dir);
553
+ if (cleanupResult.removed) {
554
+ ownedWarmupDirs.delete(handle);
555
+ }
505
556
  } catch (err) {
506
- logger.debug("Failed to remove Chrome profile warm-up dir", {
557
+ // EBUSY after retries: log but don't mask other cleanup/teardown operations
558
+ logger.debug("Failed to remove owned warmup dir (EBUSY after retries)", {
507
559
  dir,
508
560
  error: (err as Error).message,
509
561
  });
@@ -530,7 +582,8 @@ async function disposeBrowserHandle(handle: BrowserHandle, opts: { kill: boolean
530
582
  if (opts.kill && proc?.pid !== undefined) await gracefulKillTreeOnce(proc.pid);
531
583
  // Chrome owns files under the warm-up dir until the process is gone, so this
532
584
  // runs after close()/kill rather than alongside them.
533
- removeOwnedWarmupDir(handle);
585
+ // Use bounded retry on transient EBUSY to ensure cleanup completes.
586
+ await removeOwnedWarmupDir(handle);
534
587
  return;
535
588
  }
536
589
  if (handle.kind.kind === "connected") {
@@ -280,6 +280,8 @@ export interface ToolSession {
280
280
  waitForFollowUpQueued?: (signal: AbortSignal) => Promise<void>;
281
281
  /** Get session ID */
282
282
  getSessionId?: () => string | null;
283
+ /** Changes only when a different session identity or transcript is adopted; a cwd move keeps it. */
284
+ getSessionIdentityGeneration?: () => number;
283
285
  /**
284
286
  * Opaque async-job ownership/lookup endpoint key. This is not a workflow or
285
287
  * path identity: workflow/session consumers must use getSessionId(). Only
@@ -401,6 +403,8 @@ export interface ToolSession {
401
403
  getSdkPermissionProvider?: () => ClientBridge["requestPermission"];
402
404
  /** Bridge to the connected client (e.g. ACP editor host). Tools should route fs/terminal/permission requests through this when available. */
403
405
  getClientBridge?: () => ClientBridge | undefined;
406
+ /** True once the owning session is disposed; background retries stop then. */
407
+ isSessionDisposed?: () => boolean;
404
408
  /** Get compact conversation context for subagents (excludes tool results, system prompts) */
405
409
  getCompactContext?: () => string;
406
410
  /** Get cached todo phases for this session. */
@@ -459,7 +463,12 @@ export interface ToolSession {
459
463
  * tool to dispatch another skill prompt same-turn after recording a handoff. */
460
464
  sendCustomMessage?(
461
465
  message: Pick<CustomMessage, "customType" | "content" | "display" | "details" | "attribution">,
462
- options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
466
+ options?: {
467
+ triggerTurn?: boolean;
468
+ deliverAs?: "steer" | "followUp" | "nextTurn";
469
+ /** Hidden next-turn provenance: "external" (background producer) survives a terminal abort. */
470
+ origin?: "turn" | "external";
471
+ },
463
472
  ): Promise<void>;
464
473
  /** Get the active OpenTelemetry config so subagent dispatch can forward
465
474
  * the parent's tracer/hooks with the subagent's own identity stamped. */