@gajae-code/coding-agent 0.22.1 → 0.22.2

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 (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/cli/doctor/probe-types.d.ts +1 -1
  3. package/dist/types/cli/doctor/session-owners-probe.d.ts +7 -0
  4. package/dist/types/cli/doctor/session-owners.d.ts +16 -0
  5. package/dist/types/cli/github-release.d.ts +16 -0
  6. package/dist/types/cli/session-owners-cli.d.ts +13 -0
  7. package/dist/types/cli/update-cli.d.ts +2 -0
  8. package/dist/types/commands/sdk.d.ts +23 -14
  9. package/dist/types/config/settings-schema.d.ts +6 -0
  10. package/dist/types/exec/bash-shell-guardian.d.ts +61 -0
  11. package/dist/types/export/html/html-export-destination.d.ts +16 -0
  12. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
  13. package/dist/types/sdk/host/control/runtime-gate.d.ts +7 -0
  14. package/dist/types/session/internal/graph-successor-proof.d.ts +33 -0
  15. package/dist/types/session/internal/managed-session-storage.d.ts +6 -1
  16. package/dist/types/session/internal/session-claim-set.d.ts +69 -0
  17. package/dist/types/session/operator-error-message.d.ts +29 -0
  18. package/dist/types/session/session-manager.d.ts +57 -3
  19. package/dist/types/session/session-owners-layout.d.ts +24 -0
  20. package/dist/types/session/session-ownership-mode.d.ts +45 -0
  21. package/dist/types/session/session-ownership.d.ts +195 -0
  22. package/dist/types/session/session-storage.d.ts +36 -0
  23. package/dist/types/slash-commands/helpers/parse.d.ts +1 -0
  24. package/package.json +12 -8
  25. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  26. package/src/cli/doctor/probe-types.ts +1 -1
  27. package/src/cli/doctor/probe.ts +9 -5
  28. package/src/cli/doctor/runner.ts +6 -1
  29. package/src/cli/doctor/session-owners-probe.ts +69 -0
  30. package/src/cli/doctor/session-owners.ts +106 -0
  31. package/src/cli/github-release.ts +100 -0
  32. package/src/cli/session-owners-cli.ts +118 -0
  33. package/src/cli/stats-cli.ts +19 -1
  34. package/src/cli/update-cli.ts +50 -3
  35. package/src/cli-ordinary.ts +1 -1
  36. package/src/commands/sdk.ts +36 -33
  37. package/src/commands/session.ts +10 -2
  38. package/src/config/settings-schema.ts +18 -0
  39. package/src/config/settings.ts +127 -13
  40. package/src/exec/bash-shell-guardian.ts +181 -12
  41. package/src/exec/isolated-shell.ts +13 -3
  42. package/src/export/html/html-export-destination.ts +47 -2
  43. package/src/export/html/index.ts +161 -13
  44. package/src/internal-urls/docs-index.generated.ts +4 -4
  45. package/src/main.ts +20 -14
  46. package/src/modes/acp/acp-agent.ts +6 -0
  47. package/src/modes/action-registry.ts +4 -1
  48. package/src/modes/controllers/command-controller.ts +12 -5
  49. package/src/modes/controllers/extension-ui-controller.ts +6 -22
  50. package/src/modes/controllers/input-controller.ts +3 -2
  51. package/src/modes/controllers/selector-controller.ts +14 -1
  52. package/src/modes/interactive-mode.ts +6 -3
  53. package/src/modes/print-mode.ts +2 -1
  54. package/src/modes/runtime-init.ts +2 -17
  55. package/src/modes/utils/ui-helpers.ts +5 -3
  56. package/src/sdk/bus/index.ts +22 -0
  57. package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
  58. package/src/sdk/host/control/dispatch.ts +5 -1
  59. package/src/sdk/host/control/runtime-gate.ts +22 -0
  60. package/src/sdk/host/host.ts +4 -1
  61. package/src/sdk/session-readonly/metadata.ts +24 -18
  62. package/src/sdk/session.ts +2 -0
  63. package/src/session/agent-session.ts +101 -22
  64. package/src/session/internal/graph-successor-proof.ts +108 -0
  65. package/src/session/internal/managed-session-storage.ts +8 -1
  66. package/src/session/internal/session-claim-set.ts +242 -0
  67. package/src/session/operator-error-message.ts +79 -0
  68. package/src/session/session-manager.ts +524 -108
  69. package/src/session/session-owners-layout.ts +52 -0
  70. package/src/session/session-ownership-mode.ts +176 -0
  71. package/src/session/session-ownership.ts +851 -0
  72. package/src/session/session-storage.ts +60 -16
  73. package/src/setup/credential-import.ts +2 -1
  74. package/src/slash-commands/builtin-registry.ts +2 -0
  75. package/src/slash-commands/helpers/parse.ts +3 -1
@@ -41,6 +41,7 @@ import {
41
41
  parseNotificationSettingsSnapshot,
42
42
  } from "../sdk/bus/config";
43
43
  import { AgentStorage } from "../session/agent-storage";
44
+ import { setSessionOwnershipSettingSource } from "../session/session-ownership-mode";
44
45
  import { type EditMode, type EditVariantMatch, normalizeEditMode } from "../utils/edit-mode";
45
46
  import {
46
47
  type AtomicYamlConfigTransaction,
@@ -527,6 +528,16 @@ const GLOBAL_ONLY_SETTINGS = new Set<SettingPath>([
527
528
  // Operator consent for the plan-mode write guard. A project file or runtime override must not flip it.
528
529
  "plan.enabled",
529
530
  ]);
531
+
532
+ /**
533
+ * Session ownership settings (`session.ownership.*`) are global-only as a namespace, so a sub-flag
534
+ * added later is covered without a new entry here. A project or runtime layer must not lower
535
+ * another process's protection.
536
+ */
537
+ const SESSION_OWNERSHIP_SETTINGS_NAMESPACE = "session.ownership";
538
+ function isSessionOwnershipSettingsPath(path: string): boolean {
539
+ return path === SESSION_OWNERSHIP_SETTINGS_NAMESPACE || path.startsWith(`${SESSION_OWNERSHIP_SETTINGS_NAMESPACE}.`);
540
+ }
530
541
  /**
531
542
  * Project-layer values ignored at merge.
532
543
  * User config and runtime overrides still apply.
@@ -539,6 +550,47 @@ const PROJECT_LAYER_DENIED_SETTINGS = new Set<SettingPath>([
539
550
  // Operator extension disable list. A project file must not clear or replace it.
540
551
  "disabledExtensions",
541
552
  ]);
553
+ /** Global values the project layer must not erase: global-only, project-denied and credential-selection paths. */
554
+ const PROJECT_PROTECTED_SETTING_SEGMENTS: readonly string[][] = [
555
+ ...GLOBAL_ONLY_SETTINGS,
556
+ SESSION_OWNERSHIP_SETTINGS_NAMESPACE,
557
+ ...PROJECT_LAYER_DENIED_SETTINGS,
558
+ ...[...GLOBAL_ONLY_AUTH_SETTING_KEYS].map(key => `auth.${key}`),
559
+ ].map(settingPath => settingPath.split("."));
560
+ /** Global values the runtime layer must not erase. */
561
+ const RUNTIME_PROTECTED_SETTING_SEGMENTS: readonly string[][] = [
562
+ ...GLOBAL_ONLY_SETTINGS,
563
+ SESSION_OWNERSHIP_SETTINGS_NAMESPACE,
564
+ ].map(settingPath => settingPath.split("."));
565
+
566
+ /**
567
+ * Put back protected global values that a merged layer erased by replacing an ancestor with a
568
+ * non-object (null, a scalar or an array). Deleting the protected leaf before the merge covers object
569
+ * ancestors only. Every other key under that ancestor keeps the layer's replacement, as before.
570
+ */
571
+ function restoreProtectedGlobalValues(
572
+ merged: RawSettings,
573
+ global: RawSettings,
574
+ protectedPaths: readonly string[][],
575
+ ): void {
576
+ for (const segments of protectedPaths) {
577
+ const globalValue = getByPath(global, segments);
578
+ if (globalValue === undefined || getByPath(merged, segments) !== undefined) continue;
579
+ let current = merged;
580
+ for (const segment of segments.slice(0, -1)) {
581
+ // Copy on write: merged objects can share nested objects with the global layer.
582
+ const next: RawSettings = { ...rawSettingsRecord(current[segment]) };
583
+ Object.defineProperty(current, segment, { configurable: true, enumerable: true, value: next, writable: true });
584
+ current = next;
585
+ }
586
+ Object.defineProperty(current, segments[segments.length - 1]!, {
587
+ configurable: true,
588
+ enumerable: true,
589
+ value: structuredClone(globalValue),
590
+ writable: true,
591
+ });
592
+ }
593
+ }
542
594
  const LEGACY_THEME_NAME_REPLACEMENTS = {
543
595
  dark: "red-claw",
544
596
  light: "blue-crab",
@@ -942,7 +994,10 @@ export class Settings implements NotificationSettingsReader {
942
994
  previous = effective;
943
995
  }
944
996
  const allowedLayers: SettingsLayer[] = ["global"];
945
- const globalOnly = GLOBAL_ONLY_SETTINGS.has(settingPath) || isNotificationSettingsPath(settingPath);
997
+ const globalOnly =
998
+ GLOBAL_ONLY_SETTINGS.has(settingPath) ||
999
+ isNotificationSettingsPath(settingPath) ||
1000
+ isSessionOwnershipSettingsPath(settingPath);
946
1001
  if (!globalOnly) {
947
1002
  if (
948
1003
  !PROJECT_LAYER_DENIED_SETTINGS.has(settingPath) &&
@@ -2421,6 +2476,12 @@ export class Settings implements NotificationSettingsReader {
2421
2476
  bypassCache,
2422
2477
  });
2423
2478
  let merged: RawSettings = {};
2479
+
2480
+ // Log any warnings from settings discovery (parse failures, unreadable files, etc.)
2481
+ for (const warning of result.warnings) {
2482
+ logger.warn(`Settings: ${warning}`, { cwd: this.#cwd });
2483
+ }
2484
+
2424
2485
  for (const item of result.items as SettingsCapabilityItem[]) {
2425
2486
  if (item.level !== "project") continue;
2426
2487
  // Retained project settings.json remains discoverable for non-workflow
@@ -2458,6 +2519,11 @@ export class Settings implements NotificationSettingsReader {
2458
2519
  ) {
2459
2520
  throw error;
2460
2521
  }
2522
+ // Log the error when project settings loading fails (issue #8034)
2523
+ logger.warn(
2524
+ `Settings: project settings discovery failed but layer is tolerated; some project settings may be unavailable`,
2525
+ { error: error instanceof Error ? error.message : String(error), cwd: this.#cwd },
2526
+ );
2461
2527
  return {};
2462
2528
  }
2463
2529
  }
@@ -6326,8 +6392,8 @@ export class Settings implements NotificationSettingsReader {
6326
6392
  }
6327
6393
 
6328
6394
  // task.isolation.enabled (boolean) -> task.isolation.mode (enum)
6329
- const taskObj = raw.task as Record<string, unknown> | undefined;
6330
- const isolationObj = taskObj?.isolation as Record<string, unknown> | undefined;
6395
+ const taskObj = rawSettingsRecord(raw.task);
6396
+ const isolationObj = taskObj ? rawSettingsRecord(taskObj.isolation) : undefined;
6331
6397
  if (isolationObj && "enabled" in isolationObj) {
6332
6398
  if (typeof isolationObj.enabled === "boolean") {
6333
6399
  isolationObj.mode = isolationObj.enabled ? "auto" : "none";
@@ -6352,27 +6418,41 @@ export class Settings implements NotificationSettingsReader {
6352
6418
  }
6353
6419
  }
6354
6420
 
6421
+ // Ensure taskObj (now potentially modified) is updated back to raw
6422
+ if (taskObj) {
6423
+ if (isolationObj) {
6424
+ taskObj.isolation = isolationObj;
6425
+ }
6426
+ // Drop malformed (non-object) task.isolation before merging so it doesn't
6427
+ // mask the global value (issue #8034)
6428
+ if ("isolation" in taskObj && !rawSettingsRecord(taskObj.isolation)) {
6429
+ delete taskObj.isolation;
6430
+ }
6431
+ raw.task = taskObj;
6432
+ }
6433
+
6355
6434
  // edit.mode: removed "atom" variant is now "hashline"
6356
- const editObj = raw.edit as Record<string, unknown> | undefined;
6435
+ const editObj = rawSettingsRecord(raw.edit);
6357
6436
  if (editObj) {
6358
6437
  if (editObj.mode === "atom") {
6359
6438
  editObj.mode = "hashline";
6360
6439
  }
6361
- const modelVariants = editObj.modelVariants as Record<string, unknown> | undefined;
6362
- if (modelVariants && typeof modelVariants === "object" && !Array.isArray(modelVariants)) {
6440
+ const modelVariants = rawSettingsRecord(editObj.modelVariants);
6441
+ if (modelVariants) {
6363
6442
  for (const [pattern, variant] of Object.entries(modelVariants)) {
6364
6443
  if (variant === "atom") {
6365
6444
  modelVariants[pattern] = "hashline";
6366
6445
  }
6367
6446
  }
6368
6447
  }
6448
+ raw.edit = editObj;
6369
6449
  }
6370
6450
  if (raw["edit.mode"] === "atom") {
6371
6451
  raw["edit.mode"] = "hashline";
6372
6452
  }
6373
6453
 
6374
6454
  // statusLine: rename "plan_mode" segment to "mode"
6375
- const statusLineObj = raw.statusLine as Record<string, unknown> | undefined;
6455
+ const statusLineObj = rawSettingsRecord(raw.statusLine);
6376
6456
  if (statusLineObj) {
6377
6457
  for (const key of ["leftSegments", "rightSegments"] as const) {
6378
6458
  const segments = statusLineObj[key];
@@ -6380,22 +6460,23 @@ export class Settings implements NotificationSettingsReader {
6380
6460
  statusLineObj[key] = segments.map(seg => (seg === "plan_mode" ? "mode" : seg));
6381
6461
  }
6382
6462
  }
6383
- const segmentOptions = statusLineObj.segmentOptions as Record<string, unknown> | undefined;
6463
+ const segmentOptions = rawSettingsRecord(statusLineObj.segmentOptions);
6384
6464
  if (segmentOptions && "plan_mode" in segmentOptions && !("mode" in segmentOptions)) {
6385
6465
  segmentOptions.mode = segmentOptions.plan_mode;
6386
6466
  delete segmentOptions.plan_mode;
6387
6467
  }
6468
+ raw.statusLine = statusLineObj;
6388
6469
  }
6389
6470
 
6390
6471
  // Map legacy `memories.enabled` boolean to the explicit `memory.backend`
6391
6472
  // enum if the latter hasn't been set yet. Idempotent: subsequent
6392
6473
  // migrations are no-ops once memory.backend is materialised.
6393
- const memoryBackendObj = raw.memory as Record<string, unknown> | undefined;
6474
+ const memoryBackendObj = rawSettingsRecord(raw.memory);
6394
6475
  const memoryBackendSet = memoryBackendObj && typeof memoryBackendObj.backend === "string";
6395
- const memoriesObj = raw.memories as Record<string, unknown> | undefined;
6476
+ const memoriesObj = rawSettingsRecord(raw.memories);
6396
6477
  if (!memoryBackendSet && memoriesObj && typeof memoriesObj.enabled === "boolean") {
6397
6478
  const next = memoriesObj.enabled ? "local" : "off";
6398
- const memoryRoot = (memoryBackendObj ?? {}) as Record<string, unknown>;
6479
+ const memoryRoot = memoryBackendObj ?? {};
6399
6480
  memoryRoot.backend = next;
6400
6481
  raw.memory = memoryRoot;
6401
6482
  }
@@ -6407,7 +6488,7 @@ export class Settings implements NotificationSettingsReader {
6407
6488
  // - hindsight.agentName was only used as the agent slot in the legacy
6408
6489
  // dynamic tuple; if the user customised it we surface it as the new
6409
6490
  // bankId base when no explicit bankId is set.
6410
- const hindsightObj = raw.hindsight as Record<string, unknown> | undefined;
6491
+ const hindsightObj = rawSettingsRecord(raw.hindsight);
6411
6492
  if (hindsightObj) {
6412
6493
  if ("dynamicBankId" in hindsightObj) {
6413
6494
  if (!("scoping" in hindsightObj) && hindsightObj.dynamicBankId === true) {
@@ -6427,6 +6508,7 @@ export class Settings implements NotificationSettingsReader {
6427
6508
  }
6428
6509
  delete hindsightObj.agentName;
6429
6510
  }
6511
+ raw.hindsight = hindsightObj;
6430
6512
  }
6431
6513
 
6432
6514
  // Migrate legacy providers.image* settings into modelRoles.image.
@@ -6939,6 +7021,8 @@ export class Settings implements NotificationSettingsReader {
6939
7021
  const overrides = structuredClone(overrideLayer);
6940
7022
  // A non-object project clipboard value would replace the user clipboard
6941
7023
  // object. Drop that parent; nested objects still lose only the denied leaves.
7024
+ // The restore after each merge stage protects every leaf below. The searxng guard stays because
7025
+ // dropping its parent also keeps non-global searxng keys; the clipboard guard is now redundant.
6942
7026
  const projectClipboard = project.clipboard;
6943
7027
  if (
6944
7028
  projectClipboard !== undefined &&
@@ -6955,16 +7039,40 @@ export class Settings implements NotificationSettingsReader {
6955
7039
  delete layer.searxng;
6956
7040
  }
6957
7041
  }
7042
+ // A non-object hindsight value would replace the global hindsight object and drop
7043
+ // the global-only hindsight.apiUrl. A non-object compaction value would similarly
7044
+ // replace the compaction object and drop the global-only compaction.remoteEndpoint.
7045
+ // A non-object task.isolation value would mask the global task.isolation object.
7046
+ // Drop malformed parents; nested objects still lose only the global-only child paths.
7047
+ // An explicit null is not malformed: it resets the section's non-protected keys to
7048
+ // their defaults while the merge keeps global-only children.
7049
+ for (const layer of [project, overrides]) {
7050
+ for (const section of ["hindsight", "compaction"] as const) {
7051
+ const value = layer[section];
7052
+ if (value !== undefined && value !== null && (typeof value !== "object" || Array.isArray(value))) {
7053
+ delete layer[section];
7054
+ }
7055
+ }
7056
+ // Drop malformed task.isolation (issue #8034)
7057
+ const taskObj = rawSettingsRecord(layer.task);
7058
+ if (taskObj && "isolation" in taskObj && !rawSettingsRecord(taskObj.isolation)) {
7059
+ delete taskObj.isolation;
7060
+ }
7061
+ }
6958
7062
  for (const settingPath of GLOBAL_ONLY_SETTINGS) {
6959
7063
  const segments = settingPath.split(".");
6960
7064
  deleteByPath(project, segments);
6961
7065
  deleteByPath(overrides, segments);
6962
7066
  }
7067
+ for (const layer of [project, overrides]) deleteByPath(layer, SESSION_OWNERSHIP_SETTINGS_NAMESPACE.split("."));
6963
7068
  for (const settingPath of PROJECT_LAYER_DENIED_SETTINGS) {
6964
7069
  deleteByPath(project, settingPath.split("."));
6965
7070
  }
6966
7071
  const merged = this.#deepMerge(this.#deepMerge({}, global), project);
6967
- return this.#deepMerge(merged, overrides);
7072
+ restoreProtectedGlobalValues(merged, global, PROJECT_PROTECTED_SETTING_SEGMENTS);
7073
+ const result = this.#deepMerge(merged, overrides);
7074
+ restoreProtectedGlobalValues(result, global, RUNTIME_PROTECTED_SETTING_SEGMENTS);
7075
+ return result;
6968
7076
  }
6969
7077
 
6970
7078
  #fireAllHooks(): void {
@@ -7117,6 +7225,12 @@ let globalInstance: Settings | null = null;
7117
7225
  let globalInstancePromise: Promise<Settings> | null = null;
7118
7226
  let globalInitOptions: SettingsOptions | null = null;
7119
7227
 
7228
+ // Session ownership reads its global-only mode from the process settings. Injected, because the
7229
+ // session modules sit below config in the import graph.
7230
+ // The global layer only: a project or runtime value, including a null or scalar `session` parent
7231
+ // that would replace the user's whole `session` object in the merge, never reaches the mode.
7232
+ setSessionOwnershipSettingSource(() => globalInstance?.getGlobal("session.ownership.mode"));
7233
+
7120
7234
  export function isSettingsInitialized(): boolean {
7121
7235
  return globalInstance !== null;
7122
7236
  }
@@ -178,6 +178,12 @@ export type DarwinAncestryTracker = {
178
178
  track(processRef: NativeProcess, uniqueId?: bigint): boolean;
179
179
  trackGuardian(processRef: NativeProcess, uniqueId?: bigint): boolean;
180
180
  poll(): boolean;
181
+ /**
182
+ * Pids currently descended from `rootPid` by unique-id ancestry, including
183
+ * `rootPid` itself. Reparenting does not break the chain. Returns undefined
184
+ * when the root or the process table cannot be read.
185
+ */
186
+ lineage(rootPid: number): Set<number> | undefined;
181
187
  close(): void;
182
188
  };
183
189
 
@@ -314,6 +320,20 @@ export function createDarwinAncestryTracker(
314
320
  retainOwnedProcess(owned, processRef);
315
321
  return true;
316
322
  };
323
+ const listIdentities = (): Map<number, DarwinIdentity> | undefined => {
324
+ const capacity = proc.symbols.proc_listallpids(null, 0);
325
+ if (capacity <= 0) return undefined;
326
+ const pids = new Int32Array(capacity + 64);
327
+ const count = proc.symbols.proc_listallpids(ptr(pids), pids.byteLength);
328
+ if (count <= 0) return undefined;
329
+ const identities = new Map<number, DarwinIdentity>();
330
+ for (let index = 0; index < count; index++) {
331
+ const pid = pids[index]!;
332
+ const identity = uniqueIdentity(pid);
333
+ if (identity) identities.set(pid, identity);
334
+ }
335
+ return identities;
336
+ };
317
337
  return {
318
338
  seed(uniqueId) {
319
339
  knownUniqueIds.add(uniqueId);
@@ -332,18 +352,9 @@ export function createDarwinAncestryTracker(
332
352
  anchorKeys.delete(`${anchor.pid}:${anchor.incarnation}`);
333
353
  }
334
354
  }
335
- const capacity = proc.symbols.proc_listallpids(null, 0);
336
- if (capacity <= 0) return false;
337
- const pids = new Int32Array(capacity + 64);
338
- const count = proc.symbols.proc_listallpids(ptr(pids), pids.byteLength);
339
- if (count <= 0) return false;
340
355
  // First pass: collect identities for all pids, avoiding Process.fromPid calls.
341
- const identities = new Map<number, { uniqueId: bigint; parentUniqueId: bigint }>();
342
- for (let index = 0; index < count; index++) {
343
- const pid = pids[index]!;
344
- const identity = uniqueIdentity(pid);
345
- if (identity) identities.set(pid, identity);
346
- }
356
+ const identities = listIdentities();
357
+ if (!identities) return false;
347
358
  // Extend ancestry evidence, then validate every listed pid that is known but
348
359
  // not yet retained: new descendants plus earlier ones whose Process.fromPid
349
360
  // check failed (it can return null for a live pid it could not query). A pid
@@ -362,6 +373,13 @@ export function createDarwinAncestryTracker(
362
373
  }
363
374
  return true;
364
375
  },
376
+ lineage(rootPid) {
377
+ const root = uniqueIdentity(rootPid);
378
+ if (!root) return undefined;
379
+ const identities = listIdentities();
380
+ if (!identities) return undefined;
381
+ return new Set([rootPid, ...extendOwnedDarwinAncestry(new Set([root.uniqueId]), identities)]);
382
+ },
365
383
  close() {
366
384
  proc.close();
367
385
  },
@@ -377,6 +395,137 @@ function supervisorArgv(): string[] {
377
395
  : [process.execPath, path.join(import.meta.dir, "bash-shell-supervisor-entry.ts")];
378
396
  }
379
397
 
398
+ /**
399
+ * Agent dir of a shared SDK broker launch argv (`... sdk broker-internal --agent-dir <dir>`),
400
+ * the only shape `ensure.ts` spawns. The argv only says where to look; the published
401
+ * discovery record decides whether the process is that broker.
402
+ */
403
+ export function sdkBrokerAgentDirFromArgs(args: readonly string[]): string | undefined {
404
+ const index = args.lastIndexOf("broker-internal");
405
+ if (index < 1 || args[index - 1] !== "sdk" || args[index + 1] !== "--agent-dir") return undefined;
406
+ if (args.length !== index + 3) return undefined;
407
+ return args[index + 2] || undefined;
408
+ }
409
+
410
+ export type SparedSdkBrokerDeps = {
411
+ /** Published broker identity for an agent dir, read fresh; null when none is published. */
412
+ readDiscovery: (agentDir: string) => Promise<{ pid: number; incarnation: string } | null>;
413
+ /** Pids descended from a pid by unique-id ancestry, including the pid itself. */
414
+ lineage: (pid: number) => Set<number> | undefined;
415
+ /** Current kernel incarnation of a pid, or undefined when it is gone or unreadable. */
416
+ incarnationOf: (pid: number) => string | undefined;
417
+ };
418
+
419
+ /**
420
+ * Pids cleanup must not kill: every owned process that is the published shared SDK
421
+ * broker for its agent dir (same pid and incarnation as the discovery record), plus
422
+ * the broker's descendants (its session hosts). The broker is a machine-wide daemon
423
+ * that a guarded command may only have happened to start. A reused pid has a
424
+ * different incarnation, so it does not match and is still killed.
425
+ */
426
+ export async function findSparedSdkBrokerPids(
427
+ owned: Iterable<Pick<NativeProcess, "pid" | "incarnation" | "args">>,
428
+ deps: SparedSdkBrokerDeps,
429
+ ): Promise<Set<number>> {
430
+ const spared = new Set<number>();
431
+ for (const processRef of owned) {
432
+ let args: string[];
433
+ try {
434
+ args = processRef.args();
435
+ } catch {
436
+ continue;
437
+ }
438
+ const agentDir = sdkBrokerAgentDirFromArgs(args);
439
+ if (!agentDir) continue;
440
+ const discovery = await Promise.resolve()
441
+ .then(() => deps.readDiscovery(agentDir))
442
+ .catch(() => null);
443
+ if (discovery?.pid !== processRef.pid || discovery.incarnation !== processRef.incarnation) continue;
444
+ // The lineage walk reads the root by bare pid, so only trust it if the broker
445
+ // still holds the same incarnation afterwards.
446
+ const lineage = deps.lineage(processRef.pid) ?? new Set([processRef.pid]);
447
+ if (deps.incarnationOf(processRef.pid) !== processRef.incarnation) continue;
448
+ for (const pid of lineage) spared.add(pid);
449
+ }
450
+ return spared;
451
+ }
452
+
453
+ /** Upper bound on the broker lookup so a stalled discovery read cannot stall cleanup. */
454
+ export const SPARED_SDK_BROKER_LOOKUP_TIMEOUT_MS = 1_000;
455
+
456
+ /**
457
+ * {@link findSparedSdkBrokerPids} that cannot weaken cleanup: any throw, or a lookup
458
+ * that outlives `timeoutMs`, spares nothing, so every owned process is killed as before.
459
+ */
460
+ export async function findSparedSdkBrokerPidsBounded(
461
+ owned: Iterable<Pick<NativeProcess, "pid" | "incarnation" | "args">>,
462
+ deps: SparedSdkBrokerDeps,
463
+ timeoutMs = SPARED_SDK_BROKER_LOOKUP_TIMEOUT_MS,
464
+ ): Promise<Set<number>> {
465
+ let timer: ReturnType<typeof setTimeout> | undefined;
466
+ const timeout = new Promise<Set<number>>(resolve => {
467
+ timer = setTimeout(() => resolve(new Set()), timeoutMs);
468
+ });
469
+ try {
470
+ return await Promise.race([
471
+ Promise.resolve()
472
+ .then(() => findSparedSdkBrokerPids(owned, deps))
473
+ .catch(() => new Set<number>()),
474
+ timeout,
475
+ ]);
476
+ } finally {
477
+ clearTimeout(timer);
478
+ }
479
+ }
480
+
481
+ /** Process operations {@link signalOwnedProcessAlone} needs, injectable for tests. */
482
+ export type SignalOwnedProcessDeps = {
483
+ /** Current kernel incarnation of a pid, or undefined when it is gone or unreadable. */
484
+ incarnationOf: (pid: number) => string | undefined;
485
+ /** Raw signal by pid; throws when delivery fails. */
486
+ killPid: (pid: number, signal: NodeJS.Signals) => void;
487
+ };
488
+
489
+ /**
490
+ * SIGKILL one owned process without touching its descendants, and only while `pid`
491
+ * still names the incarnation that was recorded as owned.
492
+ *
493
+ * The only caller is darwin cleanup when a broker is spared. Darwin has no atomic
494
+ * "signal iff start time matches" primitive, so `signalRoot` fails closed there
495
+ * today; it is tried first so this picks up an identity-bound signal if the platform
496
+ * ever gains one. The fallback re-reads the incarnation right before a raw `kill(2)`.
497
+ * That is the same check-then-kill race the native `killTree` accepts per node on
498
+ * darwin (slightly wider here because of the JS and napi hop), and narrower than
499
+ * `killTree`'s unchecked process-group signal, which this path replaces. The
500
+ * `signalRoot` rule against raw-pid fallback covers broker retirement, where failing
501
+ * closed just spares the broker; here failing closed would leak an owned process.
502
+ * Returns whether a signal was delivered.
503
+ */
504
+ export function signalOwnedProcessAlone(
505
+ owned: Pick<NativeProcess, "pid" | "incarnation" | "signalRoot">,
506
+ deps: SignalOwnedProcessDeps,
507
+ ): boolean {
508
+ try {
509
+ if (owned.signalRoot(9)) return true;
510
+ } catch {}
511
+ if (deps.incarnationOf(owned.pid) !== owned.incarnation) return false;
512
+ try {
513
+ deps.killPid(owned.pid, "SIGKILL");
514
+ return true;
515
+ } catch {
516
+ return false;
517
+ }
518
+ }
519
+
520
+ async function readPublishedSdkBroker(agentDir: string): Promise<{ pid: number; incarnation: string } | null> {
521
+ // Loaded lazily so guardian startup does not pull in the SDK discovery modules; it
522
+ // only runs at cleanup when an owned process has the broker launch argv.
523
+ const { readBrokerDiscovery } = await import("../sdk/broker/discovery");
524
+ // A stale heartbeat does not make the published broker any less shared; liveness
525
+ // and incarnation are still checked against the kernel.
526
+ return readBrokerDiscovery(agentDir, Number.POSITIVE_INFINITY);
527
+ }
528
+
380
529
  export async function runBashShellGuardian(): Promise<void> {
381
530
  if (!enableLinuxChildSubreaper()) throw new Error("Linux child subreaper setup failed.");
382
531
  const ownershipFilePath = path.join(os.tmpdir(), `gjc-shell-ownership-${randomUUID()}.jsonl`);
@@ -540,7 +689,27 @@ export async function runBashShellGuardian(): Promise<void> {
540
689
  pending.push(...processRef.children());
541
690
  }
542
691
  trackingOk = (await scanOwnership()) && trackingOk;
543
- for (const owned of ownedProcesses.values()) owned.killTree(9);
692
+ const spared = darwinTracker
693
+ ? await findSparedSdkBrokerPidsBounded(ownedProcesses.values(), {
694
+ readDiscovery: readPublishedSdkBroker,
695
+ lineage: pid => darwinTracker.lineage(pid),
696
+ incarnationOf: pid => Process.fromPid(pid)?.incarnation,
697
+ })
698
+ : undefined;
699
+ for (const owned of ownedProcesses.values()) {
700
+ if (spared?.has(owned.pid)) continue;
701
+ if (!spared?.size) {
702
+ owned.killTree(9);
703
+ continue;
704
+ }
705
+ // killTree walks ppid descendants, so on a non-spared ancestor (for example
706
+ // the darwin launch trampoline) it would still reach the spared broker.
707
+ // Darwin ownership already lists every descendant, so signal each one alone.
708
+ signalOwnedProcessAlone(owned, {
709
+ incarnationOf: pid => Process.fromPid(pid)?.incarnation,
710
+ killPid: (pid, signal) => process.kill(pid, signal),
711
+ });
712
+ }
544
713
  }
545
714
  darwinTracker?.close();
546
715
  await ledger.close();
@@ -177,7 +177,12 @@ export class IsolatedShell {
177
177
  async abort(): Promise<void> {
178
178
  if (this.#closed) return;
179
179
  this.#abortPromise ??= this.#ready.promise
180
- .then(() => this.#requestVoid("abort"))
180
+ .then(() => {
181
+ if (this.#closed || this.#child.exitCode !== null || this.#child.signalCode !== null) return;
182
+ // Abort acknowledgement can wait behind the foreground command. The
183
+ // run promise owns cancellation settlement, so do not wait for it here.
184
+ this.#dispatchVoid("abort").acknowledgement.catch(() => undefined);
185
+ })
181
186
  .finally(() => {
182
187
  this.#abortPromise = undefined;
183
188
  });
@@ -201,7 +206,12 @@ export class IsolatedShell {
201
206
  }
202
207
 
203
208
  async #requestVoid(type: "abort" | "close"): Promise<void> {
204
- if (this.#child.exitCode !== null || this.#child.signalCode !== null) return;
209
+ await this.#dispatchVoid(type).acknowledgement;
210
+ }
211
+
212
+ #dispatchVoid(type: "abort" | "close"): { acknowledgement: Promise<void> } {
213
+ if (this.#child.exitCode !== null || this.#child.signalCode !== null)
214
+ return { acknowledgement: Promise.resolve() };
205
215
  const id = this.#nextId++;
206
216
  const deferred = Promise.withResolvers<void>();
207
217
  this.#pending.set(id, { kind: "void", resolve: deferred.resolve, reject: deferred.reject });
@@ -211,7 +221,7 @@ export class IsolatedShell {
211
221
  this.#pending.delete(id);
212
222
  throw error;
213
223
  }
214
- await deferred.promise;
224
+ return { acknowledgement: deferred.promise };
215
225
  }
216
226
 
217
227
  #send(request: BashShellWorkerRequest): void {
@@ -1,7 +1,12 @@
1
+ import * as crypto from "node:crypto";
1
2
  import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { hasFsCode, isEnoent } from "@gajae-code/utils";
2
5
 
3
- const HTML_EXPORT_DESTINATION_OPEN_FLAGS =
4
- fs.constants.O_WRONLY | fs.constants.O_CREAT | (process.platform === "win32" ? 0 : (fs.constants.O_NOFOLLOW ?? 0));
6
+ const NOFOLLOW = process.platform === "win32" ? 0 : (fs.constants.O_NOFOLLOW ?? 0);
7
+ const HTML_EXPORT_DESTINATION_OPEN_FLAGS = fs.constants.O_WRONLY | fs.constants.O_CREAT | NOFOLLOW;
8
+ const HTML_EXPORT_TEMP_OPEN_FLAGS = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | NOFOLLOW;
9
+ const HTML_EXPORT_EXISTING_OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0) | NOFOLLOW;
5
10
 
6
11
  /** Owner-only HTML export. A replaced file is locked down on the opened descriptor. */
7
12
  export function openHtmlExportDestination(outputPath: string): number {
@@ -14,3 +19,43 @@ export function openHtmlExportDestination(outputPath: string): number {
14
19
  throw error;
15
20
  }
16
21
  }
22
+
23
+ /**
24
+ * Owner-only sibling of `outputPath` that an export is written to and then renamed over the
25
+ * output, so a failed or interrupted export never leaves a partial file at the output path.
26
+ */
27
+ export function createHtmlExportTempFile(outputPath: string): { path: string; fd: number } {
28
+ const tempPath = path.join(path.dirname(outputPath), `.${path.basename(outputPath)}.${crypto.randomUUID()}.tmp`);
29
+ const fd = fs.openSync(tempPath, HTML_EXPORT_TEMP_OPEN_FLAGS, 0o600);
30
+ try {
31
+ fs.fchmodSync(fd, 0o600);
32
+ return { path: tempPath, fd };
33
+ } catch (error) {
34
+ fs.closeSync(fd);
35
+ removeHtmlExportTempFile(tempPath);
36
+ throw error;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Opens an existing output only to compare its identity with the source; never writes it.
42
+ * Returns undefined when there is no output yet, or it cannot be opened for reading (the path
43
+ * preflight already compared its identity).
44
+ */
45
+ export function openExistingHtmlExportOutput(outputPath: string): number | undefined {
46
+ try {
47
+ return fs.openSync(outputPath, HTML_EXPORT_EXISTING_OPEN_FLAGS);
48
+ } catch (error) {
49
+ if (isEnoent(error) || hasFsCode(error, "EACCES")) return undefined;
50
+ throw error;
51
+ }
52
+ }
53
+
54
+ /** Removes an export temp file; a missing file is fine. */
55
+ export function removeHtmlExportTempFile(tempPath: string): void {
56
+ try {
57
+ fs.unlinkSync(tempPath);
58
+ } catch (error) {
59
+ if (!isEnoent(error)) throw error;
60
+ }
61
+ }