gentle-pi 4.5.0 → 4.6.0

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 (243) hide show
  1. package/README.md +9 -6
  2. package/assets/agents/gentle-ai-verify.md +4 -0
  3. package/assets/agents/gentle-ai-worker.md +1 -0
  4. package/assets/migrations/agent-body-history.json +147 -0
  5. package/assets/orchestrator-delegation-reference.md +3 -3
  6. package/assets/orchestrator-delegation.md +2 -2
  7. package/assets/orchestrator-verification.md +10 -6
  8. package/assets/orchestrator.md +8 -8
  9. package/bin/gentle-shell.mjs +61 -26
  10. package/docs/ci-performance.md +11 -0
  11. package/docs/delegated-verification.md +6 -0
  12. package/docs/fast-mode.md +15 -0
  13. package/docs/gentle-agents-activity.md +8 -0
  14. package/docs/gentle-music.md +6 -3
  15. package/docs/gentle-shell.md +70 -20
  16. package/docs/install-wizard.md +1 -1
  17. package/docs/mcp-status.md +52 -0
  18. package/docs/prompt-budget.md +28 -0
  19. package/docs/readme-reference.md +82 -21
  20. package/docs/session-profile-format.md +20 -5
  21. package/docs/sound-notifications.md +1 -1
  22. package/docs/star-prompt.md +32 -0
  23. package/docs/work-continuity.md +46 -0
  24. package/extensions/ask-user-question.ts +1 -0
  25. package/extensions/codegraph-tools.ts +38 -4
  26. package/extensions/gentle-agents.ts +477 -50
  27. package/extensions/gentle-ai.ts +1046 -191
  28. package/extensions/gentle-fast.ts +61 -0
  29. package/extensions/gentle-guide.ts +174 -0
  30. package/extensions/gentle-herdr-activity.ts +21 -1
  31. package/extensions/gentle-herdr-agent.ts +144 -0
  32. package/extensions/gentle-music.ts +10 -0
  33. package/extensions/gentle-program-identity.ts +61 -0
  34. package/extensions/gentle-shell.ts +642 -97
  35. package/extensions/gentle-star-prompt.ts +334 -0
  36. package/extensions/gentle-stats.ts +5 -5
  37. package/extensions/gentle-todo.ts +42 -22
  38. package/extensions/history/store.ts +18 -12
  39. package/extensions/skill-registry.ts +35 -3
  40. package/extensions/startup-banner.ts +39 -7
  41. package/lib/agent-assets.ts +74 -17
  42. package/lib/agent-profiles.ts +1 -1
  43. package/lib/agents-config.ts +12 -3
  44. package/lib/agents-keys.ts +8 -16
  45. package/lib/agents-protocol.ts +80 -4
  46. package/lib/agents-runner.ts +105 -4
  47. package/lib/agents-view.ts +6 -1
  48. package/lib/agents-widget.ts +132 -9
  49. package/lib/bridge-cost.ts +28 -0
  50. package/lib/codemode-renderer.ts +16 -0
  51. package/lib/command-palette-catalog.ts +1 -0
  52. package/lib/command-palette.ts +21 -8
  53. package/lib/exploration-budget.ts +62 -0
  54. package/lib/gentle-guide.ts +201 -0
  55. package/lib/gentle-shell-launcher.ts +4 -0
  56. package/lib/herdr-activity.ts +9 -3
  57. package/lib/herdr-task-summary-policy.ts +85 -0
  58. package/lib/inprocess-reviewer.ts +33 -13
  59. package/lib/jobs-sidebar-state.ts +5 -6
  60. package/lib/jobs-widget.ts +16 -52
  61. package/lib/keymaps-customize.ts +81 -0
  62. package/lib/keymaps.ts +291 -0
  63. package/lib/model-fallback-notice.ts +61 -0
  64. package/lib/model-fallback-policy.ts +141 -0
  65. package/lib/model-fallback-store.ts +143 -0
  66. package/lib/model-routing-authority.ts +10 -2
  67. package/lib/nan-provider.ts +3 -2
  68. package/lib/native-review-cli.ts +7 -2
  69. package/lib/notification-customize.ts +48 -51
  70. package/lib/openai-fast-tier.ts +22 -0
  71. package/lib/orchestrator-discovery.ts +5 -1
  72. package/lib/orchestrator-fallback.ts +75 -0
  73. package/lib/pasted-image-paths.ts +113 -0
  74. package/lib/questionnaire/questionnaire-view.ts +121 -7
  75. package/lib/review-candidate-view-owner.ts +4 -0
  76. package/lib/review-candidate-view.ts +10 -7
  77. package/lib/review-host-relay.ts +5 -1
  78. package/lib/review-integration-v2.ts +22 -7
  79. package/lib/review-repository.ts +5 -0
  80. package/lib/session-profile-append-controller.ts +21 -6
  81. package/lib/session-profile-authority.ts +119 -0
  82. package/lib/session-profile-binding.ts +54 -5
  83. package/lib/session-profile-freeze.ts +105 -9
  84. package/lib/session-profile-integration.ts +313 -0
  85. package/lib/session-profile-persistence.ts +63 -9
  86. package/lib/shell-bar.ts +171 -56
  87. package/lib/shell-card.ts +26 -6
  88. package/lib/shell-page.ts +120 -0
  89. package/lib/shell-panel.ts +149 -0
  90. package/lib/shell-prompt.ts +53 -1
  91. package/lib/shell-sidebar-layout.ts +98 -25
  92. package/lib/shell-sidebar.ts +54 -1
  93. package/lib/shell-stats.ts +123 -0
  94. package/lib/shell-todo.ts +71 -0
  95. package/lib/shell-usage.ts +12 -2
  96. package/lib/star-prompt.ts +197 -0
  97. package/lib/verifier-admission.ts +18 -8
  98. package/lib/verifier-settle-reminder.ts +64 -0
  99. package/lib/vim-editor-adapter.ts +6 -1
  100. package/lib/visual-customization-policy.ts +41 -6
  101. package/lib/visual-customize-view.ts +164 -26
  102. package/lib/visual-layout-preview.ts +43 -0
  103. package/lib/yolo-session-policy.ts +28 -1
  104. package/package.json +1 -1
  105. package/runtime/gentle-shell-launcher.mjs +4 -0
  106. package/runtime/native-review-cli.mjs +7 -2
  107. package/runtime/review-integration-v2.mjs +22 -7
  108. package/runtime/windows-session-transport.ps1 +60 -3
  109. package/scripts/bootstrap.sh +4 -1
  110. package/scripts/installer-preflight.mjs +1 -1
  111. package/scripts/pi-update.mjs +113 -3
  112. package/scripts/run-test-suite.mjs +17 -1
  113. package/scripts/shell-snapshot.mjs +340 -0
  114. package/scripts/test-packed-runner.mjs +1 -1
  115. package/scripts/update-agent-body-history.mjs +41 -0
  116. package/scripts/verify-installer-tap.mjs +45 -0
  117. package/scripts/verify-package-files.mjs +2 -0
  118. package/skills/gentle-ai/SKILL.md +2 -2
  119. package/skills/tui-design/NOTICE.md +5 -0
  120. package/skills/tui-design/SKILL.md +56 -0
  121. package/skills/tui-design/references/commands.md +75 -0
  122. package/skills/tui-design/references/critique.md +48 -0
  123. package/skills/tui-design/references/design-doc.md +44 -0
  124. package/skills/tui-design/references/terminal-craft.md +64 -0
  125. package/skills/tui-design/references/visual-loop.md +32 -0
  126. package/tests/agents-protocol.test.ts +53 -1
  127. package/tests/agents-runner.test.ts +168 -3
  128. package/tests/agents-view.test.ts +27 -0
  129. package/tests/agents-widget.test.ts +312 -10
  130. package/tests/bounded-scan-contract.test.ts +39 -0
  131. package/tests/bridge-cost.test.ts +32 -0
  132. package/tests/bundled-install.test.ts +6 -4
  133. package/tests/ci-concurrency.test.ts +11 -0
  134. package/tests/ci-merge-base-identity.test.ts +114 -0
  135. package/tests/codegraph-tools.test.ts +69 -0
  136. package/tests/codemode-rendering.test.ts +22 -2
  137. package/tests/command-palette.test.ts +16 -2
  138. package/tests/commit-slice-signal.test.ts +11 -9
  139. package/tests/delegate-for-reason-contract.test.ts +5 -4
  140. package/tests/design-canvas-server.test.ts +6 -2
  141. package/tests/exploration-budget.test.ts +128 -0
  142. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  143. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  144. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  145. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  148. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  149. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  150. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  151. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  152. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  153. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  154. package/tests/gentle-agents.test.ts +416 -21
  155. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  156. package/tests/gentle-ai.test.ts +1011 -37
  157. package/tests/gentle-fast.test.ts +73 -0
  158. package/tests/gentle-guide.test.ts +208 -0
  159. package/tests/gentle-herdr-activity.test.ts +76 -2
  160. package/tests/gentle-herdr-agent.test.ts +111 -0
  161. package/tests/gentle-music.test.ts +36 -1
  162. package/tests/gentle-program-identity.test.ts +197 -0
  163. package/tests/gentle-shell-bin.test.ts +49 -26
  164. package/tests/gentle-shell-launcher.test.ts +18 -2
  165. package/tests/gentle-shell.test.ts +1068 -37
  166. package/tests/gentle-stats.test.ts +15 -2
  167. package/tests/gentle-todo.test.ts +50 -4
  168. package/tests/herdr-task-summary-policy.test.ts +128 -0
  169. package/tests/history-store-private-mode.test.ts +40 -0
  170. package/tests/image-paste-chips.test.ts +42 -0
  171. package/tests/inprocess-reviewer.test.ts +122 -0
  172. package/tests/installer-posix-bootstrap.test.ts +67 -5
  173. package/tests/installer-server.test.ts +2 -2
  174. package/tests/installer-windows-diagnostics.test.ts +4 -5
  175. package/tests/isolated-config-home.ts +28 -0
  176. package/tests/jobs-widget.test.ts +25 -37
  177. package/tests/keymaps-customize.test.ts +114 -0
  178. package/tests/keymaps.test.ts +103 -0
  179. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  180. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  181. package/tests/model-fallback-notice.test.ts +45 -0
  182. package/tests/model-fallback-policy.test.ts +83 -0
  183. package/tests/model-fallback-store.test.ts +111 -0
  184. package/tests/nan-provider.test.ts +4 -4
  185. package/tests/no-self-pause-contract.test.ts +19 -0
  186. package/tests/notification-customize.test.ts +58 -34
  187. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  188. package/tests/odd-routing-contract.test.ts +1 -1
  189. package/tests/orchestrator-fallback.test.ts +82 -0
  190. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  191. package/tests/package-manifest.test.ts +160 -7
  192. package/tests/pasted-image-paths.test.ts +118 -0
  193. package/tests/persona-reply-language.test.ts +61 -0
  194. package/tests/pi-update-launcher.test.ts +32 -8
  195. package/tests/pi-update-source.test.ts +162 -0
  196. package/tests/profile-fast-tier.test.ts +311 -0
  197. package/tests/profile-tier-footer.test.ts +79 -0
  198. package/tests/questionnaire-view.test.ts +150 -0
  199. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  200. package/tests/review-candidate-view.test.ts +51 -0
  201. package/tests/review-controller-native-routing.test.ts +120 -6
  202. package/tests/review-gate.test.ts +24 -0
  203. package/tests/review-inspect-preflight.test.ts +197 -0
  204. package/tests/review-integration-v2-forward.test.ts +59 -0
  205. package/tests/review-repository.test.ts +52 -1
  206. package/tests/review-sidebar-state.test.ts +5 -5
  207. package/tests/run-test-suite.test.ts +61 -5
  208. package/tests/sensitive-path-tools.test.ts +74 -0
  209. package/tests/session-profile-append-controller.test.ts +63 -0
  210. package/tests/session-profile-authority.test.ts +259 -0
  211. package/tests/session-profile-binding.test.ts +15 -0
  212. package/tests/session-profile-extension.test.ts +615 -0
  213. package/tests/session-profile-freeze.test.ts +110 -2
  214. package/tests/session-profile-integration.test.ts +857 -0
  215. package/tests/session-profile-persistence.test.ts +57 -0
  216. package/tests/session-profile-v1-compat.test.ts +221 -0
  217. package/tests/shell-bar.test.ts +113 -55
  218. package/tests/shell-card.test.ts +13 -1
  219. package/tests/shell-page.test.ts +108 -0
  220. package/tests/shell-panel.test.ts +332 -0
  221. package/tests/shell-prompt.test.ts +54 -0
  222. package/tests/shell-render-cache.test.ts +5 -0
  223. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  224. package/tests/shell-sidebar-layout.test.ts +159 -27
  225. package/tests/shell-stats.test.ts +90 -0
  226. package/tests/shell-usage.test.ts +14 -0
  227. package/tests/skill-registry.test.ts +68 -1
  228. package/tests/star-prompt.test.ts +470 -0
  229. package/tests/startup-banner.test.ts +57 -1
  230. package/tests/task-size-routing-contract.test.ts +45 -1
  231. package/tests/verifier-settle-reminder.test.ts +281 -0
  232. package/tests/verify-first-launch-contract.test.ts +56 -5
  233. package/tests/verify-installer-tap.test.ts +57 -0
  234. package/tests/vim-editor-adapter.test.ts +2 -2
  235. package/tests/visual-customization-policy.test.ts +61 -7
  236. package/tests/visual-customize-view.test.ts +253 -8
  237. package/tests/visual-layout-preview.test.ts +28 -0
  238. package/tests/windows-session-bootstrap.test.ts +105 -2
  239. package/tests/work-continuity-contract.test.ts +86 -0
  240. package/tests/writer-surfaces.test.ts +12 -10
  241. package/tests/yolo-customize.test.ts +30 -11
  242. package/tests/yolo-mode-runtime.test.ts +4 -2
  243. package/tests/yolo-mode.test.ts +16 -2
