@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
package/src/main.ts CHANGED
@@ -5,7 +5,6 @@
5
5
  * createAgentSession() options. The SDK does the heavy lifting.
6
6
  */
7
7
 
8
- import { existsSync } from "node:fs";
9
8
  import * as fs from "node:fs/promises";
10
9
  import * as os from "node:os";
11
10
  import * as path from "node:path";
@@ -24,15 +23,14 @@ import {
24
23
  import { startupProjectEnvSnapshot } from "@gajae-code/utils/env";
25
24
  import { canonicalEnvKey } from "@gajae-code/utils/env-file";
26
25
  import chalk from "chalk";
27
- import { selectAppendSystemPromptFile } from "./cli/append-system-prompt";
26
+ import { discoverAppendSystemPromptFile } from "./cli/append-system-prompt";
28
27
  import { type Args, resolvePlanModelOverride } from "./cli/args";
29
28
  import { processFileArguments } from "./cli/file-processor";
30
29
  import { fetchGithubChannelRelease } from "./cli/github-release";
31
30
  import { buildInitialMessage } from "./cli/initial-message";
32
31
  import { resolveLaunchDisposition } from "./cli/launch-disposition";
33
32
  import { runListModelsCommand } from "./cli/list-models";
34
- import { selectSession } from "./cli/session-picker";
35
- import { getConfigDirs } from "./config";
33
+ import { promptHeldSession, selectSession } from "./cli/session-picker";
36
34
  import { FileLockAcquireError, FileLockStagingCleanupError } from "./config/file-lock";
37
35
  import {
38
36
  activateModelProfile,
@@ -61,7 +59,12 @@ import { releaseLaunchWorktreeReservationAfterRegistration } from "./gjc-runtime
61
59
  import { persistCoordinatorRuntimeInputReady } from "./gjc-runtime/session-state-sidecar";
62
60
  import { assertMasterLaunchArgs, assertMasterLaunchDisposition, createMasterModeContext } from "./master-mode/context";
63
61
  import type { AcpStartupOptions } from "./modes/acp/startup-options";
64
- import type { SessionSelectionResult } from "./modes/components/session-selector";
62
+ import {
63
+ type HeldSessionChoice,
64
+ type HeldSessionWarningOptions,
65
+ SESSION_HOST_WAITING_MESSAGE,
66
+ } from "./modes/components/session-held-warning";
67
+ import type { HeldSession, SessionSelectionResult } from "./modes/components/session-selector";
65
68
  import type { InteractiveMode } from "./modes/interactive-mode";
66
69
  import type { PrintModeOptions } from "./modes/print-mode";
67
70
  import { initTheme, stopThemeWatcher } from "./modes/theme/theme";
@@ -81,6 +84,8 @@ import {
81
84
  } from "./sdk";
82
85
  import { processIncarnation } from "./sdk/broker/process-incarnation";
83
86
  import {
87
+ DIRECT_SESSION_REGISTRATION_ATTEMPTS,
88
+ isTransientSessionIndexLockError,
84
89
  newMasterAttestationEpoch,
85
90
  resolveSessionLocator,
86
91
  SessionIndex,
@@ -92,9 +97,11 @@ import {
92
97
  ManagedAppendIdentityMismatchError,
93
98
  RESUME_REJECTED_OPERATOR_MESSAGE,
94
99
  } from "./session/internal/managed-session-storage";
100
+ import { probeHeldSessions, resolveSessionOwnership } from "./session/internal/session-claim-set";
95
101
  import { SessionMigrationBusyError } from "./session/internal/session-open-errors";
96
102
  import { composeOperatorMessage, operatorErrorMessage } from "./session/operator-error-message";
97
103
  import { setPrimaryControlSurface } from "./session/primary-control-surface";
104
+ import { checkSessionHandover, handOverSession, type SessionHandoverWaitOptions } from "./session/session-handover";
98
105
  import {
99
106
  resolveResumableSession,
100
107
  SESSION_OVERSIZED_RECOVERY_MESSAGE,
@@ -106,6 +113,18 @@ import {
106
113
  SessionTranscriptOversizedError,
107
114
  type StrictSessionOpenResult,
108
115
  } from "./session/session-manager";
116
+ import {
117
+ SessionHeldError,
118
+ type SessionOwnerClaim,
119
+ type SessionOwnerSurface,
120
+ SessionOwnershipError,
121
+ sessionHeldForkCommand,
122
+ sessionHeldForkedNotice,
123
+ sessionOwnerHolderPhrase,
124
+ sessionOwnerSurface,
125
+ setSessionOwnerSurface,
126
+ } from "./session/session-ownership";
127
+ import { dropProjectSuppliedSessionOwnershipOverride, sessionOwnershipModeFor } from "./session/session-ownership-mode";
109
128
  import { resolveStartupAuthConfig } from "./session/startup-auth-config";
110
129
  import { runStartupCredentialAutoImportIfNeeded } from "./setup/credential-auto-import";
111
130
  import {
@@ -382,7 +401,8 @@ export async function submitInteractiveInput(
382
401
  | "showError"
383
402
  | "checkShutdownRequested"
384
403
  | "waitForAgentEnd"
385
- >,
404
+ > &
405
+ Partial<Pick<InteractiveMode, "handleRefusedSessionTurn">>,
386
406
  session: Pick<AgentSession, "prompt" | "promptCustomMessage"> & {
387
407
  continuePersistedHistory?: AgentSession["continuePersistedHistory"];
388
408
  },
@@ -391,6 +411,13 @@ export async function submitInteractiveInput(
391
411
  if (input.cancelled) {
392
412
  return;
393
413
  }
414
+ // A turn enforce refused (another process holds the session, or gjc could not check) restores
415
+ // the draft; a held session gets the held warning.
416
+ const reportFailure = (error: unknown): void => {
417
+ const refused = error instanceof SessionHeldError || error instanceof SessionOwnershipError;
418
+ if (refused && mode.handleRefusedSessionTurn) mode.handleRefusedSessionTurn(error, input);
419
+ else mode.showError(operatorErrorMessage(error));
420
+ };
394
421
 
395
422
  try {
396
423
  if (input.started) {
@@ -421,20 +448,15 @@ export async function submitInteractiveInput(
421
448
  agentEnd.promise.then(() => ({ type: "agent_end" as const })),
422
449
  ]);
423
450
  if (result.type === "error") {
424
- const errorMessage = operatorErrorMessage(result.error);
425
- mode.showError(errorMessage);
451
+ reportFailure(result.error);
426
452
  } else if (result.type === "agent_end") {
427
- void prompt.catch((error: unknown) => {
428
- const errorMessage = operatorErrorMessage(error);
429
- mode.showError(errorMessage);
430
- });
453
+ void prompt.catch(reportFailure);
431
454
  }
432
455
  } finally {
433
456
  agentEnd.dispose();
434
457
  }
435
458
  } catch (error: unknown) {
436
- const errorMessage = operatorErrorMessage(error);
437
- mode.showError(errorMessage);
459
+ reportFailure(error);
438
460
  } finally {
439
461
  mode.finishPendingSubmission(input);
440
462
  await mode.checkShutdownRequested();
@@ -966,7 +988,58 @@ export class SessionNotFoundError extends Error {
966
988
  }
967
989
  }
968
990
 
969
- export function operatorFacingSessionOpenMessage(value: unknown): string | undefined {
991
+ /** Cancel chosen in the held-session warning at launch: gjc exits 0 without opening anything (design §3.1). */
992
+ export class SessionResumeCancelledError extends Error {
993
+ constructor() {
994
+ super("Resume cancelled");
995
+ this.name = "SessionResumeCancelledError";
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * Where a printed `gjc --fork` must look for the session it copies: the transcript path the launch
1001
+ * named, and the `--session-dir` it searched, both absolute. An id alone resolves only in the
1002
+ * default store.
1003
+ */
1004
+ export interface SessionHeldForkSource {
1005
+ readonly source?: string;
1006
+ readonly sessionDir?: string;
1007
+ }
1008
+
1009
+ export function sessionHeldForkSourceFor(parsed: Args, cwd: string): SessionHeldForkSource {
1010
+ const resume = typeof parsed.resume === "string" ? parsed.resume : undefined;
1011
+ const pathForm =
1012
+ resume !== undefined && (resume.includes("/") || resume.includes("\\") || resume.endsWith(".jsonl"));
1013
+ return {
1014
+ ...(pathForm ? { source: path.resolve(cwd, resume) } : {}),
1015
+ ...(parsed.sessionDir ? { sessionDir: path.resolve(cwd, parsed.sessionDir) } : {}),
1016
+ };
1017
+ }
1018
+
1019
+ /**
1020
+ * The CLI refusal for a session another process holds (design §3.3), with the command that
1021
+ * continues it in a copy. Only a safe id, and a path quoted for the shell, is printed.
1022
+ */
1023
+ function sessionHeldCliMessage(error: SessionHeldError, print: boolean, fork: SessionHeldForkSource): string {
1024
+ const holder = sessionOwnerHolderPhrase(error.holder);
1025
+ const command = sessionHeldForkCommand(error.sessionId, { print, ...fork });
1026
+ if (!command)
1027
+ return `error: this session is open for writing in ${holder}.\nOnly one process can write a session at a time. Close it there, or fork it to continue in a copy.`;
1028
+ return `error: session ${error.sessionId.slice(0, 8)} is open for writing in ${holder}.\nOnly one process can write a session at a time. Close it there, or continue in a copy:\n ${command}`;
1029
+ }
1030
+
1031
+ /** Why `--continue` or `autoResume` started a new session (design §3.3). */
1032
+ function heldContinueNotice(error: SessionHeldError): string {
1033
+ return `Your most recent session is open in ${sessionOwnerHolderPhrase(error.holder)}, so a new session was started. Run gjc --resume to pick a session.`;
1034
+ }
1035
+
1036
+ export function operatorFacingSessionOpenMessage(
1037
+ value: unknown,
1038
+ options: { readonly print?: boolean; readonly fork?: SessionHeldForkSource } = {},
1039
+ ): string | undefined {
1040
+ if (value instanceof SessionHeldError)
1041
+ return sessionHeldCliMessage(value, options.print === true, options.fork ?? {});
1042
+ if (value instanceof SessionOwnershipError) return value.operatorMessage;
970
1043
  const code =
971
1044
  value instanceof SessionForkDeclinedError
972
1045
  ? value.code
@@ -1163,14 +1236,20 @@ export async function runInteractiveMode(
1163
1236
  let deferredInitialImages: ImageContent[] | undefined;
1164
1237
  const deferredInitialMessages: string[] = [];
1165
1238
 
1239
+ // A startup turn enforce refused goes the way a typed one does (`submitInteractiveInput`).
1240
+ const reportStartupFailure = (error: unknown, text = "", images?: ImageContent[]): void => {
1241
+ if (error instanceof SessionHeldError || error instanceof SessionOwnershipError)
1242
+ mode.handleRefusedSessionTurn(error, { text, images, cancelled: false, started: true });
1243
+ else mode.showError(operatorErrorMessage(error));
1244
+ };
1245
+
1166
1246
  const runStartupInputAndPromptLoop = async (): Promise<never> => {
1167
1247
  const hasStartupInput = initialMessage !== undefined || initialMessages.length > 0;
1168
1248
  if (!hasStartupInput && resumeAction === "continue-tail") {
1169
1249
  try {
1170
1250
  await session.continuePersistedHistory();
1171
1251
  } catch (error: unknown) {
1172
- const errorMessage = operatorErrorMessage(error);
1173
- mode.showError(errorMessage);
1252
+ reportStartupFailure(error);
1174
1253
  }
1175
1254
  }
1176
1255
 
@@ -1187,8 +1266,7 @@ export async function runInteractiveMode(
1187
1266
  maybeGenerateStartupTitle(initialMessage, initialImages);
1188
1267
  await session.prompt(initialMessage, { images: initialImages });
1189
1268
  } catch (error: unknown) {
1190
- const errorMessage = operatorErrorMessage(error);
1191
- mode.showError(errorMessage);
1269
+ reportStartupFailure(error, initialMessage, initialImages);
1192
1270
  }
1193
1271
  }
1194
1272
  }
@@ -1383,11 +1461,47 @@ async function flushChangelogVersion(): Promise<void> {
1383
1461
  }
1384
1462
  }
1385
1463
 
1464
+ /**
1465
+ * How a launch reports that `--continue` or `autoResume` started fresh because the session it would
1466
+ * continue is held: `-p --continue` refuses instead, unless `interactive`.
1467
+ */
1468
+ export interface SessionStartupNotices {
1469
+ readonly interactive: boolean;
1470
+ readonly notice: (message: string) => void;
1471
+ /**
1472
+ * Only for a launch that can show the TUI (a TTY): under enforce, `--resume` of a session another
1473
+ * process holds asks here whether to fork it (design §3.1); without it the open refuses.
1474
+ */
1475
+ readonly held?: {
1476
+ readonly choose: (error: SessionHeldError, options: HeldSessionWarningOptions) => Promise<HeldSessionChoice>;
1477
+ readonly forked: (message: string) => void;
1478
+ /** The warning is waiting for a launched session host to publish before it shows. */
1479
+ readonly waiting?: () => void;
1480
+ };
1481
+ }
1482
+
1483
+ /** What the held-session warning at launch resolved to, when it did not cancel. */
1484
+ type HeldStartupResolution =
1485
+ | { readonly kind: "forked"; readonly manager: SessionManager }
1486
+ | { readonly kind: "continued"; readonly admission: SessionOwnerClaim | undefined };
1487
+
1488
+ const STDERR_STARTUP_NOTICES: SessionStartupNotices = {
1489
+ interactive: false,
1490
+ notice: message => process.stderr.write(`${message}\n`),
1491
+ };
1492
+
1386
1493
  export async function createSessionManager(
1387
1494
  parsed: Args,
1388
1495
  cwd: string,
1389
1496
  activeSettings: Settings = settings,
1497
+ surface: SessionOwnerSurface = sessionOwnerSurface(),
1498
+ startup: SessionStartupNotices = STDERR_STARTUP_NOTICES,
1390
1499
  ): Promise<SessionManager | undefined> {
1500
+ // `gjc acp` never builds an agent here: its sessions run in broker-launched hosts, or in the
1501
+ // process that owns them. A persisting manager would open, and claim, a session it never uses.
1502
+ if (parsed.mode === "acp") return SessionManager.inMemory(cwd);
1503
+ // Read once, from the settings this launch uses, for whichever factory runs below.
1504
+ const ownership = { surface, mode: sessionOwnershipModeFor(activeSettings.getGlobal("session.ownership.mode")) };
1391
1505
  const migrationPolicy = activeSettings.get("session.directoryMigration") === "disabled" ? "disabled" : "copy-retain";
1392
1506
  const sessionMemoryMode = activeSettings.get("sessionMemory.mode");
1393
1507
  const sessionDestination = () =>
@@ -1410,6 +1524,7 @@ export async function createSessionManager(
1410
1524
  undefined,
1411
1525
  migrationPolicy,
1412
1526
  sessionMemoryMode,
1527
+ ownership,
1413
1528
  );
1414
1529
  }
1415
1530
  const match = await resolveResumableSession(
@@ -1429,6 +1544,7 @@ export async function createSessionManager(
1429
1544
  undefined,
1430
1545
  migrationPolicy,
1431
1546
  sessionMemoryMode,
1547
+ ownership,
1432
1548
  );
1433
1549
  }
1434
1550
 
@@ -1437,11 +1553,90 @@ export async function createSessionManager(
1437
1553
  }
1438
1554
  if (typeof parsed.resume === "string") {
1439
1555
  const sessionArg = parsed.resume;
1556
+ // Under enforce, a session another process holds is never opened: the launch warns and offers
1557
+ // Fork, which copies it here and also answers the different-folder question below (design §1
1558
+ // row 1). A race past this probe still meets the open's own refusal.
1559
+ // `undefined`, with nothing awaited, outside enforce or without a terminal to ask on.
1560
+ // Continue here (design §13 L1) closes a broker-launched holder and resolves to the claim
1561
+ // that covers the open below, released once the open has claimed or failed.
1562
+ const forkIfHeld = (
1563
+ sourcePath: string,
1564
+ continueHere: boolean,
1565
+ ): Promise<HeldStartupResolution | undefined> | undefined => {
1566
+ const held = startup.held;
1567
+ const probe = held && SessionManager.probeHeldTranscript(sourcePath, ownership);
1568
+ return held && probe ? forkWhenHeld(sourcePath, held, probe, continueHere) : undefined;
1569
+ };
1570
+ const forkWhenHeld = async (
1571
+ sourcePath: string,
1572
+ held: NonNullable<SessionStartupNotices["held"]>,
1573
+ probe: Promise<SessionHeldError | undefined>,
1574
+ continueHere: boolean,
1575
+ ): Promise<HeldStartupResolution | undefined> => {
1576
+ const probed = await probe;
1577
+ if (!probed) return undefined;
1578
+ const agentDir = activeSettings.getAgentDir();
1579
+ const check = continueHere
1580
+ ? await checkSessionHandover(probed, agentDir, { onWaiting: held.waiting })
1581
+ : { error: probed, target: undefined };
1582
+ // The holder let go while the warning waited: open the session as unheld.
1583
+ const refusal = check.error;
1584
+ if (!refusal) return undefined;
1585
+ const handover = check.target;
1586
+ let note: string | undefined;
1587
+ for (;;) {
1588
+ const choice = await held.choose(refusal, { continueHere: handover !== undefined, note });
1589
+ switch (choice) {
1590
+ case "fork":
1591
+ break;
1592
+ case "continue": {
1593
+ if (!handover) continue;
1594
+ const outcome = await handOverSession(refusal, agentDir, resolveSessionOwnership(ownership));
1595
+ if (outcome.kind === "closed") return { kind: "continued", admission: outcome.claim };
1596
+ note = outcome.message;
1597
+ continue;
1598
+ }
1599
+ case "cancel":
1600
+ throw new SessionResumeCancelledError();
1601
+ default: {
1602
+ const unknown: never = choice;
1603
+ throw new Error(`Unknown held-session choice: ${String(unknown)}`);
1604
+ }
1605
+ }
1606
+ break;
1607
+ }
1608
+ const forked = await SessionManager.forkFrom(
1609
+ sourcePath,
1610
+ cwd,
1611
+ sessionDestination(),
1612
+ undefined,
1613
+ migrationPolicy,
1614
+ sessionMemoryMode,
1615
+ ownership,
1616
+ );
1617
+ held.forked(sessionHeldForkedNotice(refusal));
1618
+ return { kind: "forked", manager: forked };
1619
+ };
1620
+ const openAfterHandover = async (
1621
+ held: HeldStartupResolution | undefined,
1622
+ open: () => Promise<SessionManager>,
1623
+ ): Promise<SessionManager> => {
1624
+ try {
1625
+ return await open();
1626
+ } finally {
1627
+ if (held?.kind === "continued") held.admission?.release();
1628
+ }
1629
+ };
1440
1630
  if (sessionArg.includes("/") || sessionArg.includes("\\") || sessionArg.endsWith(".jsonl")) {
1631
+ const forking = forkIfHeld(sessionArg, true);
1632
+ const held = forking && (await forking);
1633
+ if (held?.kind === "forked") return held.manager;
1441
1634
  const destination = parsed.sessionDir
1442
1635
  ? SessionManager.explicitDestination(parsed.sessionDir)
1443
1636
  : SessionManager.explicitDestination(path.dirname(sessionArg));
1444
- return await SessionManager.open(sessionArg, destination, undefined, migrationPolicy, sessionMemoryMode);
1637
+ return await openAfterHandover(held, () =>
1638
+ SessionManager.open(sessionArg, destination, undefined, migrationPolicy, sessionMemoryMode, ownership),
1639
+ );
1445
1640
  }
1446
1641
  const match = await resolveResumableSession(
1447
1642
  sessionArg,
@@ -1453,10 +1648,16 @@ export async function createSessionManager(
1453
1648
  if (!match) {
1454
1649
  throw new SessionNotFoundError(sessionArg);
1455
1650
  }
1456
- if (match.scope === "global") {
1457
- const normalizedCwd = normalizePathForComparison(cwd);
1458
- const normalizedMatchCwd = normalizePathForComparison(match.session.cwd || cwd);
1459
- if (normalizedCwd !== normalizedMatchCwd) {
1651
+ // A session from another folder is only ever forked here, so the held warning offers Fork
1652
+ // (which answers this question too), not Continue here.
1653
+ const otherFolder =
1654
+ match.scope === "global" &&
1655
+ normalizePathForComparison(cwd) !== normalizePathForComparison(match.session.cwd || cwd);
1656
+ const forking = forkIfHeld(match.session.path, !otherFolder);
1657
+ const held = forking && (await forking);
1658
+ if (held?.kind === "forked") return held.manager;
1659
+ return await openAfterHandover(held, async () => {
1660
+ if (otherFolder) {
1460
1661
  const shouldFork = await promptForkSession(match.session);
1461
1662
  if (!shouldFork) {
1462
1663
  throw new SessionForkDeclinedError(sessionArg, match.session.cwd);
@@ -1468,30 +1669,43 @@ export async function createSessionManager(
1468
1669
  undefined,
1469
1670
  migrationPolicy,
1470
1671
  sessionMemoryMode,
1672
+ ownership,
1471
1673
  );
1472
1674
  }
1473
- }
1474
- return await SessionManager.open(
1475
- match.session.path,
1476
- sessionDestination(),
1477
- undefined,
1478
- migrationPolicy,
1479
- sessionMemoryMode,
1480
- );
1481
- }
1482
- if (parsed.continue) {
1483
- return await SessionManager.continueRecent(
1484
- cwd,
1485
- sessionDestination(),
1486
- undefined,
1487
- migrationPolicy,
1488
- sessionMemoryMode,
1489
- );
1675
+ return await SessionManager.open(
1676
+ match.session.path,
1677
+ sessionDestination(),
1678
+ undefined,
1679
+ migrationPolicy,
1680
+ sessionMemoryMode,
1681
+ ownership,
1682
+ );
1683
+ });
1490
1684
  }
1685
+ // Enforce ends `continueRecent`'s search at a held session it would continue (design §1 row 4):
1686
+ // gjc then starts fresh with a notice, except `-p --continue`, which asked for that session and
1687
+ // refuses (row 10).
1688
+ const continueOrStartFresh = async (refuseWhenHeld: boolean): Promise<SessionManager> => {
1689
+ try {
1690
+ return await SessionManager.continueRecent(
1691
+ cwd,
1692
+ sessionDestination(),
1693
+ undefined,
1694
+ migrationPolicy,
1695
+ sessionMemoryMode,
1696
+ ownership,
1697
+ );
1698
+ } catch (error) {
1699
+ if (!(error instanceof SessionHeldError) || refuseWhenHeld) throw error;
1700
+ startup.notice(heldContinueNotice(error));
1701
+ return SessionManager.create(cwd, sessionDestination(), undefined, ownership);
1702
+ }
1703
+ };
1704
+ if (parsed.continue) return await continueOrStartFresh(!startup.interactive);
1491
1705
  // --resume without value is handled separately (needs picker UI)
1492
1706
  // If --session-dir provided without --continue/--resume, create new session there
1493
1707
  if (parsed.sessionDir) {
1494
- return SessionManager.create(cwd, SessionManager.explicitDestination(parsed.sessionDir));
1708
+ return SessionManager.create(cwd, SessionManager.explicitDestination(parsed.sessionDir), undefined, ownership);
1495
1709
  }
1496
1710
  // A lifecycle `/session_create` child must start a FRESH session that adopts
1497
1711
  // the pre-allocated id (GJC_SESSION_ID), never auto-resume existing history in
@@ -1509,19 +1723,19 @@ export async function createSessionManager(
1509
1723
  // buildSessionOptions restores the session's model/thinking instead of
1510
1724
  // overriding them with CLI defaults.
1511
1725
  if (activeSettings.get("autoResume")) {
1512
- const manager = await SessionManager.continueRecent(
1513
- cwd,
1514
- sessionDestination(),
1515
- undefined,
1516
- migrationPolicy,
1517
- sessionMemoryMode,
1518
- );
1726
+ // The user did not ask to continue, so even `-p` starts fresh, with the notice on stderr (D7).
1727
+ const manager = await continueOrStartFresh(false);
1519
1728
  if (manager.hasHistoryEntries()) {
1520
1729
  parsed.continue = true;
1521
1730
  }
1522
1731
  return manager;
1523
1732
  }
1524
- return SessionManager.create(cwd, SessionManager.managedDestination(cwd, activeSettings.getAgentDir()));
1733
+ return SessionManager.create(
1734
+ cwd,
1735
+ SessionManager.managedDestination(cwd, activeSettings.getAgentDir()),
1736
+ undefined,
1737
+ ownership,
1738
+ );
1525
1739
  }
1526
1740
 
1527
1741
  async function maybeAutoChdir(parsed: Args): Promise<void> {
@@ -1574,15 +1788,6 @@ async function maybeAutoChdir(parsed: Args): Promise<void> {
1574
1788
  }
1575
1789
  }
1576
1790
 
1577
- /** User APPEND_SYSTEM.md only. Repository copies are not appended. */
1578
- function discoverAppendSystemPromptFile(): string | undefined {
1579
- const candidates = getConfigDirs("", { existingOnly: false }).flatMap(entry => {
1580
- const filePath = path.join(entry.path, "APPEND_SYSTEM.md");
1581
- return existsSync(filePath) ? [{ level: entry.level, path: filePath }] : [];
1582
- });
1583
- return selectAppendSystemPromptFile(candidates);
1584
- }
1585
-
1586
1791
  async function buildSessionOptions(
1587
1792
  parsed: Args,
1588
1793
  scopedModels: ScopedModel[],
@@ -1598,7 +1803,7 @@ async function buildSessionOptions(
1598
1803
 
1599
1804
  const systemPromptSource = parsed.systemPrompt;
1600
1805
  const resolvedSystemPrompt = await resolvePromptInput(systemPromptSource, "system prompt");
1601
- const appendPromptSource = parsed.appendSystemPrompt ?? discoverAppendSystemPromptFile();
1806
+ const appendPromptSource = parsed.appendSystemPrompt ?? (await discoverAppendSystemPromptFile());
1602
1807
  const resolvedAppendPrompt = await resolvePromptInput(appendPromptSource, "append system prompt");
1603
1808
 
1604
1809
  if (sessionManager) {
@@ -1812,13 +2017,6 @@ export interface DirectSessionRegistration {
1812
2017
 
1813
2018
  const NOOP_DIRECT_SESSION_REGISTRATION: DirectSessionRegistration = { syncIdentity: async () => {} };
1814
2019
 
1815
- /**
1816
- * Appends allowed for one successor registration before the switch gives up and
1817
- * keeps the predecessor registered. `SessionIndex.append` takes the shared index
1818
- * lock independently per append, so a peer holding it is a transient failure.
1819
- */
1820
- const DIRECT_SESSION_REGISTRATION_ATTEMPTS = 3;
1821
-
1822
2020
  /** Register a durable direct CLI session while leaving ephemeral sessions lock-free. */
1823
2021
  export async function registerDirectSession(
1824
2022
  sessionManager: DirectSessionManager | undefined,
@@ -1951,16 +2149,8 @@ export async function registerDirectSession(
1951
2149
  // Only lock contention self-heals. A refused release is an identity
1952
2150
  // verdict; retrying it would mask a committed registration whose lock
1953
2151
  // generation no longer matches.
1954
- const code = (error as NodeJS.ErrnoException | undefined)?.code;
1955
- const transient =
1956
- code === "sharing_violation" ||
1957
- code === "access_denied" ||
1958
- code === "EBUSY" ||
1959
- code === "EPERM" ||
1960
- code === "EACCES" ||
1961
- code === "ENOTEMPTY" ||
1962
- code === "removal_record_busy";
1963
- if (!transient || attempt >= DIRECT_SESSION_REGISTRATION_ATTEMPTS) throw error;
2152
+ if (!isTransientSessionIndexLockError(error) || attempt >= DIRECT_SESSION_REGISTRATION_ATTEMPTS)
2153
+ throw error;
1964
2154
  await Bun.sleep(50 * attempt);
1965
2155
  }
1966
2156
  }
@@ -2117,12 +2307,14 @@ export async function runRootCommand(
2117
2307
  deps: RunRootCommandDependencies = {},
2118
2308
  ): Promise<void> {
2119
2309
  dropProjectSuppliedHerdrBinPath(process.env);
2310
+ dropProjectSuppliedSessionOwnershipOverride(process.env, startupProjectEnvSnapshot());
2120
2311
  const parsedArgs = parsed;
2121
2312
  assertMasterLaunchArgs(parsedArgs);
2122
2313
  let initialThemeInitialized = false;
2123
2314
  let autoChdirApplied = false;
2124
2315
  let bareResumeSessionManager: SessionManager | undefined;
2125
2316
  let bareResumeAction: "continue-tail" | "open-idle" | undefined;
2317
+ let bareResumeForkedNotice: string | undefined;
2126
2318
  let bareResumeCleanupFailed = false;
2127
2319
 
2128
2320
  if (isBareResume(parsedArgs)) {
@@ -2160,28 +2352,80 @@ export async function runRootCommand(
2160
2352
  process.stdout.write(`${chalk.dim("No sessions found")}\n`);
2161
2353
  return;
2162
2354
  }
2355
+ // Under enforce, rows other processes hold are marked, and choosing one warns (design §1 row 2).
2356
+ // The mode comes from the operator's config: picker consent comes before the scoped settings load.
2357
+ const heldOwnership = resolveSessionOwnership({ surface: "terminal" });
2358
+ const heldProbe = probeHeldSessions(
2359
+ heldOwnership,
2360
+ sessions.map(session => session.id),
2361
+ );
2362
+ const handoverAgentDir = deps.settings?.getAgentDir() ?? getAgentDir();
2363
+ const held = heldProbe && {
2364
+ sessions: await heldProbe,
2365
+ check: async (session: SessionInfo, wait?: SessionHandoverWaitOptions): Promise<HeldSession | undefined> => {
2366
+ const probed = await SessionManager.probeHeldTranscript(session.path, heldOwnership);
2367
+ if (!probed) return undefined;
2368
+ // `error` is `undefined` when the holder let go while the warning waited: resume as unheld.
2369
+ const { error, target } = await checkSessionHandover(probed, handoverAgentDir, wait);
2370
+ if (!error) return undefined;
2371
+ if (!target) return { error };
2372
+ return { error, handOver: () => handOverSession(error, handoverAgentDir, heldOwnership) };
2373
+ },
2374
+ };
2163
2375
  const selection = deps.selectResumeSession
2164
2376
  ? await deps.selectResumeSession(sessions)
2165
- : await selectSession(sessions, parsedArgs.sessionDir);
2377
+ : await selectSession(sessions, parsedArgs.sessionDir, held);
2166
2378
  if (selection.kind === "cancelled") {
2167
2379
  return;
2168
2380
  }
2169
- const scopedSettings = await (deps.loadSettingsForScope ?? Settings.loadForScope)({ cwd: resumeCwd });
2381
+ // Continue here's claim (design §13 L1) covers the open below until the open's own claim lands.
2382
+ const handoverAdmission = selection.kind === "selected" ? selection.admission : undefined;
2383
+ // Released in the `finally` below once loaded; a failed load must release it here.
2384
+ const scopedSettings = await (deps.loadSettingsForScope ?? Settings.loadForScope)({ cwd: resumeCwd }).catch(
2385
+ (error: unknown) => {
2386
+ handoverAdmission?.release();
2387
+ throw error;
2388
+ },
2389
+ );
2170
2390
  try {
2171
2391
  const resumeMigrationPolicy =
2172
2392
  scopedSettings.get("session.directoryMigration") === "disabled" ? "disabled" : "copy-retain";
2173
2393
  let opened: StrictSessionOpenResult;
2394
+ const destination = parsedArgs.sessionDir
2395
+ ? SessionManager.explicitDestination(parsedArgs.sessionDir)
2396
+ : SessionManager.managedDestination(resumeCwd, scopedSettings.getAgentDir());
2397
+ // Opened before Settings.init, so the mode comes from the scoped settings.
2398
+ const ownership = {
2399
+ surface: "terminal" as const,
2400
+ mode: sessionOwnershipModeFor(scopedSettings.getGlobal("session.ownership.mode")),
2401
+ };
2174
2402
  try {
2175
- opened = await (deps.openExistingSessionStrict ?? SessionManager.openExistingStrict)(
2176
- selection.identity,
2177
- parsedArgs.sessionDir
2178
- ? SessionManager.explicitDestination(parsedArgs.sessionDir)
2179
- : SessionManager.managedDestination(resumeCwd, scopedSettings.getAgentDir()),
2180
- undefined,
2181
- resumeMigrationPolicy,
2182
- );
2403
+ // Fork from the held-session warning: the copy opens idle; the held source is read in place.
2404
+ opened =
2405
+ selection.kind === "fork"
2406
+ ? {
2407
+ kind: "opened",
2408
+ manager: await SessionManager.forkFrom(
2409
+ selection.path,
2410
+ resumeCwd,
2411
+ destination,
2412
+ undefined,
2413
+ resumeMigrationPolicy,
2414
+ undefined,
2415
+ ownership,
2416
+ ),
2417
+ }
2418
+ : await (deps.openExistingSessionStrict ?? SessionManager.openExistingStrict)(
2419
+ selection.identity,
2420
+ destination,
2421
+ undefined,
2422
+ resumeMigrationPolicy,
2423
+ undefined,
2424
+ ownership,
2425
+ );
2183
2426
  } catch (error) {
2184
- process.stderr.write(`${operatorFacingSessionOpenMessage(error) ?? BARE_RESUME_OPEN_ERROR}\n`);
2427
+ const fork = sessionHeldForkSourceFor(parsedArgs, resumeCwd);
2428
+ process.stderr.write(`${operatorFacingSessionOpenMessage(error, { fork }) ?? BARE_RESUME_OPEN_ERROR}\n`);
2185
2429
  if (!deps.suppressProcessExit) process.exitCode = 1;
2186
2430
  return;
2187
2431
  }
@@ -2191,12 +2435,14 @@ export async function runRootCommand(
2191
2435
  return;
2192
2436
  }
2193
2437
  bareResumeSessionManager = opened.manager;
2194
- bareResumeAction = selection.action;
2438
+ bareResumeAction = selection.kind === "fork" ? "open-idle" : selection.action;
2439
+ if (selection.kind === "fork") bareResumeForkedNotice = sessionHeldForkedNotice(selection.error);
2195
2440
  } catch (error) {
2196
2441
  process.stderr.write(`${operatorFacingSessionOpenMessage(error) ?? BARE_RESUME_OPEN_ERROR}\n`);
2197
2442
  if (!deps.suppressProcessExit) process.exitCode = 1;
2198
2443
  return;
2199
2444
  } finally {
2445
+ handoverAdmission?.release();
2200
2446
  try {
2201
2447
  await scopedSettings.close?.();
2202
2448
  } catch (error) {
@@ -2226,6 +2472,7 @@ export async function runRootCommand(
2226
2472
  }
2227
2473
 
2228
2474
  const notifs: (InteractiveModeNotify | null)[] = [];
2475
+ if (bareResumeForkedNotice) notifs.push({ kind: "info", message: bareResumeForkedNotice });
2229
2476
 
2230
2477
  // Keep store authority and persistent pin intent in the same startup snapshot.
2231
2478
  // Injected discoverers own their auth unless they also supply a config resolver.
@@ -2343,6 +2590,7 @@ export async function runRootCommand(
2343
2590
  );
2344
2591
  const isInteractive = disposition.isInteractive;
2345
2592
  const mode = parsedArgs.mode || "text";
2593
+ if (mode !== "acp") setSessionOwnerSurface(isInteractive ? "terminal" : "print");
2346
2594
  // One-shot print runs (`gjc -p`, auto-print) never display provider usage, so
2347
2595
  // credential selection must not probe usage endpoints from every short-lived
2348
2596
  // process; it reuses reports that long-lived hosts already cached (#5939).
@@ -2479,12 +2727,35 @@ export async function runRootCommand(
2479
2727
  parsedArgs,
2480
2728
  cwd,
2481
2729
  settingsInstance,
2730
+ sessionOwnerSurface(),
2731
+ isInteractive
2732
+ ? {
2733
+ interactive: true,
2734
+ notice: message => notifs.push({ kind: "warn", message }),
2735
+ ...(hasResumePickerTerminal()
2736
+ ? {
2737
+ held: {
2738
+ choose: promptHeldSession,
2739
+ forked: (message: string) => notifs.push({ kind: "info", message }),
2740
+ // Before the TUI starts: a line on the terminal, above the warning.
2741
+ waiting: () => process.stderr.write(`${SESSION_HOST_WAITING_MESSAGE}\n`),
2742
+ },
2743
+ }
2744
+ : {}),
2745
+ }
2746
+ : STDERR_STARTUP_NOTICES,
2482
2747
  );
2483
2748
  } catch (error) {
2484
- const message = operatorFacingSessionOpenMessage(error);
2485
- if (!message) throw error;
2486
- process.stderr.write(`${message}\n`);
2487
- if (!deps.suppressProcessExit) process.exitCode = 1;
2749
+ // Cancel in the held-session warning exits 0, through the same cleanup, printing nothing.
2750
+ if (!(error instanceof SessionResumeCancelledError)) {
2751
+ const message = operatorFacingSessionOpenMessage(error, {
2752
+ print: !isInteractive,
2753
+ fork: sessionHeldForkSourceFor(parsedArgs, cwd),
2754
+ });
2755
+ if (!message) throw error;
2756
+ process.stderr.write(`${message}\n`);
2757
+ if (!deps.suppressProcessExit) process.exitCode = 1;
2758
+ }
2488
2759
  authStorage.close();
2489
2760
  stopThemeWatcher();
2490
2761
  await postmortem.cleanup();