@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
@@ -15,22 +15,55 @@ import { formatBytes, sanitizeDisplayLine, sanitizeText } from "@gajae-code/util
15
15
  import { theme } from "../../modes/theme/theme";
16
16
  import { matchesAppInterrupt } from "../../modes/utils/keybinding-matchers";
17
17
  import type { ResumeSessionIdentity } from "../../sdk/session-readonly/storage";
18
+ import type { SessionHandoverOutcome, SessionHandoverWaitOptions } from "../../session/session-handover";
18
19
  import { prioritizeStarredSessions, type ResumeTailInspection, type SessionInfo } from "../../session/session-manager";
20
+ import {
21
+ type SessionHeldError,
22
+ type SessionOwnerClaim,
23
+ sessionOwnerHolderMarker,
24
+ } from "../../session/session-ownership";
19
25
  import { DynamicBorder } from "./dynamic-border";
20
26
  import { HookSelectorComponent } from "./hook-selector";
27
+ import { createHeldSessionWarning, SESSION_HOST_WAITING_MESSAGE } from "./session-held-warning";
21
28
 
22
29
  export interface SelectedSession {
23
30
  kind: "selected";
24
31
  path: string;
25
32
  identity: ResumeSessionIdentity;
26
33
  action: "continue-tail" | "open-idle";
34
+ /** Continue here's claim of the session: the caller releases it once its open has claimed. */
35
+ admission?: SessionOwnerClaim;
27
36
  }
28
37
 
29
38
  export interface CancelledSessionSelection {
30
39
  kind: "cancelled";
31
40
  }
32
41
 
33
- export type SessionSelectionResult = SelectedSession | CancelledSessionSelection;
42
+ /** Fork chosen from the held-session warning: the session stays with its holder, a copy opens idle. */
43
+ export interface ForkHeldSessionSelection {
44
+ kind: "fork";
45
+ path: string;
46
+ error: SessionHeldError;
47
+ }
48
+
49
+ export type SessionSelectionResult = SelectedSession | CancelledSessionSelection | ForkHeldSessionSelection;
50
+ /** A session another process holds, as checked when it is chosen. */
51
+ export interface HeldSession {
52
+ readonly error: SessionHeldError;
53
+ /**
54
+ * Continue here (design §13 L1), only when the holder is a broker-launched host: close it and
55
+ * claim the session for the caller, which releases the claim once its open has claimed.
56
+ */
57
+ readonly handOver?: () => Promise<SessionHandoverOutcome>;
58
+ }
59
+ /**
60
+ * Whether another process holds a session, checked when it is chosen (enforce only). `wait` lets the
61
+ * picker show the wait for a launched host and stop it when the check is abandoned.
62
+ */
63
+ export type HeldSessionCheck = (
64
+ session: SessionInfo,
65
+ wait?: SessionHandoverWaitOptions,
66
+ ) => Promise<HeldSession | undefined>;
34
67
  export type SessionInspector = (sessionPath: string) => Promise<ResumeTailInspection>;
35
68
 
36
69
  /** One picker row. Keep each newline as its own space, then drop terminal controls. */
@@ -46,12 +79,16 @@ type SelectorState =
46
79
  | { kind: "starring"; token: number }
47
80
  | { kind: "checking"; session: SessionInfo; token: number }
48
81
  | { kind: "confirming"; session: SessionInfo; token: number; identity: ResumeSessionIdentity }
82
+ | { kind: "warning"; session: SessionInfo; token: number }
83
+ /** Continue here is closing the holder: input is frozen and it cannot be cancelled. */
84
+ | { kind: "handing-over"; session: SessionInfo; token: number }
49
85
  | { kind: "settled" };
50
86
 