@@ -230,6 +230,7 @@ public static class WindowsSessionBootstrap {
230
230
  [DllImport("kernel32.dll", SetLastError=true)] static extern bool ReadFile(IntPtr handle, byte[] buffer, uint length, out uint read, IntPtr overlapped);
231
231
  [DllImport("kernel32.dll", SetLastError=true)] static extern bool WriteFile(IntPtr handle, byte[] buffer, uint length, out uint written, IntPtr overlapped);
232
232
  [DllImport("kernel32.dll", SetLastError=true)] static extern bool FlushFileBuffers(IntPtr handle);
233
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool WaitNamedPipe(string name, uint timeout);
233
234
  [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr CreateNamedPipe(string name, uint openMode, uint pipeMode, uint maxInstances, uint outBufferSize, uint inBufferSize, uint defaultTimeout, IntPtr securityAttributes);
234
235
  [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool GetVolumeNameForVolumeMountPoint(string rootPathName, System.Text.StringBuilder volumeName, uint cchBufferLength);
235
236
  [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool GetVolumeInformation(string rootPathName, IntPtr volumeNameBuffer, uint volumeNameSize, out uint volumeSerialNumber, out uint maximumComponentLength, out uint fileSystemFlags, IntPtr fileSystemNameBuffer, uint fileSystemNameSize);
@@ -379,11 +380,14 @@ public static class WindowsSessionBootstrap {
379
380
  static string RecordName(string sessionId, string token) { return sessionId + "." + token + ".json"; }
380
381
  static string RecordText(string sessionId, string endpoint, long createdAt) { return "{\"version\":1,\"sessionId\":\"" + sessionId + "\",\"endpoint\":\"" + endpoint.Replace("\\", "\\\\") + "\",\"createdAt\":" + createdAt.ToString(System.Globalization.CultureInfo.InvariantCulture) + "}"; }
381
382
  static OpenResult OpenRecord(IntPtr root, string name, bool create, byte[] descriptor, bool allowDeleteSharing) {
383
+ return OpenRecord(root, name, create, descriptor, allowDeleteSharing, false);
384
+ }
385
+ static OpenResult OpenRecord(IntPtr root, string name, bool create, byte[] descriptor, bool allowDeleteSharing, bool protectIdentity) {
382
386
  IntPtr chars = IntPtr.Zero, unicode = IntPtr.Zero, security = IntPtr.Zero, handle = IntPtr.Zero;
383
387
  try {
384
388
  unicode = Unicode(name, out chars); var attributes = new OBJECT_ATTRIBUTES(); attributes.Length = (uint)Marshal.SizeOf(typeof(OBJECT_ATTRIBUTES)); attributes.RootDirectory = root; attributes.ObjectName = unicode; attributes.Attributes = OBJ_CASE_INSENSITIVE | OBJ_DONT_REPARSE;
385
389
  if (create) { if (descriptor == null || descriptor.Length == 0) Fail("unavailable"); security = Marshal.AllocHGlobal(descriptor.Length); Marshal.Copy(descriptor, 0, security, descriptor.Length); attributes.SecurityDescriptor = security; }
386
- IO_STATUS_BLOCK statusBlock; uint status = NtCreateFile(out handle, SYNCHRONIZE | FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | READ_CONTROL | DELETE, ref attributes, out statusBlock, IntPtr.Zero, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | (allowDeleteSharing ? FILE_SHARE_DELETE : 0), create ? FILE_CREATE : FILE_OPEN, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT, IntPtr.Zero, 0);
390
+ IO_STATUS_BLOCK statusBlock; uint status = NtCreateFile(out handle, SYNCHRONIZE | FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_ATTRIBUTES | READ_CONTROL | DELETE, ref attributes, out statusBlock, IntPtr.Zero, 0, protectIdentity ? FILE_SHARE_READ : FILE_SHARE_READ | FILE_SHARE_WRITE | (allowDeleteSharing ? FILE_SHARE_DELETE : 0), create ? FILE_CREATE : FILE_OPEN, FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT, IntPtr.Zero, 0);
387
391
  if (status != 0) { Close(handle); return new OpenResult(IntPtr.Zero, status); } return new OpenResult(handle, status);
388
392
  } finally { if (security != IntPtr.Zero) Marshal.FreeHGlobal(security); if (unicode != IntPtr.Zero) Marshal.FreeHGlobal(unicode); if (chars != IntPtr.Zero) Marshal.FreeHGlobal(chars); }
389
393
  }
@@ -437,8 +441,61 @@ public static class WindowsSessionBootstrap {
437
441
  }
438
442
  }
439
443
  public static void Publish(string sessionId, string endpoint, long createdAt, byte[] descriptor, string sid) { PublishOwned(sessionId, endpoint, createdAt, descriptor, sid); }
440
- public static PresenceRecord[] List(string sid) { return List(null, sid); }
441
- public static PresenceRecord[] List(string excluded, string sid) { lock (Gate) { RequirePresence(); if (excluded != null && !Regex.IsMatch(excluded, "^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$")) Fail("invalid"); var newest = new Dictionary<string, PresenceRecord>(StringComparer.Ordinal); foreach (string name in EnumeratePinned(Presence)) { IntPtr file = IntPtr.Zero; try { RecordIdentity ignoredIdentity; PresenceRecord record = ReadPinnedRecord(name, sid, out file, out ignoredIdentity); if (record.SessionId == excluded) continue; PresenceRecord prior; if (!newest.TryGetValue(record.SessionId, out prior) || record.CreatedAt > prior.CreatedAt || (record.CreatedAt == prior.CreatedAt && String.CompareOrdinal(record.Token, prior.Token) > 0)) newest[record.SessionId] = record; } catch (BootstrapFailure) { } finally { Close(file); } } var records = new List<PresenceRecord>(newest.Values); records.Sort(delegate(PresenceRecord left, PresenceRecord right) { return String.CompareOrdinal(left.SessionId, right.SessionId); }); return records.ToArray(); } }
444
+ // WaitNamedPipe does not connect, send traffic, or consume an accept slot.
445
+ // Only ERROR_FILE_NOT_FOUND proves absence; busy, timeout, access denied,
446
+ // and every other error leave discovery reachability inconclusive.
447
+ const uint PresenceProbeMilliseconds = 1;
448
+ const int ERROR_FILE_NOT_FOUND = 2;
449
+ static bool EndpointAbsent(string endpoint) {
450
+ if (WaitNamedPipe(endpoint, PresenceProbeMilliseconds)) return false;
451
+ return Marshal.GetLastWin32Error() == ERROR_FILE_NOT_FOUND;
452
+ }
453
+ static void TryRemoveAbsentRecord(string name, PresenceRecord expected, RecordIdentity expectedIdentity, string sid) {
454
+ IntPtr file = IntPtr.Zero;
455
+ try {
456
+ // Reopen relative to the pinned private directory. Denying write and
457
+ // delete sharing prevents content changes or replacement during this
458
+ // check; a conflicting handle means leave the record untouched.
459
+ OpenResult opened = OpenRecord(Presence, name, false, null, false, true);
460
+ if (opened.Handle == IntPtr.Zero) return;
461
+ file = opened.Handle;
462
+ RecordIdentity identity = AssertRecord(file, sid);
463
+ PresenceRecord current = ParseRecord(name, ReadRecordText(file));
464
+ if (!identity.Equals(expectedIdentity) || !SameRecord(current, expected.SessionId, expected.Endpoint, expected.CreatedAt)) return;
465
+ if (!EndpointAbsent(current.Endpoint)) return;
466
+ DeletePinnedHandle(file);
467
+ } catch (BootstrapFailure) { /* best effort, never delete an unverified identity */ }
468
+ finally { Close(file); }
469
+ }
470
+ public static PresenceRecord[] List(string sid) { return List(null, sid); }
471
+ public static PresenceRecord[] List(string excluded, string sid) {
472
+ lock (Gate) {
473
+ RequirePresence();
474
+ if (excluded != null && !Regex.IsMatch(excluded, "^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$")) Fail("invalid");
475
+ var newest = new Dictionary<string, PresenceRecord>(StringComparer.Ordinal);
476
+ // Enumeration is capped at MaxEntries (64); each entry needs at most
477
+ // two explicit 1ms pipe waits, with no retries or protocol handshake.
478
+ foreach (string name in EnumeratePinned(Presence)) {
479
+ IntPtr file = IntPtr.Zero;
480
+ try {
481
+ RecordIdentity identity;
482
+ PresenceRecord record = ReadPinnedRecord(name, sid, out file, out identity);
483
+ if (record.SessionId == excluded) continue;
484
+ if (EndpointAbsent(record.Endpoint)) {
485
+ Close(file); file = IntPtr.Zero;
486
+ TryRemoveAbsentRecord(name, record, identity, sid);
487
+ continue;
488
+ }
489
+ PresenceRecord prior;
490
+ if (!newest.TryGetValue(record.SessionId, out prior) || record.CreatedAt > prior.CreatedAt || (record.CreatedAt == prior.CreatedAt && String.CompareOrdinal(record.Token, prior.Token) > 0)) newest[record.SessionId] = record;
491
+ } catch (BootstrapFailure) { }
492
+ finally { Close(file); }
493
+ }
494
+ var records = new List<PresenceRecord>(newest.Values);
495
+ records.Sort(delegate(PresenceRecord left, PresenceRecord right) { return String.CompareOrdinal(left.SessionId, right.SessionId); });
496
+ return records.ToArray();
497
+ }
498
+ }
442
499
  public static PresenceRecord Resolve(string sessionId, string sid) { PresenceRecord[] records = List(null, sid); foreach (PresenceRecord record in records) if (record.SessionId == sessionId) return record; Fail("not_found"); return null; }
443
500
  static void RemoveOwnedPublication(OwnedPublication owned) {
444
501
  IntPtr current = IntPtr.Zero;
@@ -78,7 +78,10 @@ make_tools() {
78
78
  tools=$(mktemp -d "$HOME/.gentle-shell-bootstrap-tools.XXXXXXXX") || fail 'Cannot create private tooling directory'
79
79
  case "$tools" in "$HOME"/.gentle-shell-bootstrap-tools.*) ;; *) fail 'Conflicting tooling destination';; esac
80
80
  [ -d "$tools" ] && [ ! -L "$tools" ] || fail 'Unsafe tooling destination'
81
- ls -nd "$tools" | awk -v uid="$uid" '$3 == uid && $1 == "drwx------" {ok=1} END {exit !ok}' || fail 'Unsafe tooling ownership'
81
+ # ls may append @ (BSD: extended attributes, e.g. macOS com.apple.provenance
82
+ # on every new directory) or . (GNU: an SELinux security context), but
83
+ # never + (an ACL could grant others access).
84
+ ls -nd "$tools" | awk -v uid="$uid" '$3 == uid && $1 ~ /^drwx------[@.]?$/ {ok=1} END {exit !ok}' || fail 'Unsafe tooling ownership'
82
85
  # No existing destination is ever reused or replaced.
83
86
  mkdir "$tools/.claim" || fail 'Conflicting tooling destination'
84
87
  owned=1
@@ -25,7 +25,7 @@ export const requirements = Object.freeze({
25
25
  /** Pi version the installer installs next to gentle-pi, and the version an older
26
26
  * Pi is updated to (never below requirements.pi; the runner asserts it).
27
27
  */
28
- export const PI_INSTALL_VERSION = "1.4.0";
28
+ export const PI_INSTALL_VERSION = "1.5.0";
29
29
 
30
30
  /** Runtime persisted under PNPM_HOME. Bootstrap-only Node: `pnpm runtime set
31
31
  * node <node> -g`, then `pnpm add -g npm@<npm> pnpm@<pnpm>`, or only npm when
@@ -154,6 +154,88 @@ function mainBuildTarball(version, {env, home, path}) {
154
154
  return path.join(config, 'main', 'packages', `${SHELL}-${version}.tgz`);
155
155
  }
156
156
 
157
+ function managerVersionAtLeast(actual, minimum) {
158
+ if (!/^\d+\.\d+\.\d+$/.test(actual)) return false;
159
+ const current = actual.split('.').map(Number), required = minimum.split('.').map(Number);
160
+ for (let i = 0; i < current.length; i++) {
161
+ if (current[i] !== required[i]) return current[i] > required[i];
162
+ }
163
+ return true;
164
+ }
165
+
166
+ async function optionalFile(fs, file) {
167
+ try { return String(await fs.readFile(file, 'utf8')); }
168
+ catch (error) { if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return undefined; throw error; }
169
+ }
170
+
171
+ // Source updates are deliberately standalone: never infer a workspace owner or
172
+ // replace a global Shell link with a registry package.
173
+ async function sourceOwner({root, linkPath, manifest, selected, adapters, path, key, canonical, platform, cwd, env}) {
174
+ await canonical(path.join(root, '.git'));
175
+ if (key(await canonical(path.join(root, 'package.json'))) !== key(path.join(root, 'package.json'))) throw refusal('source manifest is linked outside the checkout');
176
+ const pin = /^(npm|pnpm)@(\d+\.\d+\.\d+)$/.exec(manifest.packageManager ?? '');
177
+ if (!pin) throw refusal('source checkout needs an exact npm or pnpm packageManager pin');
178
+ const ranges = ['dependencies', 'devDependencies', 'optionalDependencies'].map(field => manifest[field]?.[PI]).filter(value => value !== undefined);
179
+ if (!ranges.length || ranges.some(value => typeof value !== 'string' || !/^[~^<>=*0-9][0-9A-Za-z.*~^<>=|+\s-]*$/.test(value)) || new Set(ranges).size !== 1) throw refusal('source Pi must be a direct registry dependency with one declared range');
180
+ let sourceConfig;
181
+ for (let dir = root; ; dir = path.dirname(dir)) {
182
+ const pkg = dir === root ? manifest : JSON.parse(await optionalFile(adapters.fs, path.join(dir, 'package.json')) ?? '{}');
183
+ const config = await optionalFile(adapters.fs, path.join(dir, 'pnpm-workspace.yaml'));
184
+ if (pkg.workspaces !== undefined || (config !== undefined && (dir !== root || pin[1] !== 'pnpm'))) throw refusal('source workspaces are unsupported; update Pi from the workspace owner');
185
+ if (dir === root) sourceConfig = config;
186
+ if (path.dirname(dir) === dir) break;
187
+ }
188
+ const locks = [];
189
+ for (const name of ['pnpm-lock.yaml', 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'bun.lock', 'bun.lockb']) {
190
+ if (await optionalFile(adapters.fs, path.join(root, name)) !== undefined) locks.push(name);
191
+ }
192
+ const lock = pin[1] === 'pnpm' ? 'pnpm-lock.yaml' : 'package-lock.json';
193
+ if (locks.length !== 1 || locks[0] !== lock) throw refusal(`source checkout needs only ${lock}; conflicting or missing lockfiles require manual resolution`);
194
+ if (key(await canonical(path.join(root, lock))) !== key(path.join(root, lock))) throw refusal('source lockfile is linked outside the checkout');
195
+ const peerRoot = await canonical(path.join(root, 'node_modules', PI));
196
+ let packaged = false;
197
+ for (let dir = peerRoot; ; dir = path.dirname(dir)) {
198
+ if (path.basename(dir) === 'node_modules') { packaged = true; break; }
199
+ let source = false;
200
+ try { await adapters.fs.realpath(path.join(dir, '.git')); source = true; }
201
+ catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error; }
202
+ if (source) throw refusal('source Pi is a linked source checkout; update that checkout separately');
203
+ if (path.dirname(dir) === dir) break;
204
+ }
205
+ if (!packaged) throw refusal('source Pi has an unsupported installed override outside node_modules');
206
+ const peerCli = await canonical(path.join(root, 'node_modules', PI, 'dist/bundle/cli.js'));
207
+ if (key(peerCli) !== key(selected)) throw refusal('source checkout does not supply the selected adjacent Pi');
208
+ const invocation = await invocationFor(pin[1], adapters, platform);
209
+ if (!invocation) throw refusal(`source checkout requires ${pin[0]}`);
210
+ const sourceEnv = pin[1] === 'pnpm' ? {...(env ?? process.env), COREPACK_ENABLE_PROJECT_SPEC:'0', COREPACK_ENABLE_NETWORK:'0'} : undefined;
211
+ const probeOptions = {deadlineMs:30_000, cwd, ...(sourceEnv ? {env:sourceEnv} : {})};
212
+ const version = await adapters.run(invocation.command, [...invocation.prefix, '--version'], probeOptions);
213
+ const actual = typeof version.stdout === 'string' ? version.stdout.trim() : '';
214
+ const compatible = pin[1] === 'pnpm' ? managerVersionAtLeast(actual, pin[2]) : actual === pin[2];
215
+ if (!succeeded(version) || !compatible) throw refusal(`source checkout requires ${pin[0]}${pin[1] === 'pnpm' ? ' or newer' : ''}; the available manager version differs`);
216
+ // Keep the compatible manager just checked; --dir must not acquire the older project pin.
217
+ const sourceOptions = pin[1] === 'pnpm' ? ['--pm-on-fail=ignore'] : [];
218
+ if (sourceConfig !== undefined) {
219
+ const selectors = await adapters.run(invocation.command, [...invocation.prefix, 'config', 'get', 'packages', '--json', '--dir', root, ...sourceOptions], probeOptions);
220
+ let packages;
221
+ try {
222
+ if (typeof selectors.stdout !== 'string') throw new Error('missing selector output');
223
+ const text = selectors.stdout.trim();
224
+ packages = text === '' || text === 'undefined' ? undefined : JSON.parse(text);
225
+ }
226
+ catch { throw refusal('source workspace package selectors could not be verified'); }
227
+ if (!succeeded(selectors) || (packages != null && (!Array.isArray(packages) || packages.length !== 0))) throw refusal('source workspace package selectors are unsupported; update Pi from the workspace owner');
228
+ const listing = await adapters.run(invocation.command, [...invocation.prefix, 'list', '--recursive', '--config.include-workspace-root=true', '--depth', '-1', '--json', '--dir', root, ...sourceOptions], probeOptions);
229
+ let projects;
230
+ try { projects = JSON.parse(listing.stdout); } catch { throw refusal('source workspace projects could not be verified'); }
231
+ if (!succeeded(listing) || !Array.isArray(projects) || projects.length !== 1 || key(await canonical(projects[0]?.path)) !== key(root)) throw refusal('source workspace has other or unknown projects; update Pi from the workspace owner');
232
+ }
233
+ const flags = pin[1] === 'pnpm' ? ['--dir', root, '--lockfile-dir', root, '--recursive=false', '--ignore-pnpmfile', ...(sourceConfig === undefined ? [] : ['--workspace-root'])] : ['--prefix', root, '--workspaces=false', '--no-audit', '--no-fund'];
234
+ return {name:pin[1], ...invocation, package:SHELL, spec:PI, sourceRoot:root, sourceConfig, sourceEnv, linkPath,
235
+ manifest:await adapters.fs.readFile(path.join(root, 'package.json'), 'utf8'),
236
+ args:['update', PI, '--no-save', '--ignore-scripts', '--global=false', ...flags, ...sourceOptions]};
237
+ }
238
+
157
239
  export async function resolveUpdateOwner({runtime, packageRoot, platform = process.platform, adapters, cwd, env, home}) {
158
240
  const {path, key} = pathsFor(platform);
159
241
  const canonical = canonicalWith(adapters, path);
@@ -168,8 +250,10 @@ export async function resolveUpdateOwner({runtime, packageRoot, platform = proce
168
250
  const {entries, members} = await listedEntries(groups, {adapters, path, key, canonical});
169
251
  for (const {pkg, dependency, groupRoot} of entries) {
170
252
  if ((pkg === SHELL) !== adjacent) continue;
171
- if (dependency.link === true || [dependency.resolved, dependency.version].some(value => typeof value === 'string' && LINKED.test(value))) throw refusal('listed supplier is a source or linked package');
253
+ const linked = dependency.link === true || [dependency.resolved, dependency.version].some(value => typeof value === 'string' && LINKED.test(value));
172
254
  const root = await canonical(dependency.path);
255
+ if (pkg === SHELL && key(root) !== key(shellRoot)) continue;
256
+ if (linked && pkg === PI) throw refusal('listed supplier is a source or linked package');
173
257
  const manifest = await manifestOf(adapters, path, root);
174
258
  if (manifest.name !== pkg) throw refusal('listed package identity differs');
175
259
  let cli, spec, artifact = false;
@@ -184,6 +268,10 @@ export async function resolveUpdateOwner({runtime, packageRoot, platform = proce
184
268
  const peer = await adjacentPeer({shellRoot: root, groupRoot, adapters, path, key, canonical});
185
269
  if (!peer) continue;
186
270
  cli = peer.cli;
271
+ if (linked) {
272
+ if (key(cli) === key(selected)) candidates.push(await sourceOwner({root, linkPath:dependency.path, manifest, selected, adapters, path, key, canonical, platform, cwd, env}));
273
+ continue;
274
+ }
187
275
  // Reinstalling the same Shell version re-resolves its peer; `update`
188
276
  // never upgrades Shell itself (that is `gentle-shell upgrade`).
189
277
  if (typeof manifest.version !== 'string') throw refusal('listed Shell version is missing');
@@ -232,8 +320,8 @@ export async function updateSelectedPi(input) {
232
320
  }
233
321
  // Exactly one approved package per command; never create a comma group or
234
322
  // reinstall arbitrary dependencies merely because they share a store.
235
- const args = owner.name === 'pnpm' ? ['add', '-g', owner.spec, ...(owner.package === SHELL ? ['--allow-build=gentle-pi'] : [])] : ['install', '-g', owner.spec, ...(owner.package === PI ? ['--ignore-scripts'] : [])];
236
- const result = await input.adapters.run(owner.command, [...owner.prefix, ...args], {deadlineMs:20 * 60_000, cwd: input.cwd, stderrTail:4096});
323
+ const args = owner.args ?? (owner.name === 'pnpm' ? ['add', '-g', owner.spec, ...(owner.package === SHELL ? ['--allow-build=gentle-pi'] : [])] : ['install', '-g', owner.spec, ...(owner.package === PI ? ['--ignore-scripts'] : [])]);
324
+ const result = await input.adapters.run(owner.command, [...owner.prefix, ...args], {deadlineMs:20 * 60_000, cwd: owner.sourceRoot ?? input.cwd, stderrTail:4096, ...(owner.sourceEnv ? {env:owner.sourceEnv} : {})});
237
325
  if (!succeeded(result)) {
238
326
  // One sanitized line of the manager's own error: npm prints it on stderr,
239
327
  // pnpm 11 prints ERR_PNPM_* on stdout. Read as one text, stderr last, an
@@ -242,6 +330,28 @@ export async function updateSelectedPi(input) {
242
330
  const detail = setupErrorDetail(output, input.home, input.platform);
243
331
  throw new Error(`gentle-shell update: ${owner.name} (${[owner.command, ...owner.prefix].join(' ')}) could not install ${owner.spec}${detail ? `\n${detail}` : ''}`);
244
332
  }
333
+ if (owner.sourceRoot) {
334
+ const {path, key} = pathsFor(input.platform ?? process.platform);
335
+ const canonical = canonicalWith(input.adapters, path);
336
+ let sameLink = false;
337
+ try { sameLink = key(await canonical(owner.linkPath)) === key(owner.sourceRoot); } catch { /* checked below */ }
338
+ if (!sameLink) throw new Error('gentle-shell update: the Shell link changed during the source update; inspect the installation before retrying.');
339
+ if (await input.adapters.fs.readFile(path.join(owner.sourceRoot, 'package.json'), 'utf8') !== owner.manifest) throw new Error('gentle-shell update: the source manifest changed during the update; inspect the checkout before retrying.');
340
+ if (owner.sourceConfig !== undefined && await input.adapters.fs.readFile(path.join(owner.sourceRoot, 'pnpm-workspace.yaml'), 'utf8') !== owner.sourceConfig) throw new Error('gentle-shell update: the source pnpm configuration changed during the update; inspect the checkout before retrying.');
341
+ let after = null;
342
+ try {
343
+ const peer = await adjacentPeer({shellRoot:owner.sourceRoot, adapters:input.adapters, path, key, canonical});
344
+ const nested = await canonical(path.join(owner.sourceRoot, 'node_modules', PI, 'dist/bundle/cli.js'));
345
+ if (peer && key(peer.cli) === key(nested)) after = peer.manifest.version ?? null;
346
+ } catch { /* Never invent readback after a successful manager invocation. */ }
347
+ const location = `${owner.name} updated ${PI} in ${owner.sourceRoot}`;
348
+ if (after === null) input.out?.(`${location}. The Pi version could not be read back; run 'gentle-shell --version' to check it.`);
349
+ else {
350
+ input.out?.(`${location}; the selected Pi is ${after === input.currentVersion ? 'still' : 'now'} ${after}${after !== input.currentVersion && input.currentVersion !== undefined ? ` (was ${input.currentVersion})` : ''}.`);
351
+ if (after === input.currentVersion && owner.name === 'pnpm') input.out?.('The declared version range and pnpm minimumReleaseAge setting still apply; neither was overridden.');
352
+ }
353
+ return 0;
354
+ }
245
355
  const after = await suppliedPiVersion(owner, input);
246
356
  const before = input.currentVersion;
247
357
  if (after === null) input.out?.(`${owner.name} installed ${owner.spec}. The Pi version it now supplies could not be read back; run 'gentle-shell --version' to check it.`);
@@ -10,7 +10,7 @@
10
10
  // POSIX and Windows CI.
11
11
 
12
12
  import { spawn } from "node:child_process";
13
- import { mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
13
+ import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
14
14
  import { tmpdir } from "node:os";
15
15
  import { join } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
@@ -34,6 +34,22 @@ export async function runStage(stage) {
34
34
  // fixture that leaves a subagent unfinished cannot leave its TMPDIR behind.
35
35
  const unitTmp = configHome ? mkdtempSync(join(tmpdir(), "gentle-pi-unit-tmp-")) : undefined;
36
36
  if (unitTmp) env.TMPDIR = unitTmp;
37
+ // Stripping GIT_* environment still leaves Git's config files, which it reads
38
+ // by path: a host-level global ignore (e.g. ".agents/" in ~/.gitconfig or the
39
+ // XDG ignore file) made `git add -A` inside fixtures drop an untracked
40
+ // symlink target, so the candidate view materialized a dangling link and the
41
+ // suite saw an ENOENT (gentle-shell#2552). Pin every remaining config source
42
+ // to an empty file for the stage; fixtures that need identity pass -c flags.
43
+ if (configHome) {
44
+ const emptyGitConfig = join(configHome, "empty.gitconfig");
45
+ writeFileSync(emptyGitConfig, "");
46
+ env.GIT_CONFIG_GLOBAL = emptyGitConfig;
47
+ env.GIT_CONFIG_NOSYSTEM = "1";
48
+ // An empty GIT_CONFIG_GLOBAL does not disable Git's default ignore file:
49
+ // it still reads $XDG_CONFIG_HOME/git/ignore, so a host ignore (e.g.
50
+ // ".agents/") would keep dropping fixture files from `git add -A`.
51
+ env.XDG_CONFIG_HOME = configHome;
52
+ }
37
53
  try {
38
54
  return await new Promise((resolve) => {
39
55
  const child = spawn(stage.command, { shell: true, stdio: "inherit", env });
@@ -0,0 +1,340 @@
1
+ #!/usr/bin/env node
2
+ // Launches the real Gentle Shell TUI in a headless terminal on a FORK of an
3
+ // existing session and saves PNG screenshots, so an agent can look at what the
4
+ // shell actually renders.
5
+ //
6
+ // node scripts/shell-snapshot.mjs --session <session.jsonl> [--cols 180] [--rows 50]
7
+ // [--out <dir>] [--wait <seconds>] [--cwd <dir>]
8
+ // node scripts/shell-snapshot.mjs --latest-rich [--from <project-dir>] [...same options]
9
+ //
10
+ // --latest-rich picks the newest session of <project-dir> (default: --cwd) that
11
+ // has both todo and subagent_run calls, from ~/.gentle-shell/agent/sessions.
12
+ //
13
+ // The terminal is ttyd (xterm.js) rendered by headless Chrome, driven over the
14
+ // DevTools protocol with Node's built-in WebSocket. vhs uses the same stack but
15
+ // vhs 0.12.0 silently skips rendering (no PNG, no GIF) on this setup, so the
16
+ // script drives ttyd and Chrome itself. Requires `ttyd` and Google Chrome
17
+ // (override with CHROME_BIN).
18
+ //
19
+ // The source session is never resumed or written: the shell is started with
20
+ // `--fork <session> --session-dir <scratch>/sessions`, so the fork lands in a
21
+ // fresh /tmp/gentle-eyes.* scratch directory.
22
+ import { spawn, spawnSync } from "node:child_process";
23
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
24
+ import { createServer } from "node:net";
25
+ import { homedir } from "node:os";
26
+ import { dirname, join, resolve } from "node:path";
27
+ import { setTimeout as sleep } from "node:timers/promises";
28
+ import { fileURLToPath } from "node:url";
29
+
30
+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
31
+ const launcher = join(repoRoot, "bin", "gentle-shell.mjs");
32
+ // Pi stores a project's sessions under `--<absolute path with / as ->--`.
33
+ const sessionsDirFor = (projectDir) => join(homedir(), ".gentle-shell", "agent", "sessions", `--${resolve(projectDir).replace(/^\//, "").replaceAll("/", "-")}--`);
34
+ const chromeCandidates = [
35
+ process.env.CHROME_BIN,
36
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
37
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
38
+ "/usr/bin/google-chrome",
39
+ "/usr/bin/chromium",
40
+ ].filter(Boolean);
41
+
42
+ const FONT_SIZE = 15;
43
+ // Menlo first, then fonts that carry the Braille logo and Nerd Font icons.
44
+ const FONT_FAMILY = "Menlo, 'Apple Braille', 'Apple Symbols', 'IosevkaTerm Nerd Font', monospace";
45
+ // Dark palette close to the Gentleman terminal theme (xterm.js ITheme keys).
46
+ const THEME = {
47
+ background: "#06080f",
48
+ foreground: "#f3f6f9",
49
+ cursor: "#e0c15a",
50
+ selectionBackground: "#263356",
51
+ black: "#06080f",
52
+ red: "#cb7c94",
53
+ green: "#b7cc85",
54
+ yellow: "#ffe066",
55
+ blue: "#7fb4ca",
56
+ magenta: "#ff8dd7",
57
+ cyan: "#7aa89f",
58
+ white: "#f3f6f9",
59
+ brightBlack: "#8a8fa3",
60
+ brightRed: "#de8fa8",
61
+ brightGreen: "#d1e8a9",
62
+ brightYellow: "#fff7b1",
63
+ brightBlue: "#a3d4d5",
64
+ brightMagenta: "#ffaeeb",
65
+ brightCyan: "#a3d4d5",
66
+ brightWhite: "#ffffff",
67
+ };
68
+
69
+ function usage(message) {
70
+ if (message) console.error(`error: ${message}`);
71
+ console.error("usage: node scripts/shell-snapshot.mjs (--session <file.jsonl> | --latest-rich [--from <project-dir>]) [--cols 180] [--rows 50] [--out <dir>] [--wait <seconds>] [--cwd <dir>]");
72
+ process.exit(2);
73
+ }
74
+
75
+ function parseArgs(argv) {
76
+ const options = { session: undefined, latestRich: false, from: undefined, cols: 180, rows: 50, out: undefined, wait: 12, cwd: repoRoot };
77
+ for (let i = 0; i < argv.length; i += 1) {
78
+ const arg = argv[i];
79
+ const value = () => {
80
+ const next = argv[i + 1];
81
+ if (next === undefined) usage(`${arg} requires a value`);
82
+ i += 1;
83
+ return next;
84
+ };
85
+ const number = () => {
86
+ const parsed = Number(value());
87
+ if (!Number.isFinite(parsed) || parsed <= 0) usage(`${arg} requires a positive number`);
88
+ return parsed;
89
+ };
90
+ if (arg === "--session") options.session = resolve(value());
91
+ else if (arg === "--latest-rich") options.latestRich = true;
92
+ else if (arg === "--from") options.from = resolve(value());
93
+ else if (arg === "--cols") options.cols = Math.floor(number());
94
+ else if (arg === "--rows") options.rows = Math.floor(number());
95
+ else if (arg === "--out") options.out = resolve(value());
96
+ else if (arg === "--wait") options.wait = number();
97
+ else if (arg === "--cwd") options.cwd = resolve(value());
98
+ else if (arg === "--help" || arg === "-h") usage();
99
+ else usage(`unknown argument ${arg}`);
100
+ }
101
+ if (options.session && options.latestRich) usage("use either --session or --latest-rich, not both");
102
+ if (!options.session && !options.latestRich) usage("--session or --latest-rich is required");
103
+ if (options.from && !options.latestRich) usage("--from only applies to --latest-rich");
104
+ return options;
105
+ }
106
+
107
+ // Most recently modified session that has both todo and subagent_run tool calls.
108
+ function findLatestRichSession(projectDir) {
109
+ const richSessionsDir = sessionsDirFor(projectDir);
110
+ if (!existsSync(richSessionsDir)) usage(`sessions directory not found: ${richSessionsDir}`);
111
+ const candidates = readdirSync(richSessionsDir)
112
+ .filter((name) => name.endsWith(".jsonl"))
113
+ .map((name) => join(richSessionsDir, name))
114
+ .map((path) => ({ path, mtime: statSync(path).mtimeMs }))
115
+ .sort((a, b) => b.mtime - a.mtime);
116
+ for (const { path } of candidates) {
117
+ const text = readFileSync(path, "utf8");
118
+ if (text.includes('"name":"todo"') && text.includes('"name":"subagent_run"')) return path;
119
+ }
120
+ usage(`no session with both todo and subagent_run calls under ${richSessionsDir}`);
121
+ }
122
+
123
+ const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
124
+
125
+ // When this runs inside a Pi/Gentle Shell session (e.g. from an agent), the
126
+ // inherited PI_*, GENTLE_*, and HERDR_* variables would make the snapshot shell
127
+ // act as a subagent child (no sidebar rail) and report into the caller's pane.
128
+ // Start it like a fresh user terminal instead.
129
+ const INHERITED_SESSION_ENV = /^(PI_|GENTLE_PI_|GENTLE_SHELL_|HERDR_|TERM_PROGRAM|CLAUDE_AGENT_SDK|AI_AGENT$)/;
130
+ const cleanEnv = () => Object.fromEntries(Object.entries(process.env).filter(([key]) => !INHERITED_SESSION_ENV.test(key)));
131
+
132
+ function freePort() {
133
+ return new Promise((resolvePort, reject) => {
134
+ const server = createServer();
135
+ server.once("error", reject);
136
+ server.listen(0, "127.0.0.1", () => {
137
+ const { port } = server.address();
138
+ server.close(() => resolvePort(port));
139
+ });
140
+ });
141
+ }
142
+
143
+ async function waitFor(check, timeoutMs, label) {
144
+ const deadline = Date.now() + timeoutMs;
145
+ while (Date.now() < deadline) {
146
+ const result = await check();
147
+ if (result) return result;
148
+ await sleep(200);
149
+ }
150
+ throw new Error(`timed out waiting for ${label}`);
151
+ }
152
+
153
+ function runningPids(marker) {
154
+ const result = spawnSync("pgrep", ["-f", marker], { encoding: "utf8" });
155
+ return result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
156
+ }
157
+
158
+ // Minimal DevTools protocol client over one browser-level WebSocket.
159
+ async function connectCdp(url) {
160
+ const socket = new WebSocket(url);
161
+ await new Promise((resolveOpen, reject) => {
162
+ socket.addEventListener("open", resolveOpen, { once: true });
163
+ socket.addEventListener("error", () => reject(new Error(`cannot connect to ${url}`)), { once: true });
164
+ });
165
+ let nextId = 0;
166
+ const pending = new Map();
167
+ socket.addEventListener("message", (event) => {
168
+ const message = JSON.parse(event.data);
169
+ const waiter = message.id === undefined ? undefined : pending.get(message.id);
170
+ if (!waiter) return;
171
+ pending.delete(message.id);
172
+ if (message.error) waiter.reject(new Error(`${waiter.method}: ${message.error.message}`));
173
+ else waiter.resolve(message.result);
174
+ });
175
+ const send = (method, params = {}, sessionId) => new Promise((resolveSend, reject) => {
176
+ nextId += 1;
177
+ pending.set(nextId, { resolve: resolveSend, reject, method });
178
+ socket.send(JSON.stringify({ id: nextId, method, params, ...(sessionId ? { sessionId } : {}) }));
179
+ });
180
+ return { send, close: () => socket.close() };
181
+ }
182
+
183
+ const options = parseArgs(process.argv.slice(2));
184
+ const session = options.session ?? findLatestRichSession(options.from ?? options.cwd);
185
+ if (!existsSync(session)) usage(`session not found: ${session}`);
186
+ if (!existsSync(options.cwd)) usage(`cwd not found: ${options.cwd}`);
187
+ const chrome = chromeCandidates.find((path) => existsSync(path));
188
+ if (!chrome) usage("Google Chrome not found; set CHROME_BIN");
189
+ if (spawnSync("ttyd", ["--version"], { encoding: "utf8" }).status !== 0) usage("ttyd is not installed or not on PATH");
190
+
191
+ const scratch = mkdtempSync("/tmp/gentle-eyes.");
192
+ const sessionDir = join(scratch, "sessions");
193
+ const outDir = options.out ?? join(scratch, "shots");
194
+ const chromeProfile = join(scratch, "chrome-profile");
195
+ for (const dir of [sessionDir, outDir, chromeProfile]) mkdirSync(dir, { recursive: true });
196
+ const sourceBefore = statSync(session);
197
+
198
+ // run.sh waits for the browser to size the terminal before starting the shell,
199
+ // so the TUI starts at the final size instead of reflowing after a resize.
200
+ const runScript = join(scratch, "run.sh");
201
+ const goFile = join(scratch, "go");
202
+ const sizeFile = join(scratch, "size.txt");
203
+ writeFileSync(runScript, [
204
+ "#!/usr/bin/env bash",
205
+ `for _ in $(seq 1 600); do [ -f ${shellQuote(goFile)} ] && break; sleep 0.1; done`,
206
+ `cd ${shellQuote(options.cwd)} || exit 1`,
207
+ `stty size > ${shellQuote(sizeFile)}`,
208
+ "export COLORTERM=truecolor",
209
+ `exec node ${shellQuote(launcher)} --tui-mode fullscreen --fork ${shellQuote(session)} --session-dir ${shellQuote(sessionDir)}`,
210
+ "",
211
+ ].join("\n"));
212
+
213
+ const shots = {
214
+ loaded: join(outDir, "01-loaded.png"),
215
+ sidebar: join(outDir, "02-sidebar.png"),
216
+ exited: join(outDir, "03-exited.png"),
217
+ };
218
+ const written = [];
219
+ const notes = [];
220
+ let ttyd;
221
+ let browser;
222
+ let cdp;
223
+ let exitCode = 0;
224
+
225
+ try {
226
+ const ttydPort = await freePort();
227
+ ttyd = spawn("ttyd", [
228
+ "--port", String(ttydPort), "--interface", "127.0.0.1", "--writable", "--once",
229
+ "-t", "rendererType=canvas", "-t", "disableLeaveAlert=true", "-t", "disableResizeOverlay=true",
230
+ "-t", `fontSize=${FONT_SIZE}`, "-t", `fontFamily=${FONT_FAMILY}`, "-t", `theme=${JSON.stringify(THEME)}`,
231
+ "bash", runScript,
232
+ ], { stdio: "ignore", env: cleanEnv() });
233
+
234
+ browser = spawn(chrome, [
235
+ "--headless=new", "--remote-debugging-port=0", `--user-data-dir=${chromeProfile}`,
236
+ "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--hide-scrollbars", "about:blank",
237
+ ], { stdio: "ignore" });
238
+ const activePort = join(chromeProfile, "DevToolsActivePort");
239
+ const [debugPort, browserPath] = await waitFor(() => existsSync(activePort) && readFileSync(activePort, "utf8").trim().split("\n").length >= 2 && readFileSync(activePort, "utf8").trim().split("\n"), 20_000, "Chrome DevTools");
240
+ cdp = await connectCdp(`ws://127.0.0.1:${debugPort}${browserPath}`);
241
+ const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
242
+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
243
+ const page = (method, params) => cdp.send(method, params, sessionId);
244
+ const evaluate = async (expression) => (await page("Runtime.evaluate", { expression, returnByValue: true })).result.value;
245
+ const setViewport = (width, height) => page("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: false });
246
+ const screenshot = async (path) => {
247
+ const { data } = await page("Page.captureScreenshot", { format: "png" });
248
+ writeFileSync(path, Buffer.from(data, "base64"));
249
+ written.push(path);
250
+ };
251
+ const pressCtrl = async (key) => {
252
+ await evaluate("window.term && window.term.focus()");
253
+ const code = `Key${key.toUpperCase()}`;
254
+ const keyCode = key.toUpperCase().charCodeAt(0);
255
+ for (const type of ["rawKeyDown", "keyUp"]) {
256
+ await page("Input.dispatchKeyEvent", { type, modifiers: 2, key, code, windowsVirtualKeyCode: keyCode, nativeVirtualKeyCode: keyCode });
257
+ }
258
+ };
259
+
260
+ await setViewport(1600, 900);
261
+ await waitFor(async () => {
262
+ try {
263
+ await page("Page.navigate", { url: `http://127.0.0.1:${ttydPort}/` });
264
+ return true;
265
+ } catch {
266
+ return false;
267
+ }
268
+ }, 10_000, "ttyd page");
269
+ await waitFor(() => evaluate("Boolean(window.term && window.term.cols > 0)"), 15_000, "xterm.js terminal");
270
+
271
+ // Fit the viewport so xterm.js ends up exactly cols x rows; ttyd's fit addon
272
+ // resizes the pty on every viewport change.
273
+ let size = await evaluate("({ cols: term.cols, rows: term.rows, width: innerWidth, height: innerHeight })");
274
+ for (let attempt = 0; attempt < 8 && (size.cols !== options.cols || size.rows !== options.rows); attempt += 1) {
275
+ const width = Math.round(size.width + (options.cols - size.cols) * (size.width / size.cols)) + (size.cols > options.cols ? 0 : 1);
276
+ const height = Math.round(size.height + (options.rows - size.rows) * (size.height / size.rows)) + (size.rows > options.rows ? 0 : 1);
277
+ await setViewport(width, height);
278
+ await sleep(400);
279
+ size = await evaluate("({ cols: term.cols, rows: term.rows, width: innerWidth, height: innerHeight })");
280
+ }
281
+ if (size.cols !== options.cols || size.rows !== options.rows) notes.push(`terminal is ${size.cols}x${size.rows}, wanted ${options.cols}x${options.rows}`);
282
+ writeFileSync(goFile, "");
283
+
284
+ // tuiMode defaults to "fullscreen" in Pi, and the sidebar rail paints in
285
+ // fullscreen at >= 140 columns, so no key is needed to enter it.
286
+ await sleep(options.wait * 1000);
287
+ await screenshot(shots.loaded);
288
+ await sleep(3000);
289
+ await screenshot(shots.sidebar);
290
+ // Fullscreen mode runs on the alternate screen; "normal" means regular mode.
291
+ console.log(`screen buffer: ${await evaluate("term.buffer.active.type")}`);
292
+
293
+ // Ctrl+D quits on an empty editor; Ctrl+C twice is the fallback.
294
+ await pressCtrl("d");
295
+ const exited = async (ms) => {
296
+ try {
297
+ await waitFor(() => runningPids(sessionDir).length === 0, ms, "shell exit");
298
+ return true;
299
+ } catch {
300
+ return false;
301
+ }
302
+ };
303
+ if (!(await exited(5000))) {
304
+ await pressCtrl("c");
305
+ await sleep(500);
306
+ await pressCtrl("c");
307
+ if (!(await exited(5000))) notes.push("shell did not exit on Ctrl+D / Ctrl+C");
308
+ }
309
+ await sleep(500);
310
+ await screenshot(shots.exited);
311
+ await cdp.send("Browser.close").catch(() => {});
312
+ } catch (error) {
313
+ exitCode = 1;
314
+ console.error(`error: ${error instanceof Error ? error.message : String(error)}`);
315
+ } finally {
316
+ cdp?.close();
317
+ for (const child of [browser, ttyd]) if (child && child.exitCode === null) child.kill("SIGTERM");
318
+ }
319
+
320
+ // Anything still running from this run carries the unique scratch path in argv.
321
+ let leftovers = runningPids(sessionDir);
322
+ if (leftovers.length > 0) {
323
+ for (const pid of leftovers) spawnSync("kill", ["-TERM", pid]);
324
+ await sleep(1000);
325
+ leftovers = runningPids(sessionDir);
326
+ }
327
+
328
+ const sourceAfter = statSync(session);
329
+ const forks = readdirSync(sessionDir).filter((name) => name.endsWith(".jsonl"));
330
+ console.log(`session: ${session}`);
331
+ console.log(`fork: ${forks.length > 0 ? join(sessionDir, forks[0]) : "(none created)"}`);
332
+ console.log(`scratch: ${scratch}`);
333
+ console.log(`pty size at launch (rows cols): ${existsSync(sizeFile) ? readFileSync(sizeFile, "utf8").trim() : "unknown"}`);
334
+ if (sourceAfter.size !== sourceBefore.size || sourceAfter.mtimeMs !== sourceBefore.mtimeMs) {
335
+ notes.push("the source session changed during the run (another live writer?); this script only reads it");
336
+ }
337
+ if (leftovers.length > 0) notes.push(`gentle-shell processes still running: ${leftovers.join(", ")}`);
338
+ for (const note of notes) console.log(`note: ${note}`);
339
+ for (const path of written) console.log(`png: ${path}`);
340
+ process.exit(written.length > 0 ? exitCode : 1);