glimmervoid 0.49.1-next.562 → 0.49.1-next.563

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 (83) hide show
  1. package/dist/chunks/{main-Da0PTb94.js → main-Bou-NQrb.js} +599 -542
  2. package/dist/client/assets/{benchmark-panel-BVHKMNea.js → benchmark-panel-BWyqe9C6.js} +1 -1
  3. package/dist/client/assets/benchmark-panel-BWyqe9C6.js.br +0 -0
  4. package/dist/client/assets/{boards-view-HhY5BTvo.js → boards-view-CmK7zj_U.js} +1 -1
  5. package/dist/client/assets/boards-view-CmK7zj_U.js.br +0 -0
  6. package/dist/client/assets/{community-panel-vP_nMk4h.js → community-panel-BE67yfxH.js} +1 -1
  7. package/dist/client/assets/community-panel-BE67yfxH.js.br +0 -0
  8. package/dist/client/assets/{dialogs-DoylhFP2.js → dialogs-DCwXDxoa.js} +1 -1
  9. package/dist/client/assets/dialogs-DCwXDxoa.js.br +0 -0
  10. package/dist/client/assets/{doc-editor-ui-D9qebeKT.js → doc-editor-ui-4iVHCSpP.js} +1 -1
  11. package/dist/client/assets/doc-editor-ui-4iVHCSpP.js.br +0 -0
  12. package/dist/client/assets/{feature-hint-BzFWuFWa.js → feature-hint-D5oE-aJ_.js} +1 -1
  13. package/dist/client/assets/feature-hint-D5oE-aJ_.js.br +5 -0
  14. package/dist/client/assets/{first-run-checklist-DAtqcrx7.js → first-run-checklist-MfFcTlre.js} +1 -1
  15. package/dist/client/assets/first-run-checklist-MfFcTlre.js.br +0 -0
  16. package/dist/client/assets/{hooks-panel-ttiPw5mX.js → hooks-panel-BDo8UDry.js} +1 -1
  17. package/dist/client/assets/hooks-panel-BDo8UDry.js.br +0 -0
  18. package/dist/client/assets/{index-BL-sATDW.js → index-DLHYtIVw.js} +5 -5
  19. package/dist/client/assets/index-DLHYtIVw.js.br +0 -0
  20. package/dist/client/assets/{issues-panel-CguOvDpu.js → issues-panel-D6AOcqMa.js} +1 -1
  21. package/dist/client/assets/issues-panel-D6AOcqMa.js.br +0 -0
  22. package/dist/client/assets/{my-prs-panel-x4u6brZY.js → my-prs-panel-DAKQ4qdv.js} +1 -1
  23. package/dist/client/assets/my-prs-panel-DAKQ4qdv.js.br +0 -0
  24. package/dist/client/assets/{nyan-cat-BvkjcEkr.js → nyan-cat-CkrzNx8H.js} +1 -1
  25. package/dist/client/assets/nyan-cat-CkrzNx8H.js.br +0 -0
  26. package/dist/client/assets/{phone-shell-DplYi7zm.js → phone-shell-Dk8-8hM5.js} +1 -1
  27. package/dist/client/assets/phone-shell-Dk8-8hM5.js.br +0 -0
  28. package/dist/client/assets/{plan-face-DV_3puN9.js → plan-face-Dv7_f52D.js} +1 -1
  29. package/dist/client/assets/plan-face-Dv7_f52D.js.br +0 -0
  30. package/dist/client/assets/{plan-render-B06wF1gy.js → plan-render-BC2h4w06.js} +1 -1
  31. package/dist/client/assets/plan-render-BC2h4w06.js.br +0 -0
  32. package/dist/client/assets/{pr-queue-columns-vshP6-XL.js → pr-queue-columns-P9pZ9GaA.js} +1 -1
  33. package/dist/client/assets/pr-queue-columns-P9pZ9GaA.js.br +0 -0
  34. package/dist/client/assets/{radar-panel-D-9rdiZl.js → radar-panel-CSrczoRo.js} +1 -1
  35. package/dist/client/assets/radar-panel-CSrczoRo.js.br +0 -0
  36. package/dist/client/assets/{repo-roots-adder-bsJdFQXd.js → repo-roots-adder-4kVw0Ei2.js} +1 -1
  37. package/dist/client/assets/repo-roots-adder-4kVw0Ei2.js.br +0 -0
  38. package/dist/client/assets/{resume-dialog-DPLNb7-E.js → resume-dialog-BmLNFITR.js} +1 -1
  39. package/dist/client/assets/resume-dialog-BmLNFITR.js.br +0 -0
  40. package/dist/client/assets/{review-queue-panel-BpT17AQo.js → review-queue-panel-DB1Sx01J.js} +1 -1
  41. package/dist/client/assets/review-queue-panel-DB1Sx01J.js.br +0 -0
  42. package/dist/client/assets/{settings-panel-tzOaYZqM.js → settings-panel-DEzte2wI.js} +2 -2
  43. package/dist/client/assets/settings-panel-DEzte2wI.js.br +0 -0
  44. package/dist/client/assets/{shown-face-mvZhkdSz.js → shown-face-Chg226mm.js} +1 -1
  45. package/dist/client/assets/shown-face-Chg226mm.js.br +0 -0
  46. package/dist/client/assets/{team-review-queue-row-Dm8VDCKZ.js → team-review-queue-row-b6XgQgVA.js} +1 -1
  47. package/dist/client/assets/team-review-queue-row-b6XgQgVA.js.br +0 -0
  48. package/dist/client/assets/{trace-panel-C8cUm7SZ.js → trace-panel-SwIaXPO3.js} +1 -1
  49. package/dist/client/assets/trace-panel-SwIaXPO3.js.br +0 -0
  50. package/dist/client/assets/{usage-panel-Bnsh7Wbe.js → usage-panel-CY_OKKZb.js} +1 -1
  51. package/dist/client/assets/usage-panel-CY_OKKZb.js.br +0 -0
  52. package/dist/client/assets/{your-day-tip-Dm00jvPb.js → your-day-tip-DOwWmNmu.js} +1 -1
  53. package/dist/client/assets/your-day-tip-DOwWmNmu.js.br +0 -0
  54. package/dist/client/index.html +1 -1
  55. package/dist/client/index.html.br +0 -0
  56. package/dist/server/index.js +1 -1
  57. package/package.json +1 -1
  58. package/dist/client/assets/benchmark-panel-BVHKMNea.js.br +0 -0
  59. package/dist/client/assets/boards-view-HhY5BTvo.js.br +0 -0
  60. package/dist/client/assets/community-panel-vP_nMk4h.js.br +0 -0
  61. package/dist/client/assets/dialogs-DoylhFP2.js.br +0 -0
  62. package/dist/client/assets/doc-editor-ui-D9qebeKT.js.br +0 -0
  63. package/dist/client/assets/feature-hint-BzFWuFWa.js.br +0 -0
  64. package/dist/client/assets/first-run-checklist-DAtqcrx7.js.br +0 -0
  65. package/dist/client/assets/hooks-panel-ttiPw5mX.js.br +0 -0
  66. package/dist/client/assets/index-BL-sATDW.js.br +0 -0
  67. package/dist/client/assets/issues-panel-CguOvDpu.js.br +0 -0
  68. package/dist/client/assets/my-prs-panel-x4u6brZY.js.br +0 -0
  69. package/dist/client/assets/nyan-cat-BvkjcEkr.js.br +0 -0
  70. package/dist/client/assets/phone-shell-DplYi7zm.js.br +0 -0
  71. package/dist/client/assets/plan-face-DV_3puN9.js.br +0 -0
  72. package/dist/client/assets/plan-render-B06wF1gy.js.br +0 -0
  73. package/dist/client/assets/pr-queue-columns-vshP6-XL.js.br +0 -0
  74. package/dist/client/assets/radar-panel-D-9rdiZl.js.br +0 -0
  75. package/dist/client/assets/repo-roots-adder-bsJdFQXd.js.br +0 -0
  76. package/dist/client/assets/resume-dialog-DPLNb7-E.js.br +0 -0
  77. package/dist/client/assets/review-queue-panel-BpT17AQo.js.br +0 -0
  78. package/dist/client/assets/settings-panel-tzOaYZqM.js.br +0 -0
  79. package/dist/client/assets/shown-face-mvZhkdSz.js.br +0 -0
  80. package/dist/client/assets/team-review-queue-row-Dm8VDCKZ.js.br +0 -0
  81. package/dist/client/assets/trace-panel-C8cUm7SZ.js.br +0 -0
  82. package/dist/client/assets/usage-panel-Bnsh7Wbe.js.br +0 -0
  83. package/dist/client/assets/your-day-tip-Dm00jvPb.js.br +0 -0