51
87
  class SessionList implements Component {
52
88
  #filteredSessions: SessionInfo[] = [];
53
89
  #selectedIndex = 0;
54
90
  readonly #searchInput = new Input();
91
+ readonly #heldMarkers = new Map<string, string>();
55
92
  #inputFrozen = false;
56
93
  onSelect?: (session: SessionInfo) => void;
57
94
  onCancel?: () => void;
@@ -74,6 +111,12 @@ class SessionList implements Component {
74
111
  this.#inputFrozen = frozen;
75
112
  }
76
113
 
114
+ /** Mark (or unmark, with `undefined`) a session another process holds, by id: `in terminal`. */
115
+ setHeldMarker(sessionId: string, marker: string | undefined): void {
116
+ if (marker === undefined) this.#heldMarkers.delete(sessionId);
117
+ else this.#heldMarkers.set(sessionId, marker);
118
+ }
119
+
77
120
  #clampSelectedIndex(): void {
78
121
  this.#selectedIndex =
79
122
  this.#filteredSessions.length === 0
@@ -157,11 +200,14 @@ class SessionList implements Component {
157
200
  const prefix = selected ? theme.fg("accent", cursor) : padding(cursorWidth);
158
201
  const message = sessionRowText(session.firstMessage).trim();
159
202
  const star = session.starred ? theme.fg("warning", `${theme.icon.star} `) : "";
203
+ const heldMarker = this.#heldMarkers.get(session.id);
204
+ const held = heldMarker ? theme.fg("warning", ` ${theme.format.bullet} ${heldMarker}`) : "";
160
205
  const title = truncateToWidth(
161
206
  sessionRowText(session.title ?? message),
162
- width - cursorWidth - visibleWidth(star),
207
+ width - cursorWidth - visibleWidth(star) - visibleWidth(held),
163
208
  );
164
- lines.push(prefix + star + (selected ? theme.bold(title) : title));
209
+ const row = prefix + star + (selected ? theme.bold(title) : title);
210
+ lines.push(held ? truncateToWidth(row + held, width) : row);
165
211
  if (session.recap) {
166
212
  // A model-written recap replaces the first-message description and is labelled as such,
167
213
  // so it is never mistaken for the user's own words.
@@ -237,6 +283,9 @@ export class SessionSelectorComponent extends Container {
237
283
  #onRequestRender?: () => void;
238
284
  #state: SelectorState = { kind: "browsing" };
239
285
  #nextToken = 0;
286
+ #heldCheck: HeldSessionCheck | undefined;
287
+ /** Stops the held check in flight, and its wait for a session host, when the picker moves on. */
288
+ #heldCheckAbort: AbortController | undefined;
240
289
 
241
290
  constructor(
242
291
  sessions: SessionInfo[],
@@ -272,6 +321,16 @@ export class SessionSelectorComponent extends Container {
272
321
  setOnRequestRender(callback: () => void): void {
273
322
  this.#onRequestRender = callback;
274
323
  }
324
+
325
+ /**
326
+ * Under enforce (design §1 row 2): mark the rows other processes hold, and, with `check`, show the
327
+ * held-session warning when one is chosen instead of resuming it. Cancel returns to the list.
328
+ */
329
+ setHeldSessions(held: ReadonlyMap<string, SessionHeldError>, check?: HeldSessionCheck): void {
330
+ for (const [sessionId, error] of held)
331
+ this.#sessionList.setHeldMarker(sessionId, sessionOwnerHolderMarker(error.holder));
332
+ this.#heldCheck = check;
333
+ }
275
334
  #clearError(): void {
276
335
  this.#messageContainer.clear();
277
336
  }
@@ -321,12 +380,16 @@ export class SessionSelectorComponent extends Container {
321
380
  else this.onCancel();
322
381
  }
323
382
  #cancel(): void {
324
- if (this.#state.kind === "settled") return;
383
+ if (this.#state.kind === "settled" || this.#state.kind === "handing-over") return;
325
384
  if (this.#state.kind === "checking") this.#nextToken++;
385
+ this.#heldCheckAbort?.abort();
326
386
  this.#settle({ kind: "cancelled" });
327
387
  }
328
388
  #exit(): void {
389
+ // A handover cannot be interrupted (it is bounded); Ctrl+C is ignored until it settles.
390
+ if (this.#state.kind === "handing-over") return;
329
391
  if (this.#state.kind !== "settled") this.#nextToken++;
392
+ this.#heldCheckAbort?.abort();
330
393
  this.#state = { kind: "settled" };
331
394
  this.#sessionList.setInputFrozen(true);
332
395
  this.onExit();
@@ -362,6 +425,40 @@ export class SessionSelectorComponent extends Container {
362
425
  this.#sessionList.setInputFrozen(true);
363
426
  this.#clearError();
364
427
  this.#requestRender();
428
+ const abort = new AbortController();
429
+ this.#heldCheckAbort = abort;
430
+ const current = () => this.#state.kind === "checking" && this.#state.token === token;
431
+ try {
432
+ // Checked again when chosen: the list's markers are only as fresh as the listing.
433
+ const held = this.#heldCheck
434
+ ? await this.#heldCheck(session, {
435
+ signal: abort.signal,
436
+ onWaiting: () => {
437
+ if (!current()) return;
438
+ this.#messageContainer.clear();
439
+ this.#messageContainer.addChild(new Text(theme.fg("muted", SESSION_HOST_WAITING_MESSAGE), 1, 0));
440
+ this.#requestRender();
441
+ },
442
+ })
443
+ : undefined;
444
+ if (!current()) return;
445
+ this.#clearError();
446
+ if (this.#heldCheck)
447
+ this.#sessionList.setHeldMarker(session.id, held && sessionOwnerHolderMarker(held.error.holder));
448
+ if (held) {
449
+ this.#showHeldWarning(session, token, held);
450
+ return;
451
+ }
452
+ } catch (error) {
453
+ this.#failCheck(token, error);
454
+ return;
455
+ } finally {
456
+ if (this.#heldCheckAbort === abort) this.#heldCheckAbort = undefined;
457
+ }
458
+ await this.#inspectChosen(session, token, inspector);
459
+ }
460
+ /** The inspection and resume confirmation of a chosen session nobody else holds. */
461
+ async #inspectChosen(session: SessionInfo, token: number, inspector: SessionInspector): Promise<void> {
365
462
  try {
366
463
  const inspection = await inspector(session.path);
367
464
  if (this.#state.kind !== "checking" || this.#state.token !== token) return;
@@ -378,21 +475,112 @@ export class SessionSelectorComponent extends Container {
378
475
  }
379
476
  this.#showResumeConfirmation(session, token, inspection.identity);
380
477
  } catch (error) {
381
- if (this.#state.kind !== "checking" || this.#state.token !== token) return;
382
- this.#state = { kind: "browsing" };
383
- this.#sessionList.setInputFrozen(false);
384
- this.#showError(error instanceof Error ? error.message : String(error));
385
- this.#requestRender();
478
+ this.#failCheck(token, error);
386
479
  }
387
480
  }
388
- #showResumeConfirmation(session: SessionInfo, token: number, identity: ResumeSessionIdentity): void {
481
+ #failCheck(token: number, error: unknown): void {
482
+ if (this.#state.kind !== "checking" || this.#state.token !== token) return;
483
+ this.#state = { kind: "browsing" };
484
+ this.#sessionList.setInputFrozen(false);
485
+ this.#showError(error instanceof Error ? error.message : String(error));
486
+ this.#requestRender();
487
+ }
488
+ /**
489
+ * Continue here: the read-only inspection and the resume confirmation come first, so nothing is
490
+ * closed before the user's final yes; then the handover, which cannot be cancelled.
491
+ */
492
+ async #continueHere(session: SessionInfo, token: number, held: HeldSession): Promise<void> {
493
+ const inspector = this.inspector;
494
+ if (!held.handOver || !inspector) return;
495
+ this.#state = { kind: "checking", session, token };
496
+ this.#requestRender();
497
+ let inspection: ResumeTailInspection;
498
+ try {
499
+ inspection = await inspector(session.path);
500
+ } catch (error) {
501
+ this.#failCheck(token, error);
502
+ return;
503
+ }
504
+ if (this.#state.kind !== "checking" || this.#state.token !== token) return;
505
+ if (inspection.kind === "error") {
506
+ this.#failCheck(token, `Unable to inspect session (${inspection.reason}).`);
507
+ return;
508
+ }
509
+ if (inspection.kind === "terminal") {
510
+ await this.#handOverAndSettle(session, token, held, inspector, "open-idle");
511
+ return;
512
+ }
513
+ this.#showResumeConfirmation(session, token, inspection.identity, () =>
514
+ this.#handOverAndSettle(session, token, held, inspector, "continue-tail"),
515
+ );
516
+ }
517
+ async #handOverAndSettle(
518
+ session: SessionInfo,
519
+ token: number,
520
+ held: HeldSession,
521
+ inspector: SessionInspector,
522
+ action: SelectedSession["action"],
523
+ ): Promise<void> {
524
+ if (!held.handOver) return;
525
+ const dialog = this.#confirmationDialog;
526
+ if (dialog) this.removeChild(dialog);
527
+ this.#confirmationDialog = null;
528
+ this.#state = { kind: "handing-over", session, token };
529
+ this.#sessionList.setInputFrozen(true);
530
+ this.#messageContainer.clear();
531
+ this.#messageContainer.addChild(new Text(theme.fg("muted", "Handing the session over…"), 1, 0));
532
+ this.#requestRender();
533
+ // Still this handover: nothing settled the picker meanwhile.
534
+ const current = () => this.#state.kind === "handing-over" && this.#state.token === token;
535
+ let claim: SessionOwnerClaim | undefined;
536
+ try {
537
+ const outcome = await held.handOver();
538
+ if (outcome.kind === "closed") claim = outcome.claim;
539
+ if (!current()) {
540
+ claim?.release();
541
+ return;
542
+ }
543
+ if (outcome.kind === "refused") {
544
+ this.#clearError();
545
+ this.#showHeldWarning(session, token, held, outcome.message);
546
+ return;
547
+ }
548
+ this.#sessionList.setHeldMarker(session.id, undefined);
549
+ // Read the tail again under the claim: the host may have finished a turn since the first read.
550
+ const inspection = await inspector(session.path);
551
+ if (!current()) {
552
+ claim?.release();
553
+ return;
554
+ }
555
+ if (inspection.kind === "error") throw new Error(`Unable to inspect session (${inspection.reason}).`);
556
+ const settled = { kind: "selected", path: session.path, identity: inspection.identity } as const;
557
+ this.#settle({
558
+ ...settled,
559
+ action: inspection.kind === "terminal" ? "open-idle" : action,
560
+ ...(claim ? { admission: claim } : {}),
561
+ });
562
+ } catch (error) {
563
+ // Never back to the list while holding the session, and never on a picker that closed.
564
+ claim?.release();
565
+ if (!current()) return;
566
+ this.#state = { kind: "checking", session, token };
567
+ this.#failCheck(token, error);
568
+ }
569
+ }
570
+ #showResumeConfirmation(
571
+ session: SessionInfo,
572
+ token: number,
573
+ identity: ResumeSessionIdentity,
574
+ onYes?: () => Promise<void>,
575
+ ): void {
389
576
  this.#state = { kind: "confirming", session, token, identity };
390
577
  const dialog = new HookSelectorComponent(
391
578
  "Resume this session?",
392
579
  ["Yes", "No"],
393
580
  option => {
394
581
  if (this.#confirmationDialog !== dialog || this.#state.kind !== "confirming") return;
395
- if (option === "Yes")
582
+ if (option === "Yes" && onYes) void onYes();
583
+ else if (option === "Yes")
396
584
  this.#settle({ kind: "selected", path: session.path, identity, action: "continue-tail" });
397
585
  else this.#settle({ kind: "cancelled" });
398
586
  },
@@ -403,6 +591,41 @@ export class SessionSelectorComponent extends Container {
403
591
  this.addChild(dialog);
404
592
  this.#requestRender();
405
593
  }
594
+ #showHeldWarning(session: SessionInfo, token: number, held: HeldSession, note?: string): void {
595
+ this.#state = { kind: "warning", session, token };
596
+ const { error } = held;
597
+ const dialog = createHeldSessionWarning(
598
+ error,
599
+ choice => {
600
+ if (this.#confirmationDialog !== dialog || this.#state.kind !== "warning") return;
601
+ switch (choice) {
602
+ case "fork":
603
+ this.#settle({ kind: "fork", path: session.path, error });
604
+ return;
605
+ case "continue":
606
+ this.removeChild(dialog);
607
+ this.#confirmationDialog = null;
608
+ void this.#continueHere(session, token, held);
609
+ return;
610
+ case "cancel":
611
+ this.removeChild(dialog);
612
+ this.#confirmationDialog = null;
613
+ this.#state = { kind: "browsing" };
614
+ this.#sessionList.setInputFrozen(false);
615
+ this.#requestRender();
616
+ return;
617
+ default: {
618
+ const unknown: never = choice;
619
+ throw new Error(`Unknown held-session choice: ${String(unknown)}`);
620
+ }
621
+ }
622
+ },
623
+ { continueHere: held.handOver !== undefined, note },
624
+ );
625
+ this.#confirmationDialog = dialog;
626
+ this.addChild(dialog);
627
+ this.#requestRender();
628
+ }
406
629
  #showDeleteConfirmation(session: SessionInfo): void {
407
630
  if (this.#state.kind !== "browsing" || this.#confirmationDialog) return;
408
631
  const fromTitle = session.title ? sessionRowText(session.title) : "";
@@ -78,6 +78,7 @@ export class GoalModeController {
78
78
  #goalHeldSnapshotKey: string | undefined;
79
79
  #goalTimeoutFingerprint: string | undefined;
80
80
  #goalIdenticalTimeoutStreak = 0;
81
+ #completedExit: Promise<void> | undefined;
81
82
 
82
83
  constructor(private readonly ctx: GoalModeControllerContext) {}
83
84
 
@@ -123,10 +124,21 @@ export class GoalModeController {
123
124
 
124
125
  async beforeGetUserInput(): Promise<void> {
125
126
  if (this.ctx.session.getGoalModeState()?.mode === "exiting") {
126
- await this.exit({ reason: "completed", silent: true });
127
+ await this.#exitCompletedGoal();
127
128
  }
128
129
  }
129
130
 
131
+ /**
132
+ * agent_end and the next input prompt both observe the "exiting" state before the
133
+ * exit clears it; they must share one exit instead of racing two tool restores.
134
+ */
135
+ #exitCompletedGoal(): Promise<void> {
136
+ this.#completedExit ??= this.exit({ reason: "completed", silent: true }).finally(() => {
137
+ this.#completedExit = undefined;
138
+ });
139
+ return this.#completedExit;
140
+ }
141
+
130
142
  scheduleContinuation(): void {
131
143
  this.cancelContinuation();
132
144
  if (!this.ctx.inputCallback) return;
@@ -258,7 +270,7 @@ export class GoalModeController {
258
270
  this.#resetTimeoutHold();
259
271
  }
260
272
  if (this.ctx.session.getGoalModeState()?.mode === "exiting") {
261
- await this.exit({ reason: "completed", silent: true });
273
+ await this.#exitCompletedGoal();
262
274
  return;
263
275
  }
264
276
  this.scheduleContinuation();
@@ -1,3 +1,4 @@
1
+ import * as path from "node:path";
1
2
  import * as util from "node:util";
2
3
  import { ThinkingLevel } from "@gajae-code/agent-core";
3
4
  import {
@@ -82,8 +83,17 @@ import {
82
83
  SharedControlPublicationError,
83
84
  } from "../../session/agent-session";
84
85
  import { CREDENTIAL_STORE_UNREADABLE_MESSAGE } from "../../session/credential-store-errors";
86
+ import { probeHeldSessions, resolveSessionOwnership } from "../../session/internal/session-claim-set";
87
+ import { operatorErrorMessage } from "../../session/operator-error-message";
88
+ import { checkSessionHandover, handOverSession, type SessionHandoverCheck } from "../../session/session-handover";
85
89
  import { GraphSuccessorUnavailableError, type SessionInfo, SessionManager } from "../../session/session-manager";
86
90
  import { getTreeForInternalRead } from "../../session/session-manager-internal";
91
+ import {
92
+ SessionHeldError,
93
+ type SessionOwnerClaim,
94
+ sessionHeldForkCommand,
95
+ sessionHeldForkedNotice,
96
+ } from "../../session/session-ownership";
87
97
  import { FileSessionStorage } from "../../session/session-storage";
88
98
  import {
89
99
  CREDENTIAL_AUTO_IMPORT_DISCOVERY_WARNING,
@@ -183,6 +193,11 @@ import {
183
193
  } from "../components/provider-onboarding-selector";
184
194
  import { ProviderOrderContext } from "../components/provider-order-context";
185
195
  import { ProviderOrderEditorComponent } from "../components/provider-order-editor";
196
+ import {
197
+ heldSessionChoice,
198
+ heldSessionWarningDialog,
199
+ SESSION_HOST_WAITING_MESSAGE,
200
+ } from "../components/session-held-warning";
186
201
  import { SessionObserverOverlayComponent } from "../components/session-observer-overlay";
187
202
  import { SessionSelectorComponent } from "../components/session-selector";
188
203
  import { dashboardSessions, SessionsDashboardComponent } from "../components/sessions-dashboard";
@@ -2403,6 +2418,13 @@ export class SelectorController {
2403
2418
  async showSessionSelector(): Promise<void> {
2404
2419
  const sessions = await this.ctx.sessionManager.listForResumePickerReadOnly();
2405
2420
  if (this.ctx.isStopped?.()) return;
2421
+ // Under enforce, rows other processes hold are marked; choosing one warns (design §1 row 3).
2422
+ const heldProbe = probeHeldSessions(
2423
+ resolveSessionOwnership(),
2424
+ sessions.map(session => session.id),
2425
+ );
2426
+ const held = heldProbe ? await heldProbe : undefined;
2427
+ if (this.ctx.isStopped?.()) return;
2406
2428
  this.showSelector(done => {
2407
2429
  const selector = new SessionSelectorComponent(
2408
2430
  sessions,
@@ -2413,7 +2435,19 @@ export class SelectorController {
2413
2435
  // unhandled rejection that can kill the process. Do not auto-retry.
2414
2436
  done();
2415
2437
  void this.handleResumeSession(sessionPath).catch(error => {
2416
- this.ctx.showError(error instanceof Error ? error.message : String(error));
2438
+ // A refusal (a session open in another process, under enforce) carries operator text.
2439
+ // `/fork` here would fork the current session, so name the command that copies this one.
2440
+ const fork =
2441
+ error instanceof SessionHeldError
2442
+ ? sessionHeldForkCommand(
2443
+ error.sessionId,
2444
+ this.ctx.sessionManager.isManagedDestination()
2445
+ ? {}
2446
+ : { sessionDir: this.ctx.sessionManager.getSessionDir() },
2447
+ )
2448
+ : undefined;
2449
+ const message = operatorErrorMessage(error, String(error));
2450
+ this.ctx.showError(fork ? `${message} To continue it in a copy, quit and run: ${fork}` : message);
2417
2451
  });
2418
2452
  },
2419
2453
  () => {
@@ -2442,6 +2476,7 @@ export class SelectorController {
2442
2476
  (session, starred) => this.ctx.sessionManager.setSessionStarredForPicker(session, starred),
2443
2477
  );
2444
2478
  selector.setOnRequestRender(() => this.ctx.ui.requestRender());
2479
+ if (held) selector.setHeldSessions(held);
2445
2480
  return { component: selector, focus: selector };
2446
2481
  });
2447
2482
  }
@@ -2516,7 +2551,14 @@ export class SelectorController {
2516
2551
  */
2517
2552
  #resumeInFlight = false;
2518
2553
 
2519
- async handleResumeSession(sessionPath: string): Promise<void> {
2554
+ /**
2555
+ * `cancelledStatus`: what Cancel on the held-session warning says (default `Resume cancelled`);
2556
+ * `continueHere: false` offers Fork and Cancel only.
2557
+ */
2558
+ async handleResumeSession(
2559
+ sessionPath: string,
2560
+ options?: { readonly cancelledStatus?: string; readonly continueHere?: boolean },
2561
+ ): Promise<void> {
2520
2562
  this.ctx.promptSuggestion?.clear();
2521
2563
  if (this.#resumeInFlight) {
2522
2564
  this.ctx.showStatus("Resume already in progress");
@@ -2528,7 +2570,31 @@ export class SelectorController {
2528
2570
  // session-manager accessor, an unavailable status rail) can never strand the
2529
2571
  // guard and silently disable every later resume.
2530
2572
  let progressLease: ResumeProgressLease | undefined;
2573
+ let admission: SessionOwnerClaim | undefined;
2574
+ /** Only a copy the Fork branch created; deleted below unless the switch landed on it. */
2575
+ let forkCopy: string | undefined;
2576
+ let resumedStatus = "Resumed session";
2531
2577
  try {
2578
+ // Under enforce the target is claimed first (design §1 row 3), before the spinner and before
2579
+ // its preparation; the claim covers it until the switch's own claim lands. A session another
2580
+ // process holds gets the warning instead: Cancel stays here, Fork switches to a copy.
2581
+ const admitting = this.ctx.sessionManager.switchTargetAdmission(sessionPath);
2582
+ if (admitting) {
2583
+ try {
2584
+ admission = await admitting;
2585
+ } catch (error) {
2586
+ if (!(error instanceof SessionHeldError)) throw error;
2587
+ const forked = await this.#forkHeldSession(sessionPath, error, options);
2588
+ if (!forked) return;
2589
+ if (forked.kind === "continued") admission = forked.admission;
2590
+ else {
2591
+ ({ sessionPath, admission } = forked);
2592
+ forkCopy = forked.discardIfUnused;
2593
+ resumedStatus = sessionHeldForkedNotice(error);
2594
+ }
2595
+ }
2596
+ if (this.ctx.isStopped?.()) return;
2597
+ }
2532
2598
  const previousSessionId = this.ctx.sessionManager.getSessionId();
2533
2599
  progressLease = acquireResumeProgressLease(this.ctx);
2534
2600
  await progressLease.committed;
@@ -2616,15 +2682,138 @@ export class SelectorController {
2616
2682
  );
2617
2683
  await this.ctx.reloadTodos();
2618
2684
  if (this.ctx.isStopped?.()) return;
2619
- this.ctx.showStatus("Resumed session");
2685
+ this.ctx.showStatus(resumedStatus);
2620
2686
  this.#maybePromptResumeModelChoice();
2621
2687
  } finally {
2688
+ // A cancelled, busy, stopped or failed switch leaves the Fork's copy unused: delete it while
2689
+ // its admission claim still holds, so it never becomes the newest session.
2690
+ if (forkCopy) await this.#discardForkCopyIfUnused(forkCopy);
2691
+ admission?.release();
2622
2692
  progressLease?.clear();
2623
2693
  this.#resumeInFlight = false;
2624
2694
  releaseActivityIndicator();
2625
2695
  }
2626
2696
  }
2627
2697
 
2698
+ /**
2699
+ * Delete a copy a Fork created unless the session landed on it, through the picker's delete path.
2700
+ * Never throws, so the caller's claim release and in-flight reset always run after it.
2701
+ */
2702
+ async #discardForkCopyIfUnused(sessionPath: string): Promise<void> {
2703
+ try {
2704
+ const current = this.ctx.sessionManager.getSessionFile();
2705
+ if (current !== undefined && path.resolve(current) === path.resolve(sessionPath)) return;
2706
+ await this.#deleteSession(sessionPath);
2707
+ } catch (error) {
2708
+ logger.warn("Could not delete an unused fork of a held session", {
2709
+ error: error instanceof Error ? error.message : String(error),
2710
+ });
2711
+ }
2712
+ }
2713
+
2714
+ /**
2715
+ * The held-session warning for `/resume` (design §3.1). On Fork, copy the held session into this
2716
+ * session's store, reading it in place, and return the copy to switch to, with an admission claim
2717
+ * that covers it once the forking manager closes. On Continue here (a broker-launched holder,
2718
+ * design §13 L1), close the holder and return the admission claim of the session itself, with no
2719
+ * copy to delete. `undefined` on Cancel: the current session stays as it was, still claimed.
2720
+ */
2721
+ async #forkHeldSession(
2722
+ sessionPath: string,
2723
+ probed: SessionHeldError,
2724
+ warning?: { readonly cancelledStatus?: string; readonly continueHere?: boolean },
2725
+ ): Promise<
2726
+ | {
2727
+ readonly kind: "forked";
2728
+ readonly sessionPath: string;
2729
+ readonly admission: SessionOwnerClaim | undefined;
2730
+ /** The copy this Fork created, and only that: the one path the caller may delete. */
2731
+ readonly discardIfUnused: string;
2732
+ }
2733
+ | { readonly kind: "continued"; readonly admission: SessionOwnerClaim | undefined }
2734
+ | undefined
2735
+ > {
2736
+ // The session's own agent dir and claim decision, as the launch and this switch's admission use.
2737
+ const agentDir = this.ctx.settings.getAgentDir();
2738
+ // A refused turn on the current session offers Fork and Cancel only, so it looks up no handover.
2739
+ let check: SessionHandoverCheck = { error: probed, target: undefined };
2740
+ if (warning?.continueHere !== false) {
2741
+ // Waiting for a launched host to publish shows in the status line; quitting ends the wait.
2742
+ const stop = new AbortController();
2743
+ const offStop = this.ctx.onStop?.(() => stop.abort());
2744
+ try {
2745
+ check = await checkSessionHandover(probed, agentDir, {
2746
+ signal: stop.signal,
2747
+ onWaiting: () => this.ctx.showStatus(SESSION_HOST_WAITING_MESSAGE),
2748
+ });
2749
+ } finally {
2750
+ offStop?.();
2751
+ }
2752
+ if (this.ctx.isStopped?.()) return undefined;
2753
+ }
2754
+ // The holder let go while the warning waited: take the switch's admission claim as for an unheld session.
2755
+ if (!check.error)
2756
+ return { kind: "continued", admission: await this.ctx.sessionManager.switchTargetAdmission(sessionPath) };
2757
+ const error = check.error;
2758
+ const handover = check.target;
2759
+ let note: string | undefined;
2760
+ for (;;) {
2761
+ const { title, options } = heldSessionWarningDialog(error, { continueHere: handover !== undefined, note });
2762
+ const choice = heldSessionChoice(await this.ctx.showHookSelector(title, options));
2763
+ switch (choice) {
2764
+ case "fork":
2765
+ break;
2766
+ case "continue": {
2767
+ if (!handover || this.ctx.isStopped?.()) return undefined;
2768
+ // Not cancellable: the selector is closed and the caller waits for the claim.
2769
+ this.ctx.showStatus("Handing the session over…");
2770
+ const outcome = await handOverSession(error, agentDir, this.ctx.sessionManager.ownershipDecision);
2771
+ if (outcome.kind === "closed") return { kind: "continued", admission: outcome.claim };
2772
+ note = outcome.message;
2773
+ continue;
2774
+ }
2775
+ case "cancel":
2776
+ this.ctx.showStatus(warning?.cancelledStatus ?? "Resume cancelled");
2777
+ return undefined;
2778
+ default: {
2779
+ const unknown: never = choice;
2780
+ throw new Error(`Unknown held-session choice: ${String(unknown)}`);
2781
+ }
2782
+ }
2783
+ break;
2784
+ }
2785
+ if (this.ctx.isStopped?.()) return undefined;
2786
+ const migrationPolicy =
2787
+ this.ctx.settings?.get("session.directoryMigration") === "disabled" ? "disabled" : "copy-retain";
2788
+ const forked = await SessionManager.forkFrom(
2789
+ sessionPath,
2790
+ this.ctx.sessionManager.getCwd(),
2791
+ this.ctx.sessionManager.getDestinationForFork(),
2792
+ undefined,
2793
+ migrationPolicy,
2794
+ this.ctx.settings?.get("sessionMemory.mode"),
2795
+ undefined,
2796
+ // The switch moves the breadcrumb once it lands; an abandoned copy is deleted.
2797
+ { writeBreadcrumb: false },
2798
+ );
2799
+ const forkPath = forked.getSessionFile();
2800
+ let admission: SessionOwnerClaim | undefined;
2801
+ try {
2802
+ if (!forkPath) throw new Error("Fork created no session file");
2803
+ admission = await this.ctx.sessionManager.switchTargetAdmission(forkPath);
2804
+ await forked.close();
2805
+ return { kind: "forked", sessionPath: forkPath, admission, discardIfUnused: forkPath };
2806
+ } catch (failure) {
2807
+ // The copy can't be switched to: close the forking manager, delete the copy (under the
2808
+ // admission claim when one was taken; an unclaimed fresh id is known to no one else), then
2809
+ // release the claim.
2810
+ await forked.close().catch(() => undefined);
2811
+ if (forkPath) await this.#discardForkCopyIfUnused(forkPath);
2812
+ admission?.release();
2813
+ throw failure;
2814
+ }
2815
+ }
2816
+
2628
2817
  /**
2629
2818
  * When `session.resumeModelBehavior` is "ask", offer a one-shot choice after
2630
2819
  * resuming: keep the model the session was last using, or switch to whatever