@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
@@ -817,6 +817,30 @@ const SESSION_INDEX_LOCK_OPTIONS = {
817
817
  const SESSION_INDEX_STARTUP_LOCK_WAIT_MS =
818
818
  FILE_LOCK_ORPHAN_TRANSITION_ADOPTION_AGE_MS + SESSION_INDEX_LOCK_OPTIONS.retryDelayMs * 2;
819
819
 
820
+ /**
821
+ * Appends allowed for one direct-session registration, or its withdrawal, before giving up.
822
+ * `SessionIndex.append` takes the shared index lock independently per append, so a peer holding
823
+ * it is a transient failure.
824
+ */
825
+ export const DIRECT_SESSION_REGISTRATION_ATTEMPTS = 3;
826
+
827
+ /**
828
+ * An index append that failed on lock contention, which a short retry heals. A refused lock
829
+ * release is an identity verdict, not contention, and is never retried.
830
+ */
831
+ export function isTransientSessionIndexLockError(error: unknown): boolean {
832
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
833
+ return (
834
+ code === "sharing_violation" ||
835
+ code === "access_denied" ||
836
+ code === "EBUSY" ||
837
+ code === "EPERM" ||
838
+ code === "EACCES" ||
839
+ code === "ENOTEMPTY" ||
840
+ code === "removal_record_busy"
841
+ );
842
+ }
843
+
820
844
  /** Bound ordinary bootstrap waits; authorized doctor successors may use the full prepared window. */
821
845
  export function sessionIndexStartupLockOptions(
822
846
  deadline: number,
@@ -476,6 +476,7 @@ export type LifecycleErrorReason =
476
476
  | "dependency_preparation_timeout"
477
477
  | "close_refused"
478
478
  | "not_found"
479
+ | "live_session"
479
480
  | "terminal_uncertain"
480
481
  | "unsupported_platform";
481
482
 
@@ -337,6 +337,10 @@ export function formatLifecycleOutcome(r: SessionLifecycleResponse, verb?: Lifec
337
337
  return "\u26a0\ufe0f Close refused: that session is not GJC-managed or did not match.";
338
338
  case "not_found":
339
339
  return "\u2753 No matching session was found.";
340
+ case "live_session":
341
+ // Resume of a session another process holds without an SDK endpoint yet; the broker's
342
+ // path-free message names that process.
343
+ return `\u23f3 ${r.message}`;
340
344
  case "unsupported_platform":
341
345
  return "Remote session lifecycle is unavailable on this psmux host because GJC cannot prove immutable session identity. No lifecycle action was performed. Use a local GJC terminal with a supported tmux provider.";
342
346
  case "terminal_uncertain":
@@ -321,6 +321,14 @@ export function lifecyclePublicFailure(outcome: Extract<SessionLifecycleResult,
321
321
  diagnostic = "lifecycle_legacy_history_ambiguous";
322
322
  } else if (LIFECYCLE_INPUT_REFUSAL_CODES.has(outcome.error.code)) {
323
323
  diagnostic = "lifecycle_input_refused";
324
+ } else if (
325
+ outcome.operation === "session.resume" &&
326
+ outcome.error.code === "live_session" &&
327
+ outcome.error.holder !== undefined
328
+ ) {
329
+ // Only the single-owner refusal names a holder; a live session whose endpoint authority is
330
+ // unavailable is a different `live_session` and keeps no diagnostic.
331
+ diagnostic = "lifecycle_session_held";
324
332
  }
325
333
  const diagnostics: readonly PublicCommandDiagnosticCode[] | undefined =
326
334
  diagnostic === undefined ? undefined : [diagnostic];
@@ -4,6 +4,11 @@ import {
4
4
  parseDefaultModelSelectionRecovery,
5
5
  } from "../../../session/default-model-selection";
6
6
  import { findOperatorMessage } from "../../../session/operator-error-message";
7
+ import {
8
+ SessionHeldError,
9
+ type SessionOwnerHolderSummary,
10
+ sessionOwnerHolderSummary,
11
+ } from "../../../session/session-owner-holder";
7
12
  import { MODEL_NOT_SELECTED_CODE, MODEL_NOT_SELECTED_PUBLIC_MESSAGE } from "../../../setup/model-onboarding-guidance";
8
13
  import { validateRequiredPromptText } from "../../protocol/adapter-validation";
9
14
  import { isSecureLocalOperation } from "../../protocol/client-control-contracts";
@@ -41,6 +46,8 @@ export interface ControlError {
41
46
  message: string;
42
47
  currentRevision?: string;
43
48
  details?: ControlValue;
49
+ /** The process that holds the session, on a `live_session` refusal (as the broker reports it). */
50
+ holder?: SessionOwnerHolderSummary;
44
51
  }
45
52
 
46
53
  export interface ControlResponse {
@@ -475,6 +482,17 @@ function errorResponse(id: string, row: Operation, error: unknown): ControlRespo
475
482
  ? ({ handoffDocument: candidate.handoffDocument } as ControlValue)
476
483
  : undefined;
477
484
  if (error instanceof BusyError) return failure(id, "busy", message, undefined, details);
485
+ // Under enforce a turn (or a later write) on a session another process now holds is refused
486
+ // with `SessionHeldError`. Remote clients get the broker's `live_session` outcome for a held
487
+ // session, with the same holder summary, not an opaque `internal`.
488
+ if (error instanceof SessionHeldError) {
489
+ const holder = sessionOwnerHolderSummary(error.holder);
490
+ return {
491
+ id,
492
+ ok: false,
493
+ error: { code: "live_session", message: error.operatorMessage, ...(holder ? { holder } : {}) },
494
+ };
495
+ }
478
496
  if (code === "default_model_selection_recovery" && row.errorCodes.includes(code)) {
479
497
  const recovery = parseDefaultModelSelectionRecovery(candidate.recovery) ?? {
480
498
  message: DEFAULT_MODEL_SELECTION_RECOVERY_MESSAGE,
@@ -11,6 +11,7 @@ import { redactBrokerRuntimeCapabilities, redactObservedRequestContent } from ".
11
11
  import { type EventFrame, type EventReplayGap, SessionEventStream } from "./events";
12
12
  import { isAutoroutingInactive } from "./internal-autorouting-state";
13
13
  import { RESPONSE_CEILING_BYTES } from "./query/handlers";
14
+ import { awaitHostRegistrationTestHold } from "./registration-test-hold";
14
15
  import { type ProviderLease, ReverseLeaseError, ReverseLeaseRuntime } from "./reverse-leases";
15
16
  import type { BrokerIndexWriter, HostEndpointAdapters, SdkFrame } from "./types";
16
17
 
@@ -607,6 +608,10 @@ export class SessionSdkHost {
607
608
  }
608
609
 
609
610
  async registerWithBroker(writer: BrokerIndexWriter): Promise<void> {
611
+ // Test-only and inert (nothing awaited) unless the operator's environment sets it. A host
612
+ // stopped during the hold has `#started` false, so it publishes nothing below.
613
+ const testHold = awaitHostRegistrationTestHold(this.#options.sessionId);
614
+ if (testHold) await testHold;
610
615
  this.#registration = { writer, generation: this.events.generation };
611
616
  if (this.#started) await this.#publishRegistration(writer);
612
617
  if (this.#started)
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Test seam for the single-owner flow tests (design §13 H3): hold a session host's broker
3
+ * registration while it already holds the session claim but has no endpoint in the index.
4
+ */
5
+ import * as fs from "node:fs/promises";
6
+ import * as path from "node:path";
7
+ import { startupProjectEnvSnapshot } from "@gajae-code/utils/env";
8
+ import { projectEnvSnapshot } from "@gajae-code/utils/env-file";
9
+ import { trustedCoordinatorEnv } from "../../gjc-runtime/sidecar-bootstrap-env";
10
+
11
+ const HOST_REGISTRATION_HOLD_DIR_ENV = "GJC_SDK_TEST_HOST_REGISTRATION_HOLD_DIR";
12
+ const HOST_REGISTRATION_HOLD_MAX_MS = 60_000;
13
+
14
+ /**
15
+ * The hold directory from the operator's environment only: a value the project dotenv supplied, in
16
+ * the current directory or in the one this process started in, is ignored and removed from this
17
+ * process's environment, so no child inherits it. An unset variable costs no read.
18
+ */
19
+ function trustedHostRegistrationHoldDirectory(): string | undefined {
20
+ if (!process.env[HOST_REGISTRATION_HOLD_DIR_ENV]) return undefined;
21
+ let accepted: string | undefined;
22
+ for (const snapshot of [projectEnvSnapshot(process.cwd()), startupProjectEnvSnapshot()]) {
23
+ accepted = trustedCoordinatorEnv(HOST_REGISTRATION_HOLD_DIR_ENV, process.env, snapshot);
24
+ if (accepted === undefined) {
25
+ delete process.env[HOST_REGISTRATION_HOLD_DIR_ENV];
26
+ return undefined;
27
+ }
28
+ }
29
+ return accepted;
30
+ }
31
+
32
+ /**
33
+ * While `<dir>/<sessionId>.hold` exists, defer this host's broker registration (at most 60 s).
34
+ * `SessionSdkHost.registerWithBroker` calls it, so it holds an interactive TUI and a broker-launched
35
+ * host alike: both register through that method. `undefined`, with nothing awaited, when the seam
36
+ * is not set, so registration keeps its ordering outside the tests that use it.
37
+ */
38
+ export function awaitHostRegistrationTestHold(sessionId: string): Promise<void> | undefined {
39
+ const directory = trustedHostRegistrationHoldDirectory();
40
+ return directory ? waitWhileHeld(path.join(directory, `${sessionId}.hold`)) : undefined;
41
+ }
42
+
43
+ async function waitWhileHeld(hold: string): Promise<void> {
44
+ const held = (): Promise<boolean> =>
45
+ fs.stat(hold).then(
46
+ () => true,
47
+ () => false,
48
+ );
49
+ const deadline = Date.now() + HOST_REGISTRATION_HOLD_MAX_MS;
50
+ while (Date.now() < deadline && (await held())) await Bun.sleep(50);
51
+ }
@@ -40,6 +40,7 @@ import type {
40
40
  ClientBridgePermissionToolCall,
41
41
  } from "../../session/client-bridge";
42
42
  import { SessionManager } from "../../session/session-manager";
43
+ import { SessionHeldError } from "../../session/session-owner-holder";
43
44
  import {
44
45
  registerOwnedRegistration,
45
46
  resetTerminalAbortRegistriesForTests,
@@ -10574,6 +10575,47 @@ describe("post-acceptance invocation terminalization", () => {
10574
10575
  }
10575
10576
  });
10576
10577
 
10578
+ test("a turn refused because another process holds the session answers live_session with the holder", async () => {
10579
+ const cwd = await mkdtemp(path.join(os.tmpdir(), "gjc-terminalize-held-"));
10580
+ try {
10581
+ const refusal = new SessionHeldError("held-session-1", {
10582
+ surface: "terminal",
10583
+ pid: 4242,
10584
+ host: "build-box",
10585
+ gjcVersion: "0.0.0",
10586
+ });
10587
+ const harness = await invocationHarness("terminalize-held", cwd, {
10588
+ sendUserMessage: async () => {
10589
+ throw refusal;
10590
+ },
10591
+ });
10592
+ // The response a remote client (ACP, `gjc sdk`) reads: the broker's held-session code and
10593
+ // holder summary (surface and pid only), never `internal`.
10594
+ expect(await harness.control("turn.prompt", { text: "hello", clientRef: "held-ref" })).toMatchObject({
10595
+ ok: false,
10596
+ error: {
10597
+ code: "live_session",
10598
+ message: refusal.operatorMessage,
10599
+ holder: { surface: "terminal", pid: 4242 },
10600
+ },
10601
+ });
10602
+ const rejected = await harness.control("turn.prompt", { text: "again", clientRef: "held-ref-2" });
10603
+ expect(Object.keys(rejected.error as object).sort()).toEqual(["code", "holder", "message"]);
10604
+ expect((rejected.error as { holder?: object }).holder).toEqual({ surface: "terminal", pid: 4242 });
10605
+ // The submission status agrees with the response.
10606
+ const status = await harness.query("turn.prompt_status", { clientRef: "held-ref" });
10607
+ expect(status.result as Record<string, unknown>).toMatchObject({
10608
+ status: "failed",
10609
+ receiptState: "missing",
10610
+ error: { code: "live_session" },
10611
+ });
10612
+ await harness.stop();
10613
+ } finally {
10614
+ await Bun.sleep(50);
10615
+ await rm(cwd, { recursive: true, force: true });
10616
+ }
10617
+ });
10618
+
10577
10619
  test("a later provider error never changes or re-opens an already terminal prompt", async () => {
10578
10620
  const cwd = await mkdtemp(path.join(os.tmpdir(), "gjc-terminalize-once-"));
10579
10621
  try {
package/src/sdk/index.ts CHANGED
@@ -33,6 +33,16 @@ export type {
33
33
  TrackedSendUserMessageOptions,
34
34
  } from "../session/agent-session";
35
35
  export { getSessionMessageEntryId } from "../session/session-manager";
36
+ // Session ownership (design §2.6, §3.3): who holds a session for writing, and the refusal enforce raises.
37
+ export {
38
+ probeSessionOwners,
39
+ SessionHeldError,
40
+ type SessionOwnerBaseSurface,
41
+ type SessionOwnerHolder,
42
+ type SessionOwnerProbe,
43
+ type SessionOwnerSurface,
44
+ type SessionOwnerUnknownReason,
45
+ } from "../session/session-ownership";
36
46
  export { ACP_BUILTIN_SLASH_COMMANDS, executeAcpBuiltinSlashCommand } from "../slash-commands/acp-builtins";
37
47
  export type { SlashCommandResult, SlashCommandRuntime } from "../slash-commands/types";
38
48
  export * from "./activity-controls";
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  import { isRecord } from "@gajae-code/utils";
4
+ import { type SessionOwnerHolderSummary, sessionOwnerHolderSummary } from "../../session/session-owner-holder";
4
5
  import {
5
6
  resolvedScopeV1,
6
7
  resolveScopeRequest,
@@ -365,6 +366,8 @@ export interface SessionLifecycleLookupFailure {
365
366
  export interface SessionLifecycleError {
366
367
  readonly code: string;
367
368
  readonly message: string;
369
+ /** The process that holds the session, when a resume was refused under `enforce` (`live_session`). */
370
+ readonly holder?: SessionOwnerHolderSummary;
368
371
  }
369
372
 
370
373
  export type SessionCreateFailure = {
@@ -1076,6 +1079,20 @@ function brokerErrorFromThrown(value: unknown): { code: string; message: string;
1076
1079
  return { code, message, ...(requestSent === undefined ? {} : { requestSent }) };
1077
1080
  }
1078
1081
 
1082
+ /** The holder a broker refusal names, from a response or a thrown client error, checked field by field. */
1083
+ function brokerErrorHolder(value: unknown): SessionOwnerHolderSummary | undefined {
1084
+ if (!isRecord(value)) return undefined;
1085
+ const error = isRecord(value.error) ? value.error : isRecord(value.details) ? value.details : undefined;
1086
+ return sessionOwnerHolderSummary(error?.holder);
1087
+ }
1088
+
1089
+ function withHolder<T extends { readonly error: SessionLifecycleError }>(
1090
+ outcome: T,
1091
+ holder: SessionOwnerHolderSummary | undefined,
1092
+ ): T {
1093
+ return holder ? { ...outcome, error: { ...outcome.error, holder } } : outcome;
1094
+ }
1095
+
1079
1096
  function unavailableScopedList(scope: SdkSearchResultV1["scope"]): SessionListFailure {
1080
1097
  return {
1081
1098
  ok: false,
@@ -1391,22 +1408,28 @@ export class SessionLifecycleService {
1391
1408
  } catch (thrown) {
1392
1409
  const error = brokerError(thrown) ?? brokerErrorFromThrown(thrown);
1393
1410
  return error
1394
- ? failure(
1395
- operation,
1396
- certaintyForThrownError(error),
1397
- operation === "session.revise" ? revisionErrorCode(error.code, normalizedTarget) : error.code,
1398
- operation === "session.revise" ? "lifecycle broker revision request failed" : error.message,
1411
+ ? withHolder(
1412
+ failure(
1413
+ operation,
1414
+ certaintyForThrownError(error),
1415
+ operation === "session.revise" ? revisionErrorCode(error.code, normalizedTarget) : error.code,
1416
+ operation === "session.revise" ? "lifecycle broker revision request failed" : error.message,
1417
+ ),
1418
+ brokerErrorHolder(thrown),
1399
1419
  )
1400
1420
  : failure(operation, "retryable", "unavailable", "lifecycle broker request was unavailable");
1401
1421
  }
1402
1422
 
1403
1423
  const error = brokerError(response);
1404
1424
  if (error)
1405
- return failure(
1406
- operation,
1407
- certaintyForBrokerCode(error.code),
1408
- operation === "session.revise" ? revisionErrorCode(error.code, normalizedTarget) : error.code,
1409
- operation === "session.revise" ? "lifecycle broker revision request failed" : error.message,
1425
+ return withHolder(
1426
+ failure(
1427
+ operation,
1428
+ certaintyForBrokerCode(error.code),
1429
+ operation === "session.revise" ? revisionErrorCode(error.code, normalizedTarget) : error.code,
1430
+ operation === "session.revise" ? "lifecycle broker revision request failed" : error.message,
1431
+ ),
1432
+ brokerErrorHolder(response),
1410
1433
  );
1411
1434
  if (operation === "session.revise") {
1412
1435
  const parsed = revisionResult(brokerSuccess(response), normalizedTarget);
@@ -302,6 +302,10 @@ export function sanitizePromptFailure(error: unknown): { code: string; message:
302
302
  } catch {
303
303
  // Untrusted error records may expose throwing accessors.
304
304
  }
305
+ // A turn refused because another process holds the session (`SessionHeldError`, code
306
+ // `session_held`) is published as the broker's `live_session`, the code every remote client
307
+ // already reads for a held session, so a prompt record never carries a second spelling of it.
308
+ if (rawCode === "session_held") return { code: "live_session", message: "Prompt submission failed." };
305
309
  const code = rawCode.length <= PROMPT_FAILURE_CODE_MAX && /^[A-Za-z0-9._-]+$/.test(rawCode) ? rawCode : "internal";
306
310
  return { code, message: "Prompt submission failed." };
307
311
  }
@@ -379,15 +379,20 @@ function controlErrors(id: string): string[] {
379
379
  // C01/C05 submit a prompt and therefore run the prompt preflight, which
380
380
  // refuses a session with no selected model before admission. The code is
381
381
  // appended: ACP machine-only mapping reads errorCodes[0].
382
+ // Every turn-starting operation (C01, C03, C05, C09) also refuses, under
383
+ // session ownership `enforce`, a turn on a session another process now
384
+ // holds, with the broker's `live_session` and its holder; appended too.
382
385
  C01: [
383
386
  "client_ref_conflict",
384
387
  "reconciliation_capacity",
385
388
  "reconciliation_persist_failed",
386
389
  "model_not_selected",
387
390
  "image_upload_unavailable",
391
+ "live_session",
388
392
  ],
389
393
  C02: ["turn_not_active", "client_ref_conflict", "reconciliation_capacity", "reconciliation_persist_failed"],
390
- C09: ["client_ref_conflict", "reconciliation_capacity", "reconciliation_persist_failed"],
394
+ C03: ["invalid_request", "busy", "live_session"],
395
+ C09: ["client_ref_conflict", "reconciliation_capacity", "reconciliation_persist_failed", "live_session"],
391
396
  C06: ["stale_request"],
392
397
  C07: ["action_claimed", "terminal_uncertain"],
393
398
  C05: [
@@ -398,6 +403,7 @@ function controlErrors(id: string): string[] {
398
403
  "client_ref_conflict",
399
404
  "reconciliation_capacity",
400
405
  "reconciliation_persist_failed",
406
+ "live_session",
401
407
  ],
402
408
  C08: ["action_claimed", "terminal_uncertain"],
403
409
  C13: ["invalid_request", "busy", "default_model_selection_recovery"],
@@ -9,22 +9,30 @@ export type SessionApiKeyModel = {
9
9
  baseUrl?: string;
10
10
  };
11
11
 
12
+ /** A resolved key plus the stored credential row that supplied it, when any. */
13
+ export type SessionApiKeyLookup = {
14
+ apiKey: string | undefined;
15
+ credentialRowId: number | undefined;
16
+ };
17
+
12
18
  export type SessionApiKeyRegistry = {
13
- getApiKey(
19
+ getApiKeyWithCredentialRowId(
14
20
  model: SessionApiKeyModel,
15
21
  sessionId?: string,
16
22
  options?: { signal?: AbortSignal },
17
- ): Promise<string | undefined>;
18
- getApiKeyForProvider(
23
+ ): Promise<SessionApiKeyLookup>;
24
+ getApiKeyForProviderWithCredentialRowId(
19
25
  provider: string,
20
26
  sessionId?: string,
21
27
  baseUrl?: string,
22
28
  options?: { signal?: AbortSignal },
23
- ): Promise<string | undefined>;
29
+ ): Promise<SessionApiKeyLookup>;
24
30
  };
25
31
 
26
32
  export type SessionApiKeyResolution = {
27
33
  apiKey: string;
34
+ /** Stored credential row behind `apiKey`; undefined for runtime, config, env, or fallback keys. */
35
+ credentialRowId: number | undefined;
28
36
  credentialSessionId: string | undefined;
29
37
  };
30
38
 
@@ -53,20 +61,25 @@ async function lookupOnce(
53
61
  sessionId: string | undefined,
54
62
  model: SessionApiKeyModel | undefined,
55
63
  signal: AbortSignal | undefined,
56
- ): Promise<string | undefined> {
64
+ ): Promise<SessionApiKeyLookup> {
57
65
  signal?.throwIfAborted();
58
66
  const matchingModel = model?.provider === provider ? model : undefined;
59
67
  const options = signal ? { signal } : undefined;
60
- let key: string | undefined;
68
+ let lookup: SessionApiKeyLookup | undefined;
61
69
  if (matchingModel) {
62
- key = await registry.getApiKey(matchingModel, sessionId, options);
70
+ lookup = await registry.getApiKeyWithCredentialRowId(matchingModel, sessionId, options);
63
71
  signal?.throwIfAborted();
64
72
  }
65
- if (!key) {
66
- key = await registry.getApiKeyForProvider(provider, sessionId, matchingModel?.baseUrl, options);
73
+ if (!lookup?.apiKey) {
74
+ lookup = await registry.getApiKeyForProviderWithCredentialRowId(
75
+ provider,
76
+ sessionId,
77
+ matchingModel?.baseUrl,
78
+ options,
79
+ );
67
80
  signal?.throwIfAborted();
68
81
  }
69
- return key;
82
+ return lookup;
70
83
  }
71
84
 
72
85
  export async function lookupSessionApiKey(
@@ -77,18 +90,20 @@ export async function lookupSessionApiKey(
77
90
  allowUnscopedRetry = true,
78
91
  signal?: AbortSignal,
79
92
  ): Promise<SessionApiKeyResolution> {
80
- let key = await lookupOnce(registry, provider, sessionId, model, signal);
93
+ let lookup = await lookupOnce(registry, provider, sessionId, model, signal);
81
94
  // Architect children inherit the parent SID. Direct `-p --no-session` does
82
95
  // not. Scoped miss then global/broker hit is the remaining 0-token death
83
96
  // after #5105 (jsonl: Agent run failed / output 0).
84
- if (!key && sessionId && allowUnscopedRetry) {
85
- key = await lookupOnce(registry, provider, undefined, model, signal);
86
- if (key) return { apiKey: key, credentialSessionId: undefined };
97
+ if (!lookup.apiKey && sessionId && allowUnscopedRetry) {
98
+ lookup = await lookupOnce(registry, provider, undefined, model, signal);
99
+ if (lookup.apiKey) {
100
+ return { apiKey: lookup.apiKey, credentialRowId: lookup.credentialRowId, credentialSessionId: undefined };
101
+ }
87
102
  }
88
- if (!key) {
103
+ if (!lookup.apiKey) {
89
104
  throw Object.assign(new Error(`No API key found for provider "${provider}"`), {
90
105
  code: "provider_unavailable",
91
106
  });
92
107
  }
93
- return { apiKey: key, credentialSessionId: sessionId };
108
+ return { apiKey: lookup.apiKey, credentialRowId: lookup.credentialRowId, credentialSessionId: sessionId };
94
109
  }
@@ -40,6 +40,16 @@ export interface EntryPatchRecord<TMessage = unknown> {
40
40
 
41
41
  export type StoredSessionPatchRecord = HeaderPatchRecord | EntryPatchRecord;
42
42
 
43
+ /**
44
+ * True when a directory entry name can be a session transcript. Transcripts are
45
+ * named `<timestamp>_<sessionId>.jsonl`; a dot-prefixed `.jsonl` file is an
46
+ * in-flight staging copy (such as an unpromoted memory-guard restore) and never
47
+ * a session of its own, even when a crash leaves it behind.
48
+ */
49
+ export function isSessionTranscriptFileName(name: string): boolean {
50
+ return name.endsWith(".jsonl") && !name.startsWith(".");
51
+ }
52
+
43
53
  export function isSupportedSessionVersion(version: unknown): boolean {
44
54
  return (
45
55
  version === undefined ||
@@ -5,6 +5,7 @@ import * as path from "node:path";
5
5
  import type * as natives from "@gajae-code/natives";
6
6
  import type { NativeDirectoryTreeSnapshot } from "@gajae-code/natives";
7
7
  import { hasFsCode } from "@gajae-code/utils";
8
+ import { isSessionTranscriptFileName } from "./format";
8
9
  import type { ManagedFileSnapshot } from "./inspection";
9
10
  import {
10
11
  captureManagedFileNoFollow,
@@ -655,7 +656,7 @@ function listDirectoryCandidates(
655
656
  if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) throw new Error("unsafe directory");
656
657
  return fs
657
658
  .readdirSync(directory, { withFileTypes: true })
658
- .filter(entry => entry.name.endsWith(".jsonl"))
659
+ .filter(entry => isSessionTranscriptFileName(entry.name))
659
660
  .map(entry => {
660
661
  const filePath = path.join(directory, entry.name);
661
662
  const preflight = preflightCandidate(filePath, scope);