@@ -2604,148 +2604,6 @@ function createHostUrlOpener({ platform = process.platform, spawnProcess = spawn
2604
2604
  };
2605
2605
  }
2606
2606
  //#endregion
2607
- //#region session/core/snapshot-projection.ts
2608
- function projectSessionCard(source, { id, name }) {
2609
- const card = {
2610
- id,
2611
- session: name,
2612
- taskTitle: source.taskTitle ?? null,
2613
- taskTitleIsCustom: source.taskTitleIsCustom ?? false,
2614
- path: source.path,
2615
- agent: source.agentId,
2616
- state: source.state,
2617
- stateSince: source.stateSince,
2618
- skipPerms: !!source.dangerouslySkipPermissions,
2619
- saneYolo: !!source.saneYolo,
2620
- worktree: !!source.isWorktree,
2621
- resumeSessionId: source.resumeSessionId || null,
2622
- ...source.isWorkspace ? { workspace: true } : {},
2623
- ...source.remoteWorkspace ? { remoteWorkspace: source.remoteWorkspace } : {},
2624
- ...source.linkedPrs?.length ? { linkedPrs: source.linkedPrs } : {},
2625
- ...source.ownerId ? { ownerId: source.ownerId } : {}
2626
- };
2627
- if (source.ephemeral === void 0) return card;
2628
- return {
2629
- ...card,
2630
- ephemeral: source.ephemeral
2631
- };
2632
- }
2633
- function projectSessionSnapshots(source) {
2634
- const wire = {
2635
- id: source.id,
2636
- name: source.name,
2637
- taskTitle: source.taskTitle ?? null,
2638
- taskTitleIsCustom: source.taskTitleIsCustom ?? false,
2639
- path: source.path,
2640
- agent: source.agent,
2641
- state: source.state,
2642
- stateSince: source.stateSince,
2643
- dangerouslySkipPermissions: source.dangerouslySkipPermissions,
2644
- saneYolo: !!source.saneYolo,
2645
- ephemeral: source.ephemeral,
2646
- ownerId: source.ownerId ?? null,
2647
- isWorktree: source.isWorktree,
2648
- isWorkspace: source.isWorkspace,
2649
- remoteWorkspace: source.remoteWorkspace ?? null,
2650
- resumeSessionId: source.resumeSessionId,
2651
- activeAgents: source.activeAgents,
2652
- awaitingBackgroundTasks: source.awaitingBackgroundTasks,
2653
- pendingPromptKind: source.pendingPromptKind,
2654
- hasPlan: source.hasPlan,
2655
- mergeStatus: source.mergeStatus,
2656
- mergeReason: source.mergeReason,
2657
- worktreeNotice: source.worktreeNotice,
2658
- failureReason: source.failureReason ?? null,
2659
- unseenOutcome: source.unseenOutcome ?? null,
2660
- effectiveBase: source.effectiveBase ?? null,
2661
- linkedPrs: source.linkedPrs,
2662
- coherenceHooks: source.coherenceHooks ?? null,
2663
- auditLog: source.auditLog.slice(-100)
2664
- };
2665
- return {
2666
- wire,
2667
- debug: {
2668
- state: wire.state,
2669
- transitions: wire.auditLog.slice(-5).map((entry) => ({
2670
- from: entry.from,
2671
- to: entry.to,
2672
- event: entry.event,
2673
- timestamp: entry.timestamp,
2674
- detail: entry.detail
2675
- })),
2676
- detection: source.detection,
2677
- decisions: source.decisions.slice(-15)
2678
- }
2679
- };
2680
- }
2681
- //#endregion
2682
- //#region session/core/session-pr-links-core.ts
2683
- function comparableLinkKey(link) {
2684
- return `${link.repo}#${link.number}`.toLowerCase();
2685
- }
2686
- function isUnlinked(current, comparableKey) {
2687
- return current.unlinkedKeys.some((unlinkedKey) => unlinkedKey.toLowerCase() === comparableKey);
2688
- }
2689
- function seedSessionPrLinks(persisted) {
2690
- return persisted ?? {
2691
- links: [],
2692
- unlinkedKeys: []
2693
- };
2694
- }
2695
- function mergeSessionPrLink(current, incoming) {
2696
- const incomingKey = comparableLinkKey(incoming);
2697
- if (isUnlinked(current, incomingKey)) return current;
2698
- if (current.links.some((link) => comparableLinkKey(link) === incomingKey)) return current;
2699
- const firstOlderIndex = current.links.findIndex((link) => link.linkedAt <= incoming.linkedAt);
2700
- const insertAt = firstOlderIndex === -1 ? current.links.length : firstOlderIndex;
2701
- if (insertAt >= 20) return current;
2702
- return {
2703
- links: [
2704
- ...current.links.slice(0, insertAt),
2705
- incoming,
2706
- ...current.links.slice(insertAt)
2707
- ].slice(0, 20),
2708
- unlinkedKeys: current.unlinkedKeys
2709
- };
2710
- }
2711
- function withManualPrLink(current, link) {
2712
- const key = comparableLinkKey(link);
2713
- if (!isUnlinked(current, key)) return mergeSessionPrLink(current, link);
2714
- return mergeSessionPrLink({
2715
- links: current.links,
2716
- unlinkedKeys: current.unlinkedKeys.filter((unlinkedKey) => unlinkedKey.toLowerCase() !== key)
2717
- }, link);
2718
- }
2719
- function withoutPrLink(current, pullRequestKey) {
2720
- const comparableKey = pullRequestKey.toLowerCase();
2721
- const links = current.links.filter((link) => comparableLinkKey(link) !== comparableKey);
2722
- const isAlreadyUnlinked = isUnlinked(current, comparableKey);
2723
- if (isAlreadyUnlinked && links.length === current.links.length) return current;
2724
- return {
2725
- links,
2726
- unlinkedKeys: isAlreadyUnlinked ? current.unlinkedKeys : [...current.unlinkedKeys, pullRequestKey]
2727
- };
2728
- }
2729
- function manualPrLink(pullRequestKey, knownPrs, nowMs) {
2730
- const separatorIndex = pullRequestKey.lastIndexOf("#");
2731
- const repo = pullRequestKey.slice(0, separatorIndex);
2732
- const number = Number(pullRequestKey.slice(separatorIndex + 1));
2733
- const comparableKey = pullRequestKey.toLowerCase();
2734
- const canonicalPr = knownPrs.find((pr) => pr.key.toLowerCase() === comparableKey) ?? {
2735
- repo,
2736
- number,
2737
- url: `https://github.com/${repo}/pull/${number}`
2738
- };
2739
- const parsed = LinkedPr.safeParse({
2740
- repo: canonicalPr.repo,
2741
- number: canonicalPr.number,
2742
- url: canonicalPr.url,
2743
- source: "manual",
2744
- linkedAt: nowMs
2745
- });
2746
- return parsed.success ? parsed.data : null;
2747
- }
2748
- //#endregion
2749
2607
  //#region server/core/child-channel-core.ts
2750
2608
  var MAX_UNREAD_ENTRIES_PER_SIDE = 50;
2751
2609
  var MAX_ENTRY_CHARS = 4e3;
@@ -2908,336 +2766,35 @@ function canSubmitWake({ recipientState, pastedAt, lastOperatorInputAt }) {
2908
2766
  return WAKEABLE_STATES.includes(recipientState);
2909
2767
  }
2910
2768
  //#endregion
2911
- //#region server/prune-files.ts
2912
- var MS_PER_DAY = 864e5;
2913
- function idForEntry(entry, suffixes) {
2914
- for (const suffix of suffixes) {
2915
- if (suffix.length === 0) return entry;
2916
- if (entry.endsWith(suffix)) return entry.slice(0, -suffix.length);
2917
- }
2918
- return null;
2919
- }
2920
- async function pruneAgedFiles({ directory, suffixes, retainDays, now = Date.now(), isRetainedId = () => false, entryMode = "file", fsPromises = fs.promises }) {
2921
- let entries;
2922
- try {
2923
- entries = await fsPromises.readdir(directory);
2924
- } catch {
2925
- return [];
2769
+ //#region server/agent-api/agent-api-context.ts
2770
+ var AGENT_LANE_TAG = "agent-spawn";
2771
+ //#endregion
2772
+ //#region server/agent-api/child-channels.ts
2773
+ var WAKE_SUBMIT_DELAY_MS = 150;
2774
+ function createChildChannels(runtime) {
2775
+ const { listAllSessions, logger, setTimeoutFn, clearTimeoutFn, now, channelsByChildId, linksByChildId, parentsWithChannelCleanup, sessionsWithOperatorWatch, lastOperatorInputAtBySession, childIdsToDiscard, endCauseByChildId } = runtime;
2776
+ function noteEndCause(childId, cause) {
2777
+ if (!endCauseByChildId.has(childId)) endCauseByChildId.set(childId, cause);
2926
2778
  }
2927
- const cutoff = now - retainDays * MS_PER_DAY;
2928
- const removedIds = [];
2929
- for (const entry of entries) {
2930
- const id = idForEntry(entry, suffixes);
2931
- if (!id || isRetainedId(id)) continue;
2932
- const filePath = path.join(directory, entry);
2933
- try {
2934
- if ((await fsPromises.stat(filePath)).mtimeMs >= cutoff) continue;
2935
- if (!await recordSweptPath({
2936
- cause: "aged-files",
2937
- kind: entryMode === "directory" ? "folder" : "file",
2938
- path: filePath,
2939
- checksPassed: [`untouched-${retainDays}d`]
2940
- })) continue;
2941
- if (entryMode === "directory") await fsPromises.rm(filePath, {
2942
- recursive: true,
2943
- force: true
2944
- });
2945
- if (entryMode === "file") await fsPromises.unlink(filePath);
2946
- removedIds.push(id);
2947
- } catch {}
2779
+ function forgetLink(childId) {
2780
+ const link = linksByChildId.get(childId);
2781
+ if (link) for (const timer of link.retryTimersBySide.values()) clearTimeoutFn(timer);
2782
+ linksByChildId.delete(childId);
2783
+ channelsByChildId.delete(childId);
2948
2784
  }
2949
- return removedIds;
2950
- }
2951
- //#endregion
2952
- //#region server/session-temp/session-temp.ts
2953
- var SESSION_TEMP_FOLDER = "guardrails-temp";
2954
- var SESSION_TEMP_LOCK_FOLDER = "session-temp-locks";
2955
- var SESSION_ID_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
2956
- var SESSION_TEMP_RETAIN_DAYS = 7;
2957
- function sessionTempLockFolder(glimmervoidHome) {
2958
- return path.join(glimmervoidHome, SESSION_TEMP_LOCK_FOLDER);
2959
- }
2960
- async function deleteSessionTempFolderOnceUnheld(lockFolder, sessionId, sessionTempFolder, keepWhenNoLockFiles, log) {
2961
- let trashFolder = null;
2962
- try {
2963
- trashFolder = trashSessionTempFolderOnceUnheld(lockFolder, sessionId, sessionTempFolder, { keepWhenNoLockFiles });
2964
- } catch (error) {
2965
- log.warn(`[session-temp] could not delete session temp folder ${sessionTempFolder}: ${errorMessage(error)}`);
2966
- return;
2785
+ function forgetChannelsOf(parent) {
2786
+ for (const [childId, channel] of channelsByChildId) if (channel.parentId === parent.id) forgetLink(childId);
2967
2787
  }
2968
- if (trashFolder === null) return;
2969
- if (!await recordSweptPath({
2970
- cause: "session-temp",
2971
- kind: "folder",
2972
- path: sessionTempFolder,
2973
- sessionId,
2974
- checksPassed: ["no-lock-held"],
2975
- log
2976
- })) {
2977
- await rename(trashFolder, sessionTempFolder).catch((error) => {
2978
- log.warn(`[session-temp] could not move session temp folder ${trashFolder} back to ${sessionTempFolder}: ${errorMessage(error)}`);
2979
- });
2980
- return;
2788
+ function recipientOf(link, side) {
2789
+ return side === "toParent" ? link.parent : link.child;
2981
2790
  }
2982
- await rm(trashFolder, {
2983
- recursive: true,
2984
- force: true
2985
- }).catch((error) => {
2986
- log.warn(`[session-temp] could not delete session temp folder ${trashFolder}: ${errorMessage(error)}`);
2987
- });
2988
- }
2989
- async function pruneLeftoverSessionTempFolders(glimmervoidHome, liveSessionIds, log = console) {
2990
- const lockFolder = sessionTempLockFolder(glimmervoidHome);
2991
- const lockEntryNames = await readdir(lockFolder).catch((error) => {
2992
- if (isMissingFileError(error)) return [];
2993
- log.warn(`[session-temp] kept every session temp folder because the lock list could not be read: ${errorMessage(error)}`);
2994
- return null;
2995
- });
2996
- if (lockEntryNames === null) return;
2997
- const sessionTempRoot = path.join(glimmervoidHome, SESSION_TEMP_FOLDER);
2998
- const sessionIdsWithLockFiles = new Set(lockEntryNames.map(sessionIdOfLockFile).filter((sessionId) => sessionId !== null));
2999
- for (const sessionId of sessionIdsWithLockFiles) {
3000
- if (liveSessionIds.has(sessionId)) continue;
3001
- await deleteSessionTempFolderOnceUnheld(lockFolder, sessionId, path.join(sessionTempRoot, sessionId), true, log);
3002
- }
3003
- await pruneAgedFiles({
3004
- directory: sessionTempRoot,
3005
- suffixes: [""],
3006
- retainDays: SESSION_TEMP_RETAIN_DAYS,
3007
- entryMode: "directory",
3008
- isRetainedId: (id) => liveSessionIds.has(id) || sessionIdsWithLockFiles.has(id)
3009
- });
3010
- }
3011
- function sessionTempFolderFor(sessionId) {
3012
- if (!SESSION_ID_SHAPE.test(sessionId)) return null;
3013
- return path.join(glimmervoidHomeDir$1(), SESSION_TEMP_FOLDER, sessionId);
3014
- }
3015
- function ensureSessionTempFolder(sessionId) {
3016
- const sessionTempFolder = sessionTempFolderFor(sessionId);
3017
- if (!sessionTempFolder) return null;
3018
- createHeldSessionTempFolder(sessionTempLockFolder(glimmervoidHomeDir$1()), sessionId, sessionTempFolder);
3019
- return sessionTempFolder;
3020
- }
3021
- async function removeSessionTempFolder(sessionId, log = console) {
3022
- const sessionTempFolder = sessionTempFolderFor(sessionId);
3023
- if (!sessionTempFolder) return;
3024
- const lockFolder = sessionTempLockFolder(glimmervoidHomeDir$1());
3025
- let didHoldSessionLock = true;
3026
- try {
3027
- didHoldSessionLock = releaseSessionLock(lockFolder, sessionId);
3028
- } catch (error) {
3029
- log.warn(`[session-temp] could not delete the lock of session ${sessionId}: ${errorMessage(error)}`);
3030
- }
3031
- if (!didHoldSessionLock) return;
3032
- await deleteSessionTempFolderOnceUnheld(lockFolder, sessionId, sessionTempFolder, false, log);
3033
- }
3034
- //#endregion
3035
- //#region server/lanes/ephemeral-session.ts
3036
- var JOB_RESULT_FILENAME = "result.json";
3037
- var ABORT_REAP_CAP_MS = 3e3;
3038
- async function awaitSessionExit(sess, { signal = null, spawnGate = null, reapCapMs = ABORT_REAP_CAP_MS } = {}) {
3039
- let onAbort = null;
3040
- try {
3041
- await new Promise((resolve, reject) => {
3042
- let settled = false;
3043
- const done = () => {
3044
- if (settled) return;
3045
- settled = true;
3046
- resolve();
3047
- };
3048
- const fail = (error) => {
3049
- if (settled) return;
3050
- settled = true;
3051
- reject(error);
3052
- };
3053
- sess.on("exit", done);
3054
- sess.on("error", fail);
3055
- if (signal) {
3056
- onAbort = () => {
3057
- try {
3058
- sess.destroy();
3059
- } catch {}
3060
- if (!sess._killReap) {
3061
- done();
3062
- return;
3063
- }
3064
- awaitBounded([sess._killReap], { capMs: reapCapMs }).then(done, done);
3065
- };
3066
- if (signal.aborted) onAbort();
3067
- if (!signal.aborted) signal.addEventListener("abort", onAbort, { once: true });
3068
- }
3069
- const run = () => signal?.aborted ? void 0 : sess.start();
3070
- const activeSpawnGate = spawnGate;
3071
- (activeSpawnGate ? activeSpawnGate.run(run) : Promise.resolve().then(run)).catch(fail);
3072
- });
3073
- } finally {
3074
- if (signal && onAbort) try {
3075
- signal.removeEventListener("abort", onAbort);
3076
- } catch {}
3077
- }
3078
- }
3079
- async function raceWithAbort({ start, timeoutMs, onTimeout, onEmpty, setTimeoutFn = DEFAULT_TIMER_FNS.setTimeoutFn, clearTimeoutFn = DEFAULT_TIMER_FNS.clearTimeoutFn, onPending = null }) {
3080
- const controller = new AbortController();
3081
- let handle = null;
3082
- const timeout = new Promise((resolve) => {
3083
- handle = setTimeoutFn(() => {
3084
- controller.abort();
3085
- resolve(onTimeout());
3086
- }, timeoutMs);
3087
- unrefTimer(handle);
3088
- });
3089
- const started = start(controller.signal);
3090
- if (typeof onPending === "function") onPending(started);
3091
- const result = await Promise.race([started, timeout]);
3092
- if (handle) clearTimeoutFn(handle);
3093
- return result || onEmpty();
3094
- }
3095
- function drainPending(pending, { capMs = 3500 } = {}) {
3096
- if (!pending) return Promise.resolve();
3097
- return awaitBounded([pending], { capMs }).then(() => {});
3098
- }
3099
- async function createJobResultFile(prefix) {
3100
- const safePrefix = String(prefix).replace(/[^\w.-]+/g, "-");
3101
- const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), `${safePrefix}-`));
3102
- return {
3103
- path: path.join(dir, JOB_RESULT_FILENAME),
3104
- async cleanup() {
3105
- try {
3106
- await fs.promises.rm(dir, {
3107
- recursive: true,
3108
- force: true
3109
- });
3110
- } catch {}
3111
- }
3112
- };
3113
- }
3114
- function readResultFile(resultPath, allowed, decorate = null, { maxBytes = null, validate = null } = {}) {
3115
- if (allowed && validate) throw new TypeError("readResultFile accepts allowed or validate, not both");
3116
- const failedRead = (kind, reason) => ({
3117
- ok: false,
3118
- kind,
3119
- reason,
3120
- verdict: "ERROR",
3121
- summary: reason
3122
- });
3123
- try {
3124
- const fileDescriptor = fs.openSync(resultPath, "r");
3125
- const chunks = [];
3126
- const chunk = Buffer.allocUnsafe(65536);
3127
- let totalBytesRead = 0;
3128
- try {
3129
- while (true) {
3130
- const bytesRead = fs.readSync(fileDescriptor, chunk, 0, chunk.length, null);
3131
- if (bytesRead === 0) break;
3132
- totalBytesRead += bytesRead;
3133
- if (maxBytes !== null && totalBytesRead > maxBytes) return failedRead("too-large", "result file is too large");
3134
- chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
3135
- }
3136
- } finally {
3137
- fs.closeSync(fileDescriptor);
3138
- }
3139
- let obj;
3140
- try {
3141
- obj = JSON.parse(Buffer.concat(chunks).toString("utf8"));
3142
- } catch {
3143
- return failedRead("invalid-json", "invalid JSON in result file");
3144
- }
3145
- if (validate) {
3146
- const validated = validate(obj);
3147
- if (validated && validated.ok !== false) return { ...validated };
3148
- return failedRead("rejected", validated?.summary || "result file was rejected");
3149
- }
3150
- const verdict = String(obj.verdict || "").toUpperCase();
3151
- if (!allowed || !allowed.has(verdict)) return failedRead("rejected", "invalid verdict in result file");
3152
- const result = {
3153
- verdict,
3154
- summary: String(obj.summary || "")
3155
- };
3156
- if (!decorate) return result;
3157
- return {
3158
- ...result,
3159
- ...decorate(obj)
3160
- };
3161
- } catch {
3162
- return failedRead("missing", "no result file");
3163
- } finally {
3164
- try {
3165
- fs.rmSync(resultPath, { force: true });
3166
- } catch {}
3167
- }
3168
- }
3169
- function registerEphemeralSession({ map, id, sess, closeSessionDataClients, logPrefix, name, recordLane = null }) {
3170
- map.set(id, sess);
3171
- if (typeof recordLane === "function") sess.on("claude-session-id", ({ id: claudeSessionId, vendor }) => recordLane(claudeSessionId, logPrefix, vendor));
3172
- sess.on("error", (err) => console.error(`[${logPrefix} ${name}] error: ${err.message}`));
3173
- const removeFromMap = () => {
3174
- if (map.get(id) === sess) {
3175
- map.delete(id);
3176
- closeSessionDataClients(id);
3177
- }
3178
- };
3179
- const releaseAfterListeners = () => {
3180
- removeFromMap();
3181
- setImmediate(() => sess.destroy());
3182
- };
3183
- sess.on("exit", releaseAfterListeners);
3184
- sess.on("error", () => {
3185
- if (sess.hasLivePty !== false) return;
3186
- releaseAfterListeners();
3187
- });
3188
- let hasScheduledTempFolderRemoval = false;
3189
- const removeTempFolderAfterReap = () => {
3190
- if (hasScheduledTempFolderRemoval) return;
3191
- hasScheduledTempFolderRemoval = true;
3192
- Promise.resolve(sess._awaitPendingReaps?.()).catch(() => {}).then(() => {
3193
- if (map.has(id)) return;
3194
- return removeSessionTempFolder(id);
3195
- });
3196
- };
3197
- const origDestroy = sess.destroy.bind(sess);
3198
- sess.destroy = () => {
3199
- origDestroy();
3200
- removeFromMap();
3201
- removeTempFolderAfterReap();
3202
- };
3203
- }
3204
- //#endregion
3205
- //#region server/agent-api-wiring.ts
3206
- var AGENT_LANE_TAG = "agent-spawn";
3207
- var SPAWN_FAILED_MESSAGE = "could not spawn the session";
3208
- var PARENT_ENDED_MESSAGE = "this session ended before its child could start, so nothing was spawned";
3209
- var BYTES_PER_MEGABYTE = 1048576;
3210
- var WAKE_SUBMIT_DELAY_MS = 150;
3211
- function createAgentApiWiring({ config, agentSessions, listAllSessions, listBoardSessions, makeSession, wireSessionEvents, closeSessionDataClients, broadcastControl, spawnGate, sessionDocs, recordLane = null, memoryAdmission = null, operatorState = null, whiteboards = null, coderWorkspaceStatus = () => null, logger = console, setTimeoutFn = DEFAULT_TIMER_FNS.setTimeoutFn, clearTimeoutFn = DEFAULT_TIMER_FNS.clearTimeoutFn, now = Date.now }) {
3212
- const channelsByChildId = /* @__PURE__ */ new Map();
3213
- const linksByChildId = /* @__PURE__ */ new Map();
3214
- const parentsWithChannelCleanup = /* @__PURE__ */ new WeakSet();
3215
- const sessionsWithOperatorWatch = /* @__PURE__ */ new WeakSet();
3216
- const lastOperatorInputAtBySession = /* @__PURE__ */ new WeakMap();
3217
- const childIdsToDiscard = /* @__PURE__ */ new Set();
3218
- const endCauseByChildId = /* @__PURE__ */ new Map();
3219
- function noteEndCause(childId, cause) {
3220
- if (!endCauseByChildId.has(childId)) endCauseByChildId.set(childId, cause);
3221
- }
3222
- function forgetLink(childId) {
3223
- const link = linksByChildId.get(childId);
3224
- if (link) for (const timer of link.retryTimersBySide.values()) clearTimeoutFn(timer);
3225
- linksByChildId.delete(childId);
3226
- channelsByChildId.delete(childId);
3227
- }
3228
- function forgetChannelsOf(parent) {
3229
- for (const [childId, channel] of channelsByChildId) if (channel.parentId === parent.id) forgetLink(childId);
3230
- }
3231
- function recipientOf(link, side) {
3232
- return side === "toParent" ? link.parent : link.child;
3233
- }
3234
- function scheduleWakeRetry(childId, link, side, retryInMs) {
3235
- const earlierTimer = link.retryTimersBySide.get(side);
3236
- if (earlierTimer) clearTimeoutFn(earlierTimer);
3237
- link.retryTimersBySide.set(side, unrefTimer(setTimeoutFn(() => {
3238
- link.retryTimersBySide.delete(side);
3239
- wakeRecipient(childId, side);
3240
- }, retryInMs)));
2791
+ function scheduleWakeRetry(childId, link, side, retryInMs) {
2792
+ const earlierTimer = link.retryTimersBySide.get(side);
2793
+ if (earlierTimer) clearTimeoutFn(earlierTimer);
2794
+ link.retryTimersBySide.set(side, unrefTimer(setTimeoutFn(() => {
2795
+ link.retryTimersBySide.delete(side);
2796
+ wakeRecipient(childId, side);
2797
+ }, retryInMs)));
3241
2798
  }
3242
2799
  function typeWakeLine(link, channel, side, recipient) {
3243
2800
  if (!recipient.pasteText(describeWakeLine(channel, side)).ok) return;
@@ -3409,51 +2966,439 @@ function createAgentApiWiring({ config, agentSessions, listAllSessions, listBoar
3409
2966
  at: now(),
3410
2967
  wakes: true
3411
2968
  });
3412
- return;
2969
+ return;
2970
+ }
2971
+ if (cause === "parent-closed") return;
2972
+ const kind = worktree || worktreeAtStart ? "discarded" : "none";
2973
+ const hasParentRead = linksByChildId.get(child.id)?.hasParentRead ?? false;
2974
+ post(child.id, "toParent", {
2975
+ author: "glimmervoid",
2976
+ text: describeChildEndNote(childName, cause, { kind }),
2977
+ at: now(),
2978
+ wakes: !hasParentRead
2979
+ });
2980
+ } catch (error) {
2981
+ logger.warn(`[${AGENT_LANE_TAG} ${childName}] could not settle the worktree: ${errorMessage(error)}`);
2982
+ }
2983
+ }
2984
+ function post(childId, side, entry) {
2985
+ const channel = channelsByChildId.get(childId);
2986
+ if (!channel) return;
2987
+ channelsByChildId.set(childId, postToChannel(channel, side, entry));
2988
+ wakeRecipient(childId, side);
2989
+ }
2990
+ function drain(childId, side) {
2991
+ const channel = channelsByChildId.get(childId);
2992
+ if (!channel) return null;
2993
+ const { channel: drainedChannel, drained } = drainChannel(channel, side);
2994
+ channelsByChildId.set(childId, drainedChannel);
2995
+ const link = linksByChildId.get(childId);
2996
+ if (link && side === "toParent" && drained.entries.length > 0) link.hasParentRead = true;
2997
+ return {
2998
+ sessionId: side === "toParent" ? channel.childId : channel.parentId,
2999
+ name: side === "toParent" ? channel.childName : listAllSessions().find((session) => session.id === channel.parentId)?.name ?? channel.parentId,
3000
+ entries: drained.entries.map(({ author, at, text }) => ({
3001
+ from: author,
3002
+ at,
3003
+ text
3004
+ })),
3005
+ dropped: drained.droppedCount
3006
+ };
3007
+ }
3008
+ function ownedChannels(parent) {
3009
+ return [...channelsByChildId.values()].filter((channel) => channel.parentId === parent.id);
3010
+ }
3011
+ function findChildOf(parent, target) {
3012
+ return findOwnedChild(ownedChannels(parent), parent.id, target);
3013
+ }
3014
+ return {
3015
+ noteEndCause,
3016
+ forgetLink,
3017
+ openChildChannel,
3018
+ settleChildWorktree,
3019
+ post,
3020
+ drain,
3021
+ ownedChannels,
3022
+ findChildOf
3023
+ };
3024
+ }
3025
+ //#endregion
3026
+ //#region session/core/snapshot-projection.ts
3027
+ function projectSessionCard(source, { id, name }) {
3028
+ const card = {
3029
+ id,
3030
+ session: name,
3031
+ taskTitle: source.taskTitle ?? null,
3032
+ taskTitleIsCustom: source.taskTitleIsCustom ?? false,
3033
+ path: source.path,
3034
+ agent: source.agentId,
3035
+ state: source.state,
3036
+ stateSince: source.stateSince,
3037
+ skipPerms: !!source.dangerouslySkipPermissions,
3038
+ saneYolo: !!source.saneYolo,
3039
+ worktree: !!source.isWorktree,
3040
+ resumeSessionId: source.resumeSessionId || null,
3041
+ ...source.isWorkspace ? { workspace: true } : {},
3042
+ ...source.remoteWorkspace ? { remoteWorkspace: source.remoteWorkspace } : {},
3043
+ ...source.linkedPrs?.length ? { linkedPrs: source.linkedPrs } : {},
3044
+ ...source.ownerId ? { ownerId: source.ownerId } : {}
3045
+ };
3046
+ if (source.ephemeral === void 0) return card;
3047
+ return {
3048
+ ...card,
3049
+ ephemeral: source.ephemeral
3050
+ };
3051
+ }
3052
+ function projectSessionSnapshots(source) {
3053
+ const wire = {
3054
+ id: source.id,
3055
+ name: source.name,
3056
+ taskTitle: source.taskTitle ?? null,
3057
+ taskTitleIsCustom: source.taskTitleIsCustom ?? false,
3058
+ path: source.path,
3059
+ agent: source.agent,
3060
+ state: source.state,
3061
+ stateSince: source.stateSince,
3062
+ dangerouslySkipPermissions: source.dangerouslySkipPermissions,
3063
+ saneYolo: !!source.saneYolo,
3064
+ ephemeral: source.ephemeral,
3065
+ ownerId: source.ownerId ?? null,
3066
+ isWorktree: source.isWorktree,
3067
+ isWorkspace: source.isWorkspace,
3068
+ remoteWorkspace: source.remoteWorkspace ?? null,
3069
+ resumeSessionId: source.resumeSessionId,
3070
+ activeAgents: source.activeAgents,
3071
+ awaitingBackgroundTasks: source.awaitingBackgroundTasks,
3072
+ pendingPromptKind: source.pendingPromptKind,
3073
+ hasPlan: source.hasPlan,
3074
+ mergeStatus: source.mergeStatus,
3075
+ mergeReason: source.mergeReason,
3076
+ worktreeNotice: source.worktreeNotice,
3077
+ failureReason: source.failureReason ?? null,
3078
+ unseenOutcome: source.unseenOutcome ?? null,
3079
+ effectiveBase: source.effectiveBase ?? null,
3080
+ linkedPrs: source.linkedPrs,
3081
+ coherenceHooks: source.coherenceHooks ?? null,
3082
+ auditLog: source.auditLog.slice(-100)
3083
+ };
3084
+ return {
3085
+ wire,
3086
+ debug: {
3087
+ state: wire.state,
3088
+ transitions: wire.auditLog.slice(-5).map((entry) => ({
3089
+ from: entry.from,
3090
+ to: entry.to,
3091
+ event: entry.event,
3092
+ timestamp: entry.timestamp,
3093
+ detail: entry.detail
3094
+ })),
3095
+ detection: source.detection,
3096
+ decisions: source.decisions.slice(-15)
3097
+ }
3098
+ };
3099
+ }
3100
+ //#endregion
3101
+ //#region server/prune-files.ts
3102
+ var MS_PER_DAY = 864e5;
3103
+ function idForEntry(entry, suffixes) {
3104
+ for (const suffix of suffixes) {
3105
+ if (suffix.length === 0) return entry;
3106
+ if (entry.endsWith(suffix)) return entry.slice(0, -suffix.length);
3107
+ }
3108
+ return null;
3109
+ }
3110
+ async function pruneAgedFiles({ directory, suffixes, retainDays, now = Date.now(), isRetainedId = () => false, entryMode = "file", fsPromises = fs.promises }) {
3111
+ let entries;
3112
+ try {
3113
+ entries = await fsPromises.readdir(directory);
3114
+ } catch {
3115
+ return [];
3116
+ }
3117
+ const cutoff = now - retainDays * MS_PER_DAY;
3118
+ const removedIds = [];
3119
+ for (const entry of entries) {
3120
+ const id = idForEntry(entry, suffixes);
3121
+ if (!id || isRetainedId(id)) continue;
3122
+ const filePath = path.join(directory, entry);
3123
+ try {
3124
+ if ((await fsPromises.stat(filePath)).mtimeMs >= cutoff) continue;
3125
+ if (!await recordSweptPath({
3126
+ cause: "aged-files",
3127
+ kind: entryMode === "directory" ? "folder" : "file",
3128
+ path: filePath,
3129
+ checksPassed: [`untouched-${retainDays}d`]
3130
+ })) continue;
3131
+ if (entryMode === "directory") await fsPromises.rm(filePath, {
3132
+ recursive: true,
3133
+ force: true
3134
+ });
3135
+ if (entryMode === "file") await fsPromises.unlink(filePath);
3136
+ removedIds.push(id);
3137
+ } catch {}
3138
+ }
3139
+ return removedIds;
3140
+ }
3141
+ //#endregion
3142
+ //#region server/session-temp/session-temp.ts
3143
+ var SESSION_TEMP_FOLDER = "guardrails-temp";
3144
+ var SESSION_TEMP_LOCK_FOLDER = "session-temp-locks";
3145
+ var SESSION_ID_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
3146
+ var SESSION_TEMP_RETAIN_DAYS = 7;
3147
+ function sessionTempLockFolder(glimmervoidHome) {
3148
+ return path.join(glimmervoidHome, SESSION_TEMP_LOCK_FOLDER);
3149
+ }
3150
+ async function deleteSessionTempFolderOnceUnheld(lockFolder, sessionId, sessionTempFolder, keepWhenNoLockFiles, log) {
3151
+ let trashFolder = null;
3152
+ try {
3153
+ trashFolder = trashSessionTempFolderOnceUnheld(lockFolder, sessionId, sessionTempFolder, { keepWhenNoLockFiles });
3154
+ } catch (error) {
3155
+ log.warn(`[session-temp] could not delete session temp folder ${sessionTempFolder}: ${errorMessage(error)}`);
3156
+ return;
3157
+ }
3158
+ if (trashFolder === null) return;
3159
+ if (!await recordSweptPath({
3160
+ cause: "session-temp",
3161
+ kind: "folder",
3162
+ path: sessionTempFolder,
3163
+ sessionId,
3164
+ checksPassed: ["no-lock-held"],
3165
+ log
3166
+ })) {
3167
+ await rename(trashFolder, sessionTempFolder).catch((error) => {
3168
+ log.warn(`[session-temp] could not move session temp folder ${trashFolder} back to ${sessionTempFolder}: ${errorMessage(error)}`);
3169
+ });
3170
+ return;
3171
+ }
3172
+ await rm(trashFolder, {
3173
+ recursive: true,
3174
+ force: true
3175
+ }).catch((error) => {
3176
+ log.warn(`[session-temp] could not delete session temp folder ${trashFolder}: ${errorMessage(error)}`);
3177
+ });
3178
+ }
3179
+ async function pruneLeftoverSessionTempFolders(glimmervoidHome, liveSessionIds, log = console) {
3180
+ const lockFolder = sessionTempLockFolder(glimmervoidHome);
3181
+ const lockEntryNames = await readdir(lockFolder).catch((error) => {
3182
+ if (isMissingFileError(error)) return [];
3183
+ log.warn(`[session-temp] kept every session temp folder because the lock list could not be read: ${errorMessage(error)}`);
3184
+ return null;
3185
+ });
3186
+ if (lockEntryNames === null) return;
3187
+ const sessionTempRoot = path.join(glimmervoidHome, SESSION_TEMP_FOLDER);
3188
+ const sessionIdsWithLockFiles = new Set(lockEntryNames.map(sessionIdOfLockFile).filter((sessionId) => sessionId !== null));
3189
+ for (const sessionId of sessionIdsWithLockFiles) {
3190
+ if (liveSessionIds.has(sessionId)) continue;
3191
+ await deleteSessionTempFolderOnceUnheld(lockFolder, sessionId, path.join(sessionTempRoot, sessionId), true, log);
3192
+ }
3193
+ await pruneAgedFiles({
3194
+ directory: sessionTempRoot,
3195
+ suffixes: [""],
3196
+ retainDays: SESSION_TEMP_RETAIN_DAYS,
3197
+ entryMode: "directory",
3198
+ isRetainedId: (id) => liveSessionIds.has(id) || sessionIdsWithLockFiles.has(id)
3199
+ });
3200
+ }
3201
+ function sessionTempFolderFor(sessionId) {
3202
+ if (!SESSION_ID_SHAPE.test(sessionId)) return null;
3203
+ return path.join(glimmervoidHomeDir$1(), SESSION_TEMP_FOLDER, sessionId);
3204
+ }
3205
+ function ensureSessionTempFolder(sessionId) {
3206
+ const sessionTempFolder = sessionTempFolderFor(sessionId);
3207
+ if (!sessionTempFolder) return null;
3208
+ createHeldSessionTempFolder(sessionTempLockFolder(glimmervoidHomeDir$1()), sessionId, sessionTempFolder);
3209
+ return sessionTempFolder;
3210
+ }
3211
+ async function removeSessionTempFolder(sessionId, log = console) {
3212
+ const sessionTempFolder = sessionTempFolderFor(sessionId);
3213
+ if (!sessionTempFolder) return;
3214
+ const lockFolder = sessionTempLockFolder(glimmervoidHomeDir$1());
3215
+ let didHoldSessionLock = true;
3216
+ try {
3217
+ didHoldSessionLock = releaseSessionLock(lockFolder, sessionId);
3218
+ } catch (error) {
3219
+ log.warn(`[session-temp] could not delete the lock of session ${sessionId}: ${errorMessage(error)}`);
3220
+ }
3221
+ if (!didHoldSessionLock) return;
3222
+ await deleteSessionTempFolderOnceUnheld(lockFolder, sessionId, sessionTempFolder, false, log);
3223
+ }
3224
+ //#endregion
3225
+ //#region server/lanes/ephemeral-session.ts
3226
+ var JOB_RESULT_FILENAME = "result.json";
3227
+ var ABORT_REAP_CAP_MS = 3e3;
3228
+ async function awaitSessionExit(sess, { signal = null, spawnGate = null, reapCapMs = ABORT_REAP_CAP_MS } = {}) {
3229
+ let onAbort = null;
3230
+ try {
3231
+ await new Promise((resolve, reject) => {
3232
+ let settled = false;
3233
+ const done = () => {
3234
+ if (settled) return;
3235
+ settled = true;
3236
+ resolve();
3237
+ };
3238
+ const fail = (error) => {
3239
+ if (settled) return;
3240
+ settled = true;
3241
+ reject(error);
3242
+ };
3243
+ sess.on("exit", done);
3244
+ sess.on("error", fail);
3245
+ if (signal) {
3246
+ onAbort = () => {
3247
+ try {
3248
+ sess.destroy();
3249
+ } catch {}
3250
+ if (!sess._killReap) {
3251
+ done();
3252
+ return;
3253
+ }
3254
+ awaitBounded([sess._killReap], { capMs: reapCapMs }).then(done, done);
3255
+ };
3256
+ if (signal.aborted) onAbort();
3257
+ if (!signal.aborted) signal.addEventListener("abort", onAbort, { once: true });
3258
+ }
3259
+ const run = () => signal?.aborted ? void 0 : sess.start();
3260
+ const activeSpawnGate = spawnGate;
3261
+ (activeSpawnGate ? activeSpawnGate.run(run) : Promise.resolve().then(run)).catch(fail);
3262
+ });
3263
+ } finally {
3264
+ if (signal && onAbort) try {
3265
+ signal.removeEventListener("abort", onAbort);
3266
+ } catch {}
3267
+ }
3268
+ }
3269
+ async function raceWithAbort({ start, timeoutMs, onTimeout, onEmpty, setTimeoutFn = DEFAULT_TIMER_FNS.setTimeoutFn, clearTimeoutFn = DEFAULT_TIMER_FNS.clearTimeoutFn, onPending = null }) {
3270
+ const controller = new AbortController();
3271
+ let handle = null;
3272
+ const timeout = new Promise((resolve) => {
3273
+ handle = setTimeoutFn(() => {
3274
+ controller.abort();
3275
+ resolve(onTimeout());
3276
+ }, timeoutMs);
3277
+ unrefTimer(handle);
3278
+ });
3279
+ const started = start(controller.signal);
3280
+ if (typeof onPending === "function") onPending(started);
3281
+ const result = await Promise.race([started, timeout]);
3282
+ if (handle) clearTimeoutFn(handle);
3283
+ return result || onEmpty();
3284
+ }
3285
+ function drainPending(pending, { capMs = 3500 } = {}) {
3286
+ if (!pending) return Promise.resolve();
3287
+ return awaitBounded([pending], { capMs }).then(() => {});
3288
+ }
3289
+ async function createJobResultFile(prefix) {
3290
+ const safePrefix = String(prefix).replace(/[^\w.-]+/g, "-");
3291
+ const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), `${safePrefix}-`));
3292
+ return {
3293
+ path: path.join(dir, JOB_RESULT_FILENAME),
3294
+ async cleanup() {
3295
+ try {
3296
+ await fs.promises.rm(dir, {
3297
+ recursive: true,
3298
+ force: true
3299
+ });
3300
+ } catch {}
3301
+ }
3302
+ };
3303
+ }
3304
+ function readResultFile(resultPath, allowed, decorate = null, { maxBytes = null, validate = null } = {}) {
3305
+ if (allowed && validate) throw new TypeError("readResultFile accepts allowed or validate, not both");
3306
+ const failedRead = (kind, reason) => ({
3307
+ ok: false,
3308
+ kind,
3309
+ reason,
3310
+ verdict: "ERROR",
3311
+ summary: reason
3312
+ });
3313
+ try {
3314
+ const fileDescriptor = fs.openSync(resultPath, "r");
3315
+ const chunks = [];
3316
+ const chunk = Buffer.allocUnsafe(65536);
3317
+ let totalBytesRead = 0;
3318
+ try {
3319
+ while (true) {
3320
+ const bytesRead = fs.readSync(fileDescriptor, chunk, 0, chunk.length, null);
3321
+ if (bytesRead === 0) break;
3322
+ totalBytesRead += bytesRead;
3323
+ if (maxBytes !== null && totalBytesRead > maxBytes) return failedRead("too-large", "result file is too large");
3324
+ chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
3413
3325
  }
3414
- if (cause === "parent-closed") return;
3415
- const kind = worktree || worktreeAtStart ? "discarded" : "none";
3416
- const hasParentRead = linksByChildId.get(child.id)?.hasParentRead ?? false;
3417
- post(child.id, "toParent", {
3418
- author: "glimmervoid",
3419
- text: describeChildEndNote(childName, cause, { kind }),
3420
- at: now(),
3421
- wakes: !hasParentRead
3422
- });
3423
- } catch (error) {
3424
- logger.warn(`[${AGENT_LANE_TAG} ${childName}] could not settle the worktree: ${errorMessage(error)}`);
3326
+ } finally {
3327
+ fs.closeSync(fileDescriptor);
3425
3328
  }
3426
- }
3427
- function post(childId, side, entry) {
3428
- const channel = channelsByChildId.get(childId);
3429
- if (!channel) return;
3430
- channelsByChildId.set(childId, postToChannel(channel, side, entry));
3431
- wakeRecipient(childId, side);
3432
- }
3433
- function drain(childId, side) {
3434
- const channel = channelsByChildId.get(childId);
3435
- if (!channel) return null;
3436
- const { channel: drainedChannel, drained } = drainChannel(channel, side);
3437
- channelsByChildId.set(childId, drainedChannel);
3438
- const link = linksByChildId.get(childId);
3439
- if (link && side === "toParent" && drained.entries.length > 0) link.hasParentRead = true;
3329
+ let obj;
3330
+ try {
3331
+ obj = JSON.parse(Buffer.concat(chunks).toString("utf8"));
3332
+ } catch {
3333
+ return failedRead("invalid-json", "invalid JSON in result file");
3334
+ }
3335
+ if (validate) {
3336
+ const validated = validate(obj);
3337
+ if (validated && validated.ok !== false) return { ...validated };
3338
+ return failedRead("rejected", validated?.summary || "result file was rejected");
3339
+ }
3340
+ const verdict = String(obj.verdict || "").toUpperCase();
3341
+ if (!allowed || !allowed.has(verdict)) return failedRead("rejected", "invalid verdict in result file");
3342
+ const result = {
3343
+ verdict,
3344
+ summary: String(obj.summary || "")
3345
+ };
3346
+ if (!decorate) return result;
3440
3347
  return {
3441
- sessionId: side === "toParent" ? channel.childId : channel.parentId,
3442
- name: side === "toParent" ? channel.childName : listAllSessions().find((session) => session.id === channel.parentId)?.name ?? channel.parentId,
3443
- entries: drained.entries.map(({ author, at, text }) => ({
3444
- from: author,
3445
- at,
3446
- text
3447
- })),
3448
- dropped: drained.droppedCount
3348
+ ...result,
3349
+ ...decorate(obj)
3449
3350
  };
3351
+ } catch {
3352
+ return failedRead("missing", "no result file");
3353
+ } finally {
3354
+ try {
3355
+ fs.rmSync(resultPath, { force: true });
3356
+ } catch {}
3450
3357
  }
3451
- function ownedChannels(parent) {
3452
- return [...channelsByChildId.values()].filter((channel) => channel.parentId === parent.id);
3453
- }
3454
- function findChildOf(parent, target) {
3455
- return findOwnedChild(ownedChannels(parent), parent.id, target);
3456
- }
3358
+ }
3359
+ function registerEphemeralSession({ map, id, sess, closeSessionDataClients, logPrefix, name, recordLane = null }) {
3360
+ map.set(id, sess);
3361
+ if (typeof recordLane === "function") sess.on("claude-session-id", ({ id: claudeSessionId, vendor }) => recordLane(claudeSessionId, logPrefix, vendor));
3362
+ sess.on("error", (err) => console.error(`[${logPrefix} ${name}] error: ${err.message}`));
3363
+ const removeFromMap = () => {
3364
+ if (map.get(id) === sess) {
3365
+ map.delete(id);
3366
+ closeSessionDataClients(id);
3367
+ }
3368
+ };
3369
+ const releaseAfterListeners = () => {
3370
+ removeFromMap();
3371
+ setImmediate(() => sess.destroy());
3372
+ };
3373
+ sess.on("exit", releaseAfterListeners);
3374
+ sess.on("error", () => {
3375
+ if (sess.hasLivePty !== false) return;
3376
+ releaseAfterListeners();
3377
+ });
3378
+ let hasScheduledTempFolderRemoval = false;
3379
+ const removeTempFolderAfterReap = () => {
3380
+ if (hasScheduledTempFolderRemoval) return;
3381
+ hasScheduledTempFolderRemoval = true;
3382
+ Promise.resolve(sess._awaitPendingReaps?.()).catch(() => {}).then(() => {
3383
+ if (map.has(id)) return;
3384
+ return removeSessionTempFolder(id);
3385
+ });
3386
+ };
3387
+ const origDestroy = sess.destroy.bind(sess);
3388
+ sess.destroy = () => {
3389
+ origDestroy();
3390
+ removeFromMap();
3391
+ removeTempFolderAfterReap();
3392
+ };
3393
+ }
3394
+ //#endregion
3395
+ //#region server/agent-api/agent-spawn.ts
3396
+ var SPAWN_FAILED_MESSAGE = "could not spawn the session";
3397
+ var PARENT_ENDED_MESSAGE = "this session ended before its child could start, so nothing was spawned";
3398
+ var BYTES_PER_MEGABYTE = 1048576;
3399
+ function createAgentSpawner(runtime, channels) {
3400
+ const { config, agentSessions, listAllSessions, makeSession, wireSessionEvents, closeSessionDataClients, broadcastControl, spawnGate, recordLane, memoryAdmission, logger } = runtime;
3401
+ const { noteEndCause, forgetLink, openChildChannel, settleChildWorktree } = channels;
3457
3402
  async function describeMemoryShortfall() {
3458
3403
  const shortfall = await memoryAdmission?.describeShortfallNow("session") ?? null;
3459
3404
  if (shortfall === null) return null;
@@ -3609,10 +3554,84 @@ function createAgentApiWiring({ config, agentSessions, listAllSessions, listBoar
3609
3554
  parent.finishAgentSpawn();
3610
3555
  }
3611
3556
  }
3557
+ return { spawn };
3558
+ }
3559
+ //#endregion
3560
+ //#region session/core/session-pr-links-core.ts
3561
+ function comparableLinkKey(link) {
3562
+ return `${link.repo}#${link.number}`.toLowerCase();
3563
+ }
3564
+ function isUnlinked(current, comparableKey) {
3565
+ return current.unlinkedKeys.some((unlinkedKey) => unlinkedKey.toLowerCase() === comparableKey);
3566
+ }
3567
+ function seedSessionPrLinks(persisted) {
3568
+ return persisted ?? {
3569
+ links: [],
3570
+ unlinkedKeys: []
3571
+ };
3572
+ }
3573
+ function mergeSessionPrLink(current, incoming) {
3574
+ const incomingKey = comparableLinkKey(incoming);
3575
+ if (isUnlinked(current, incomingKey)) return current;
3576
+ if (current.links.some((link) => comparableLinkKey(link) === incomingKey)) return current;
3577
+ const firstOlderIndex = current.links.findIndex((link) => link.linkedAt <= incoming.linkedAt);
3578
+ const insertAt = firstOlderIndex === -1 ? current.links.length : firstOlderIndex;
3579
+ if (insertAt >= 20) return current;
3580
+ return {
3581
+ links: [
3582
+ ...current.links.slice(0, insertAt),
3583
+ incoming,
3584
+ ...current.links.slice(insertAt)
3585
+ ].slice(0, 20),
3586
+ unlinkedKeys: current.unlinkedKeys
3587
+ };
3588
+ }
3589
+ function withManualPrLink(current, link) {
3590
+ const key = comparableLinkKey(link);
3591
+ if (!isUnlinked(current, key)) return mergeSessionPrLink(current, link);
3592
+ return mergeSessionPrLink({
3593
+ links: current.links,
3594
+ unlinkedKeys: current.unlinkedKeys.filter((unlinkedKey) => unlinkedKey.toLowerCase() !== key)
3595
+ }, link);
3596
+ }
3597
+ function withoutPrLink(current, pullRequestKey) {
3598
+ const comparableKey = pullRequestKey.toLowerCase();
3599
+ const links = current.links.filter((link) => comparableLinkKey(link) !== comparableKey);
3600
+ const isAlreadyUnlinked = isUnlinked(current, comparableKey);
3601
+ if (isAlreadyUnlinked && links.length === current.links.length) return current;
3602
+ return {
3603
+ links,
3604
+ unlinkedKeys: isAlreadyUnlinked ? current.unlinkedKeys : [...current.unlinkedKeys, pullRequestKey]
3605
+ };
3606
+ }
3607
+ function manualPrLink(pullRequestKey, knownPrs, nowMs) {
3608
+ const separatorIndex = pullRequestKey.lastIndexOf("#");
3609
+ const repo = pullRequestKey.slice(0, separatorIndex);
3610
+ const number = Number(pullRequestKey.slice(separatorIndex + 1));
3611
+ const comparableKey = pullRequestKey.toLowerCase();
3612
+ const canonicalPr = knownPrs.find((pr) => pr.key.toLowerCase() === comparableKey) ?? {
3613
+ repo,
3614
+ number,
3615
+ url: `https://github.com/${repo}/pull/${number}`
3616
+ };
3617
+ const parsed = LinkedPr.safeParse({
3618
+ repo: canonicalPr.repo,
3619
+ number: canonicalPr.number,
3620
+ url: canonicalPr.url,
3621
+ source: "manual",
3622
+ linkedAt: nowMs
3623
+ });
3624
+ return parsed.success ? parsed.data : null;
3625
+ }
3626
+ //#endregion
3627
+ //#region server/agent-api/agent-verbs.ts
3628
+ function createAgentVerbHandlers(runtime, channels, { spawn }) {
3629
+ const { config, agentSessions, listBoardSessions, sessionDocs, operatorState, whiteboards, coderWorkspaceStatus, channelsByChildId, childIdsToDiscard } = runtime;
3630
+ const { noteEndCause, post, drain, ownedChannels, findChildOf } = channels;
3612
3631
  function roleFactsOf(session) {
3613
3632
  return {
3614
3633
  isEphemeral: session.ephemeral,
3615
- isSpawnedChild: agentSessions.has(session.id) && session.id.startsWith(`${AGENT_LANE_TAG}-`),
3634
+ isSpawnedChild: agentSessions.has(session.id) && session.id.startsWith(`agent-spawn-`),
3616
3635
  hasOwnWorktree: session.hasOwnWorktree
3617
3636
  };
3618
3637
  }
@@ -3855,40 +3874,78 @@ function createAgentApiWiring({ config, agentSessions, listAllSessions, listBoar
3855
3874
  function githubLanesUnavailable() {
3856
3875
  return refusal(503, "GitHub lanes are not available in this Glimmervoid");
3857
3876
  }
3858
- const handlers = {
3859
- spawn: spawnReply,
3860
- send,
3861
- read,
3862
- close,
3863
- answer,
3864
- attention,
3865
- board: () => ({
3866
- status: 200,
3867
- body: {
3868
- ok: true,
3869
- sessions: board()
3870
- }
3871
- }),
3872
- push,
3873
- edit,
3874
- show: () => refusal(400, "show sends the file itself; run glimmervoid show <path>"),
3875
- limits: (session) => ({
3876
- status: 200,
3877
- body: limits(session)
3878
- }),
3879
- review: (_session, { pullRequestKey }) => review(pullRequestKey),
3880
- reviews: (_session, { pullRequestKey }) => reviews(pullRequestKey),
3881
- prs: () => operatorState ? {
3882
- status: 200,
3883
- body: projectMyPrs(operatorState.myPrsStatus())
3884
- } : githubLanesUnavailable(),
3885
- "link-pr": (session, { pullRequestKey }) => linkPr(session, pullRequestKey),
3886
- settings: (_session, request) => settings(request),
3887
- whiteboard: (session, request) => whiteboards ? whiteboards.handleAgent({
3888
- id: session.id,
3889
- name: session.name
3890
- }, request) : refusal(503, "whiteboards are not available in this Glimmervoid")
3877
+ return {
3878
+ handlers: {
3879
+ spawn: spawnReply,
3880
+ send,
3881
+ read,
3882
+ close,
3883
+ answer,
3884
+ attention,
3885
+ board: () => ({
3886
+ status: 200,
3887
+ body: {
3888
+ ok: true,
3889
+ sessions: board()
3890
+ }
3891
+ }),
3892
+ push,
3893
+ edit,
3894
+ show: () => refusal(400, "show sends the file itself; run glimmervoid show <path>"),
3895
+ limits: (session) => ({
3896
+ status: 200,
3897
+ body: limits(session)
3898
+ }),
3899
+ review: (_session, { pullRequestKey }) => review(pullRequestKey),
3900
+ reviews: (_session, { pullRequestKey }) => reviews(pullRequestKey),
3901
+ prs: () => operatorState ? {
3902
+ status: 200,
3903
+ body: projectMyPrs(operatorState.myPrsStatus())
3904
+ } : githubLanesUnavailable(),
3905
+ "link-pr": (session, { pullRequestKey }) => linkPr(session, pullRequestKey),
3906
+ settings: (_session, request) => settings(request),
3907
+ whiteboard: (session, request) => whiteboards ? whiteboards.handleAgent({
3908
+ id: session.id,
3909
+ name: session.name
3910
+ }, request) : refusal(503, "whiteboards are not available in this Glimmervoid")
3911
+ },
3912
+ roleFactsOf
3891
3913
  };
3914
+ }
3915
+ //#endregion
3916
+ //#region server/agent-api-wiring.ts
3917
+ function createAgentApiWiring({ config, agentSessions, listAllSessions, listBoardSessions, makeSession, wireSessionEvents, closeSessionDataClients, broadcastControl, spawnGate, sessionDocs, recordLane = null, memoryAdmission = null, operatorState = null, whiteboards = null, coderWorkspaceStatus = () => null, logger = console, setTimeoutFn = DEFAULT_TIMER_FNS.setTimeoutFn, clearTimeoutFn = DEFAULT_TIMER_FNS.clearTimeoutFn, now = Date.now }) {
3918
+ const runtime = {
3919
+ config,
3920
+ agentSessions,
3921
+ listAllSessions,
3922
+ listBoardSessions,
3923
+ makeSession,
3924
+ wireSessionEvents,
3925
+ closeSessionDataClients,
3926
+ broadcastControl,
3927
+ spawnGate,
3928
+ sessionDocs,
3929
+ recordLane,
3930
+ memoryAdmission,
3931
+ operatorState,
3932
+ whiteboards,
3933
+ coderWorkspaceStatus,
3934
+ logger,
3935
+ setTimeoutFn,
3936
+ clearTimeoutFn,
3937
+ now,
3938
+ channelsByChildId: /* @__PURE__ */ new Map(),
3939
+ linksByChildId: /* @__PURE__ */ new Map(),
3940
+ parentsWithChannelCleanup: /* @__PURE__ */ new WeakSet(),
3941
+ sessionsWithOperatorWatch: /* @__PURE__ */ new WeakSet(),
3942
+ lastOperatorInputAtBySession: /* @__PURE__ */ new WeakMap(),
3943
+ childIdsToDiscard: /* @__PURE__ */ new Set(),
3944
+ endCauseByChildId: /* @__PURE__ */ new Map()
3945
+ };
3946
+ const { childIdsToDiscard } = runtime;
3947
+ const channels = createChildChannels(runtime);
3948
+ const { handlers, roleFactsOf } = createAgentVerbHandlers(runtime, channels, createAgentSpawner(runtime, channels));
3892
3949
  function dispatch(session, verb, request) {
3893
3950
  const handler = handlers[verb];
3894
3951
  return handler(session, request);