@hearsay-tools/squawk 0.18.0-pr4298.8332 → 0.18.0-pr4299.8339

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 (140) hide show
  1. package/dist/automations/tools.d.ts +8 -8
  2. package/dist/contract/agent-profiles.d.ts +13 -10
  3. package/dist/contract/index.js +12 -7
  4. package/dist/core/os-cgroup.d.ts +43 -0
  5. package/dist/core/os-cgroup.js +220 -0
  6. package/dist/core/os-cgroup.js.map +1 -0
  7. package/dist/core/os-win-job.d.ts +30 -0
  8. package/dist/core/os-win-job.js +80 -0
  9. package/dist/core/os-win-job.js.map +1 -0
  10. package/dist/core/session-containment.d.ts +78 -0
  11. package/dist/core/session-containment.js +247 -0
  12. package/dist/core/session-containment.js.map +1 -0
  13. package/dist/core/session-process.d.ts +10 -0
  14. package/dist/core/session-process.js +109 -22
  15. package/dist/core/session-process.js.map +1 -1
  16. package/dist/delegation/routes.d.ts +10 -10
  17. package/dist/delegation/transport.d.ts +79 -79
  18. package/dist/jobs/cli.js +6 -2
  19. package/dist/jobs/cli.js.map +1 -1
  20. package/dist/jobs/job.d.ts +6 -0
  21. package/dist/jobs/job.js +80 -2
  22. package/dist/jobs/job.js.map +1 -1
  23. package/dist/plugin/runtime.d.ts +1 -1
  24. package/dist/plugin/runtime.js +1 -1
  25. package/dist/plugin/runtime.js.map +1 -1
  26. package/dist/remote-settings-cli.d.ts +1 -1
  27. package/dist/remote-settings-cli.js +2 -2
  28. package/dist/remote-settings-cli.js.map +1 -1
  29. package/dist/runners/opencode/opencode-http.d.ts +1 -0
  30. package/dist/runners/opencode/opencode-http.js +7 -0
  31. package/dist/runners/opencode/opencode-http.js.map +1 -1
  32. package/dist/runners/opencode/opencode-server-runner.js +3 -9
  33. package/dist/runners/opencode/opencode-server-runner.js.map +1 -1
  34. package/dist/runs/run-decode.d.ts +72 -72
  35. package/dist/server/activity-routes.d.ts +23 -23
  36. package/dist/server/capabilities.d.ts +4 -2
  37. package/dist/server/capabilities.js.map +1 -1
  38. package/dist/server/live-routes.d.ts +6 -6
  39. package/dist/server/models-routes.d.ts +12 -30
  40. package/dist/server/models-routes.js +1 -3
  41. package/dist/server/models-routes.js.map +1 -1
  42. package/dist/server/project-settings-routes.d.ts +0 -14
  43. package/dist/server/project-settings-routes.js +2 -4
  44. package/dist/server/project-settings-routes.js.map +1 -1
  45. package/dist/server/providers-routes.d.ts +70 -88
  46. package/dist/server/providers-routes.js +52 -38
  47. package/dist/server/providers-routes.js.map +1 -1
  48. package/dist/server/repo-routes.d.ts +34 -34
  49. package/dist/server/reports-api.d.ts +2 -2
  50. package/dist/server/runs-routes.d.ts +16 -16
  51. package/dist/server/server-types.d.ts +1 -1
  52. package/dist/server/server-types.js +6 -3
  53. package/dist/server/server-types.js.map +1 -1
  54. package/dist/server/server.d.ts +1312 -1368
  55. package/dist/server/server.js +3 -8
  56. package/dist/server/server.js.map +1 -1
  57. package/dist/server/workspace-live-routes.d.ts +6 -6
  58. package/dist/server/workspace-routes.d.ts +84 -84
  59. package/dist/worker-scope/cgroup.d.ts +2 -36
  60. package/dist/worker-scope/cgroup.js +5 -161
  61. package/dist/worker-scope/cgroup.js.map +1 -1
  62. package/dist/worker-scope/job.d.ts +1 -22
  63. package/dist/worker-scope/job.js +1 -56
  64. package/dist/worker-scope/job.js.map +1 -1
  65. package/dist/worker-scope/scope.d.ts +5 -1
  66. package/dist/worker-scope/worker-scopes.js +36 -18
  67. package/dist/worker-scope/worker-scopes.js.map +1 -1
  68. package/dist/workflows/input-acknowledgement.d.ts +24 -24
  69. package/dist/workflows/run/wait-engine.d.ts +72 -72
  70. package/dist/workspace/agent-accounts.d.ts +2 -0
  71. package/dist/workspace/agent-accounts.js +4 -0
  72. package/dist/workspace/agent-accounts.js.map +1 -1
  73. package/package.json +4 -4
  74. package/scripts/windows-worker-job.cs +67 -32
  75. package/scripts/windows-worker-job.ps1 +11 -4
  76. package/web/dist/assets/accounts-section-BOvRm84F.js +1 -0
  77. package/web/dist/assets/{activity-motion-wGHBuD_L.js → activity-motion-BGnxXoSR.js} +1 -1
  78. package/web/dist/assets/{activity-route-BhT-npje.js → activity-route-Ydl82wRv.js} +1 -1
  79. package/web/dist/assets/{agent-config-section-BIkW506A.js → agent-config-section-CWGkeds9.js} +2 -2
  80. package/web/dist/assets/agent-defaults-section-LW-y7EbV.js +1 -0
  81. package/web/dist/assets/{appearance-CipbKN5k.js → appearance-KQCxvweq.js} +1 -1
  82. package/web/dist/assets/{archive-on-merge-field-Dx8afb0D.js → archive-on-merge-field-CqcQ_V_s.js} +1 -1
  83. package/web/dist/assets/attention-CvHM4cjG.js +1 -0
  84. package/web/dist/assets/{automations-route-DKKwkBjL.js → automations-route-EYAx7F5Y.js} +1 -1
  85. package/web/dist/assets/{commit-diff-panel-OqVigspU.js → commit-diff-panel-Dn66n8t7.js} +1 -1
  86. package/web/dist/assets/{diff-CpkjO5Q-.js → diff-BVksMz5Q.js} +2 -2
  87. package/web/dist/assets/{diff-view-D6QC4z_i.js → diff-view-CsEHWJZz.js} +1 -1
  88. package/web/dist/assets/{file-preview-C-oYrG0r.js → file-preview-FAlEJ1cx.js} +1 -1
  89. package/web/dist/assets/{folder-browser-DJd_sQFq.js → folder-browser-B5OlxUTn.js} +1 -1
  90. package/web/dist/assets/{git-toolbar-BiWUXSvy.js → git-toolbar-RB61GwY7.js} +1 -1
  91. package/web/dist/assets/{github-DSZtAYK0.js → github-B83lFoyq.js} +1 -1
  92. package/web/dist/assets/{global-activity-route-ylV7sfQb.js → global-activity-route-ByTd6-Co.js} +1 -1
  93. package/web/dist/assets/index-F6ngXb7T.js +21 -0
  94. package/web/dist/assets/{label-HRVFTN4V.js → label-I5VElFnm.js} +1 -1
  95. package/web/dist/assets/{live-reads-Djkq38NT.js → live-reads-BxjlQXfN.js} +1 -1
  96. package/web/dist/assets/{markdown-Drj1MCd_.js → markdown-C5LEInuz.js} +1 -1
  97. package/web/dist/assets/{notifications-section-BNncS89W.js → notifications-section-BKk70JWC.js} +1 -1
  98. package/web/dist/assets/{open-in-menu-BeAj_aq3.js → open-in-menu-B3c0Ti3f.js} +1 -1
  99. package/web/dist/assets/{preview-pane-connected-C9bYs_nr.js → preview-pane-connected-cnI0j6jA.js} +2 -2
  100. package/web/dist/assets/{project-location-DJEH4PmN.js → project-location-Cy6GQdLI.js} +1 -1
  101. package/web/dist/assets/{project-router-C6zhlnwO.js → project-router-CDPfL2Jz.js} +1 -1
  102. package/web/dist/assets/{project-scope-context-d3J3hWPR.js → project-scope-context-D9axDY18.js} +2 -2
  103. package/web/dist/assets/{projects-section-DAyPYxaB.js → projects-section-6Hm2G07S.js} +1 -1
  104. package/web/dist/assets/{prompt-templates-section-BUTjHN-R.js → prompt-templates-section-Cuzl3OXR.js} +1 -1
  105. package/web/dist/assets/{queries-dnpdX9VT.js → queries-fKV3_1l7.js} +1 -1
  106. package/web/dist/assets/{reference-chip-DHWnJcWz.js → reference-chip-DlHw9fzn.js} +1 -1
  107. package/web/dist/assets/remote-settings-notice-gRZtO9f4.js +1 -0
  108. package/web/dist/assets/{repo-git-CahuM1Bi.js → repo-git-CEOVYEqE.js} +1 -1
  109. package/web/dist/assets/{report-reader-BMw7TyID.js → report-reader-xkm4C2I-.js} +1 -1
  110. package/web/dist/assets/{reports-BqhgWSM-.js → reports-Cn7Y5wuV.js} +1 -1
  111. package/web/dist/assets/{resources-section-CPdErsDL.js → resources-section-DD674cR0.js} +1 -1
  112. package/web/dist/assets/run-header-DdDGRgle.js +2 -0
  113. package/web/dist/assets/settings-agent-picker-BUU7YTUe.js +1 -0
  114. package/web/dist/assets/{settings-shell-Cg1j_HUU.js → settings-shell-BEU3xNKX.js} +1 -1
  115. package/web/dist/assets/{sidebar-section-C7mKySo9.js → sidebar-section-CsdpZ2HY.js} +1 -1
  116. package/web/dist/assets/{skills-DL6gTurZ.js → skills-DAV92Dfo.js} +1 -1
  117. package/web/dist/assets/{tab-link-Cq8g7cFx.js → tab-link-BaKE6KnE.js} +1 -1
  118. package/web/dist/assets/{task-changes-BYdPYqmr.js → task-changes-DDT3_Ewp.js} +1 -1
  119. package/web/dist/assets/{task-commits-CZs64PxA.js → task-commits-D3JKpobQ.js} +1 -1
  120. package/web/dist/assets/{task-files-CHDvZdch.js → task-files-CpPiI1PW.js} +1 -1
  121. package/web/dist/assets/{task-github-item-BaAS8tc7.js → task-github-item-CdLRcMoD.js} +1 -1
  122. package/web/dist/assets/{task-groups-BF7_ZZTh.js → task-groups-JRTdCEHW.js} +1 -1
  123. package/web/dist/assets/{task-thread-DKTYTRYk.js → task-thread-IH9IBhzt.js} +6 -6
  124. package/web/dist/assets/{tasks-table-CzLkD-kr.js → tasks-table-BzZggRo7.js} +1 -1
  125. package/web/dist/assets/{thread-state-Cnu6irf1.js → thread-state-Cbr1DOuT.js} +1 -1
  126. package/web/dist/assets/{use-hand-to-agent-state-C0HmC08K.js → use-hand-to-agent-state-Bz9OEGmR.js} +1 -1
  127. package/web/dist/assets/{useInfiniteQuery-qJcgwcf9.js → useInfiniteQuery-GZp9laKm.js} +1 -1
  128. package/web/dist/assets/useQuery-CzVHT8UE.js +1 -0
  129. package/web/dist/assets/{workflows-BxrHkrIx.js → workflows-tzdllpoB.js} +3 -3
  130. package/web/dist/assets/{workspace-tools-DK0GgizV.js → workspace-tools-8UTakmy2.js} +1 -1
  131. package/web/dist/assets/{worktrees-section-CBWXq2mc.js → worktrees-section-BEQY8IIx.js} +1 -1
  132. package/web/dist/index.html +14 -14
  133. package/web/dist/assets/accounts-section-qnA3YX9G.js +0 -1
  134. package/web/dist/assets/agent-defaults-section-D9oxRh7t.js +0 -1
  135. package/web/dist/assets/attention-VcsXbAZz.js +0 -1
  136. package/web/dist/assets/index-CS5yyNbo.js +0 -21
  137. package/web/dist/assets/remote-settings-notice-BTtluTx2.js +0 -1
  138. package/web/dist/assets/run-header-BpdSJ6lc.js +0 -2
  139. package/web/dist/assets/settings-agent-picker-By-EZVYH.js +0 -1
  140. package/web/dist/assets/useQuery-CkUPLiaa.js +0 -1
@@ -7,6 +7,10 @@ export declare function invokeScheduleTaskTool(input: unknown): Promise<{
7
7
  }[];
8
8
  isError: boolean;
9
9
  details: {
10
+ ok: false;
11
+ code: "automations_off" | "conflict" | "invalid_request" | "not_found" | "unavailable";
12
+ message: string;
13
+ } | {
10
14
  ok: true;
11
15
  task: {
12
16
  id: string;
@@ -18,10 +22,6 @@ export declare function invokeScheduleTaskTool(input: unknown): Promise<{
18
22
  url?: string | undefined;
19
23
  };
20
24
  note: string;
21
- } | {
22
- ok: false;
23
- code: "automations_off" | "conflict" | "invalid_request" | "not_found" | "unavailable";
24
- message: string;
25
25
  };
26
26
  }>;
27
27
  export declare function formatScheduleTaskTool(answer: Awaited<ReturnType<typeof callScheduleTask>>): {
@@ -31,6 +31,10 @@ export declare function formatScheduleTaskTool(answer: Awaited<ReturnType<typeof
31
31
  }[];
32
32
  isError: boolean;
33
33
  details: {
34
+ ok: false;
35
+ code: "automations_off" | "conflict" | "invalid_request" | "not_found" | "unavailable";
36
+ message: string;
37
+ } | {
34
38
  ok: true;
35
39
  task: {
36
40
  id: string;
@@ -42,10 +46,6 @@ export declare function formatScheduleTaskTool(answer: Awaited<ReturnType<typeof
42
46
  url?: string | undefined;
43
47
  };
44
48
  note: string;
45
- } | {
46
- ok: false;
47
- code: "automations_off" | "conflict" | "invalid_request" | "not_found" | "unavailable";
48
- message: string;
49
49
  };
50
50
  };
51
51
  export declare function invokeScheduledTasksTool(input: unknown): Promise<{
@@ -33,8 +33,8 @@ export declare const agentProfileSchema: z.ZodObject<{
33
33
  id: z.ZodString;
34
34
  provider: z.ZodString;
35
35
  label: z.ZodString;
36
- configDir: z.ZodString;
37
- path: z.ZodString;
36
+ configDir: z.ZodOptional<z.ZodString>;
37
+ path: z.ZodOptional<z.ZodString>;
38
38
  exists: z.ZodBoolean;
39
39
  looksValid: z.ZodBoolean;
40
40
  isDefault: z.ZodBoolean;
@@ -70,9 +70,10 @@ export type AgentAccountSelection = z.infer<typeof agentAccountSelectionSchema>;
70
70
  /**
71
71
  * `GET /api/v1/workspace/agent-profiles` — every account, discovered defaults first.
72
72
  *
73
- * `editable` is false in hosted mode (`CEZ_REMOTE`), where the whole family is refused: defining
74
- * a profile points an agent at a local directory, and the listing echoes absolute paths carrying
75
- * the username. Same posture as `PUT /api/v1/agent-config/:id`.
73
+ * `editable` mirrors `settingsAdmin` (true locally, or on a remote cockpit with a host grant).
74
+ * Without `settingsAdmin`, accounts are still listed so users can choose configured logins, while
75
+ * host paths (`configDir`, `path`, and raw repo roots in `selections`) are withheld and project
76
+ * choices ride on `projectSelections` keyed by project id.
76
77
  */
77
78
  export declare const agentProfilesResponseSchema: z.ZodObject<{
78
79
  editable: z.ZodBoolean;
@@ -80,8 +81,8 @@ export declare const agentProfilesResponseSchema: z.ZodObject<{
80
81
  id: z.ZodString;
81
82
  provider: z.ZodString;
82
83
  label: z.ZodString;
83
- configDir: z.ZodString;
84
- path: z.ZodString;
84
+ configDir: z.ZodOptional<z.ZodString>;
85
+ path: z.ZodOptional<z.ZodString>;
85
86
  exists: z.ZodBoolean;
86
87
  looksValid: z.ZodBoolean;
87
88
  isDefault: z.ZodBoolean;
@@ -102,6 +103,7 @@ export declare const agentProfilesResponseSchema: z.ZodObject<{
102
103
  }, z.core.$strip>>;
103
104
  profileCapableProviders: z.ZodArray<z.ZodString>;
104
105
  selections: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
106
+ projectSelections: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
105
107
  }, z.core.$strip>;
106
108
  export type AgentProfilesResponse = z.infer<typeof agentProfilesResponseSchema>;
107
109
  /**
@@ -117,9 +119,10 @@ export declare const selectAgentProfileInputSchema: z.ZodObject<{
117
119
  profileId: z.ZodNullable<z.ZodString>;
118
120
  }, z.core.$strip>;
119
121
  export type SelectAgentProfileInput = z.infer<typeof selectAgentProfileInputSchema>;
120
- /** The selection map after the write — the same shape the listing carries. */
122
+ /** The selection maps after the write — the same shape the listing carries. */
121
123
  export declare const agentProfileSelectionsResponseSchema: z.ZodObject<{
122
124
  selections: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
125
+ projectSelections: z.ZodRecord<z.ZodString, z.ZodRecord<z.ZodString, z.ZodOptional<z.ZodString>>>;
123
126
  }, z.core.$strip>;
124
127
  export type AgentProfileSelectionsResponse = z.infer<typeof agentProfileSelectionsResponseSchema>;
125
128
  /** `GET /api/v1/workspace/agent-profiles/:id/status` — one account's auth state, probed for real.
@@ -161,8 +164,8 @@ export declare const agentProfileResponseSchema: z.ZodObject<{
161
164
  id: z.ZodString;
162
165
  provider: z.ZodString;
163
166
  label: z.ZodString;
164
- configDir: z.ZodString;
165
- path: z.ZodString;
167
+ configDir: z.ZodOptional<z.ZodString>;
168
+ path: z.ZodOptional<z.ZodString>;
166
169
  exists: z.ZodBoolean;
167
170
  looksValid: z.ZodBoolean;
168
171
  isDefault: z.ZodBoolean;
@@ -4020,10 +4020,11 @@ var agentProfileSchema = z31.object({
4020
4020
  id: z31.string(),
4021
4021
  provider: providerIdSchema,
4022
4022
  label: z31.string(),
4023
- /** As the user wrote it — a literal `~` is preserved, matching `browseRoot`/`projectsDir`. */
4024
- configDir: z31.string(),
4025
- /** Expanded absolute path. Same-origin route, like `ProjectListEntry.root`. */
4026
- path: z31.string(),
4023
+ /** As the user wrote it — a literal `~` is preserved, matching `browseRoot`/`projectsDir`.
4024
+ * Omitted on a remote cockpit without `settingsAdmin` so host paths are not disclosed. */
4025
+ configDir: z31.string().optional(),
4026
+ /** Expanded absolute path. Omitted on a remote cockpit without `settingsAdmin`. */
4027
+ path: z31.string().optional(),
4027
4028
  /** False for a dir the CLI has not created yet — legitimate, and NOT a reason to fall back
4028
4029
  * to another account at run time (that would silently bill the wrong subscription). */
4029
4030
  exists: z31.boolean(),
@@ -4057,8 +4058,11 @@ var agentProfilesResponseSchema = z31.object({
4057
4058
  * Served here rather than on `GET /api/v1/projects` because it is stored beside the accounts it
4058
4059
  * names (`~/.cezar/agent-accounts.json`) — one file, so deleting an account and scrubbing every
4059
4060
  * reference to it is one atomic write, and neither can be dropped by a Squawk version that never
4060
- * heard of accounts. Empty in hosted mode, where the whole family is withheld. */
4061
- selections: z31.record(z31.string(), agentAccountSelectionSchema)
4061
+ * heard of accounts. Empty without `settingsAdmin` so host paths are not disclosed. */
4062
+ selections: z31.record(z31.string(), agentAccountSelectionSchema),
4063
+ /** Which account each project uses, keyed by canonical project id (plus `'default'` for the boot
4064
+ * project). Always populated without disclosing host filesystem paths. */
4065
+ projectSelections: z31.record(z31.string(), agentAccountSelectionSchema)
4062
4066
  });
4063
4067
  var selectAgentProfileInputSchema = z31.object({
4064
4068
  /** Registry slug, or the reserved `default` boot alias. Resolved to a root server-side. */
@@ -4067,7 +4071,8 @@ var selectAgentProfileInputSchema = z31.object({
4067
4071
  profileId: z31.string().max(64).nullable()
4068
4072
  });
4069
4073
  var agentProfileSelectionsResponseSchema = z31.object({
4070
- selections: z31.record(z31.string(), agentAccountSelectionSchema)
4074
+ selections: z31.record(z31.string(), agentAccountSelectionSchema),
4075
+ projectSelections: z31.record(z31.string(), agentAccountSelectionSchema)
4071
4076
  });
4072
4077
  var agentAccountStatusResponseSchema = z31.object({ status: providerStatusSchema });
4073
4078
  var createAgentProfileInputSchema = z31.object({
@@ -0,0 +1,43 @@
1
+ /** What cgroup operations read and write; tests replace it. */
2
+ export type CgroupFs = {
3
+ readFile: (path: string) => string;
4
+ writeFile: (path: string, data: string) => void;
5
+ mkdir: (path: string) => void;
6
+ rmdir: (path: string) => void;
7
+ /** False only when nothing is there; any other lookup failure throws: it proves no absence. */
8
+ isDir: (path: string) => boolean;
9
+ /** The child cgroups directly under `path`. */
10
+ children: (path: string) => string[];
11
+ };
12
+ export declare const realCgroupFs: CgroupFs;
13
+ /** The cgroup v2 directory this process is in, from `/proc/self/cgroup`. Undefined on cgroup v1,
14
+ * a hybrid host without a unified entry, or a path that leaves the hierarchy. */
15
+ export declare function ownCgroup(fs?: CgroupFs): string | undefined;
16
+ /** The argv that runs `file args` inside the cgroup at `path`. */
17
+ export declare function cgroupCommand(path: string, file: string, args: readonly string[]): [string, string[]];
18
+ /** Whether this host lets the controller create, enter, kill and remove a child cgroup. A writable
19
+ * mount alone is no proof, so the probe does each step for real; any failure answers why. */
20
+ export declare function probeCgroups(fs?: CgroupFs, place?: (procs: string) => boolean): {
21
+ base: string;
22
+ } | {
23
+ reason: string;
24
+ };
25
+ /** Ensures `join(parent, name)` exists as a real directory. A non-directory entry throws. */
26
+ export declare function ensureNamedCgroup(parent: string, name: string, fs?: CgroupFs): string;
27
+ /** Whether `path` still holds a process; an absent group holds none. */
28
+ export declare function cgroupPopulated(path: string, fs?: CgroupFs): boolean;
29
+ /** Live PIDs currently listed in `path/cgroup.procs` and any nested child cgroups. */
30
+ export declare function cgroupPids(path: string, fs?: CgroupFs): number[];
31
+ /** Moves every PID currently in `from` (and nested children) into `to`, ignoring exited PIDs. */
32
+ export declare function moveCgroupPids(from: string, to: string, fs?: CgroupFs): void;
33
+ /** Removes an already-empty cgroup (and any empty children). Returns true if absent or removed. */
34
+ export declare function removeEmptyCgroup(path: string, fs?: CgroupFs): boolean;
35
+ /** SIGKILL every process in `path` and its descendants now. An absent group is already empty. */
36
+ export declare function killCgroup(path: string, fs?: CgroupFs): void;
37
+ /** Kill, wait until empty, remove; repeated until the group is gone or `deadline` passes. One
38
+ * `cgroup.kill` on the cgroup ends every process in it and in its descendants, and its
39
+ * `populated 0` covers them all; a child cgroup is then removed depth-first, since the kernel
40
+ * removes only a cgroup without children. A process that placed itself after the kill makes a
41
+ * removal fail with EBUSY, so the round repeats; once the group is removed no process can enter
42
+ * it. True when the group is gone; a lookup that fails for any reason but absence answers false. */
43
+ export declare function removeCgroup(path: string, deadline: number, fs?: CgroupFs): Promise<boolean>;
@@ -0,0 +1,220 @@
1
+ /** Low-level Linux cgroup v2 operations shared by worker scopes (ADR 0032) and per-session
2
+ * containment (hearsay-tools/squawk#1345). */
3
+ import { spawnSync } from 'node:child_process';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
6
+ import { posix } from 'node:path';
7
+ const { join } = posix;
8
+ const CGROUP_ROOT = '/sys/fs/cgroup';
9
+ const SHELL = '/bin/sh';
10
+ /** `$0` is the target `cgroup.procs`; `0` names the writer, the shell itself, which then becomes
11
+ * the command through `exec` (same pid). A failed move ends the shell before the command runs. */
12
+ const PLACE = 'echo 0 > "$0" && exec "$@"';
13
+ const POLL_MS = 10;
14
+ export const realCgroupFs = {
15
+ readFile: path => readFileSync(path, 'utf8'),
16
+ writeFile: (path, data) => writeFileSync(path, data),
17
+ mkdir: path => mkdirSync(path, { mode: 0o700 }),
18
+ rmdir: path => rmdirSync(path),
19
+ isDir: path => {
20
+ try {
21
+ const s = lstatSync(path);
22
+ return s.isDirectory() && !s.isSymbolicLink();
23
+ }
24
+ catch (error) {
25
+ if (code(error) === 'ENOENT')
26
+ return false;
27
+ throw error;
28
+ }
29
+ },
30
+ children: path => readdirSync(path, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => join(path, entry.name)),
31
+ };
32
+ /** The cgroup v2 directory this process is in, from `/proc/self/cgroup`. Undefined on cgroup v1,
33
+ * a hybrid host without a unified entry, or a path that leaves the hierarchy. */
34
+ export function ownCgroup(fs = realCgroupFs) {
35
+ let text;
36
+ try {
37
+ text = fs.readFile('/proc/self/cgroup');
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ const line = text.split('\n').find(entry => entry.startsWith('0::/'));
43
+ if (!line)
44
+ return undefined;
45
+ const path = line.slice(3).trim();
46
+ if (path.split('/').includes('..'))
47
+ return undefined;
48
+ return path === '/' ? CGROUP_ROOT : join(CGROUP_ROOT, path);
49
+ }
50
+ /** The argv that runs `file args` inside the cgroup at `path`. */
51
+ export function cgroupCommand(path, file, args) {
52
+ return [SHELL, ['-c', PLACE, join(path, 'cgroup.procs'), file, ...args]];
53
+ }
54
+ /** Whether this host lets the controller create, enter, kill and remove a child cgroup. A writable
55
+ * mount alone is no proof, so the probe does each step for real; any failure answers why. */
56
+ export function probeCgroups(fs = realCgroupFs, place = placeProbe) {
57
+ const base = ownCgroup(fs);
58
+ if (!base)
59
+ return { reason: 'no cgroup v2 entry in /proc/self/cgroup' };
60
+ const probe = join(base, `squawk-probe-${randomUUID()}`);
61
+ try {
62
+ fs.mkdir(probe);
63
+ }
64
+ catch (error) {
65
+ return { reason: `cannot create a child cgroup (${code(error)})` };
66
+ }
67
+ let failure;
68
+ try {
69
+ if (!place(join(probe, 'cgroup.procs')))
70
+ failure = 'cannot move a process into a child cgroup';
71
+ else
72
+ fs.writeFile(join(probe, 'cgroup.kill'), '1');
73
+ }
74
+ catch (error) {
75
+ failure = `cannot kill a child cgroup (${code(error)})`;
76
+ }
77
+ // Removal is part of the proof: a host that cannot remove a cgroup cannot destroy it.
78
+ try {
79
+ fs.rmdir(probe);
80
+ }
81
+ catch (error) {
82
+ failure ??= `cannot remove a child cgroup (${code(error)})`;
83
+ }
84
+ return failure ? { reason: failure } : { base };
85
+ }
86
+ /** A shell moves itself into the probe group and exits; exit 0 means the move worked. */
87
+ function placeProbe(procs) {
88
+ const result = spawnSync(SHELL, ['-c', 'echo 0 > "$0"', procs], { stdio: 'ignore', timeout: 5_000 });
89
+ return result.status === 0;
90
+ }
91
+ const code = (error) => error.code ?? String(error);
92
+ /** Ensures `join(parent, name)` exists as a real directory. A non-directory entry throws. */
93
+ export function ensureNamedCgroup(parent, name, fs = realCgroupFs) {
94
+ const path = join(parent, name);
95
+ if (fs.isDir(path))
96
+ return path;
97
+ fs.mkdir(path);
98
+ return path;
99
+ }
100
+ /** Whether `path` still holds a process; an absent group holds none. */
101
+ export function cgroupPopulated(path, fs = realCgroupFs) {
102
+ let events;
103
+ try {
104
+ events = fs.readFile(join(path, 'cgroup.events'));
105
+ }
106
+ catch (error) {
107
+ if (code(error) === 'ENOENT')
108
+ return false;
109
+ throw error;
110
+ }
111
+ return /(?:^|\n)populated 1(?:\n|$)/.test(events);
112
+ }
113
+ /** Live PIDs currently listed in `path/cgroup.procs` and any nested child cgroups. */
114
+ export function cgroupPids(path, fs = realCgroupFs) {
115
+ const pids = [];
116
+ collectPids(path, fs, pids);
117
+ return pids;
118
+ }
119
+ function collectPids(path, fs, out) {
120
+ let text;
121
+ try {
122
+ text = fs.readFile(join(path, 'cgroup.procs'));
123
+ }
124
+ catch {
125
+ return;
126
+ }
127
+ for (const line of text.split('\n')) {
128
+ const trimmed = line.trim();
129
+ if (!/^\d+$/.test(trimmed))
130
+ continue;
131
+ const pid = Number(trimmed);
132
+ if (pid > 1)
133
+ out.push(pid);
134
+ }
135
+ let children;
136
+ try {
137
+ children = fs.children(path);
138
+ }
139
+ catch {
140
+ return;
141
+ }
142
+ for (const child of children)
143
+ collectPids(child, fs, out);
144
+ }
145
+ /** Moves every PID currently in `from` (and nested children) into `to`, ignoring exited PIDs. */
146
+ export function moveCgroupPids(from, to, fs = realCgroupFs) {
147
+ const target = join(to, 'cgroup.procs');
148
+ for (const pid of cgroupPids(from, fs)) {
149
+ try {
150
+ fs.writeFile(target, String(pid));
151
+ }
152
+ catch { /* process exited or cannot move */ }
153
+ }
154
+ }
155
+ /** Removes an already-empty cgroup (and any empty children). Returns true if absent or removed. */
156
+ export function removeEmptyCgroup(path, fs = realCgroupFs) {
157
+ try {
158
+ if (!fs.isDir(path))
159
+ return true;
160
+ return removeTree(path, fs) === true;
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ }
166
+ /** SIGKILL every process in `path` and its descendants now. An absent group is already empty. */
167
+ export function killCgroup(path, fs = realCgroupFs) {
168
+ try {
169
+ fs.writeFile(join(path, 'cgroup.kill'), '1');
170
+ }
171
+ catch (error) {
172
+ if (code(error) !== 'ENOENT')
173
+ throw error;
174
+ }
175
+ }
176
+ /** Kill, wait until empty, remove; repeated until the group is gone or `deadline` passes. One
177
+ * `cgroup.kill` on the cgroup ends every process in it and in its descendants, and its
178
+ * `populated 0` covers them all; a child cgroup is then removed depth-first, since the kernel
179
+ * removes only a cgroup without children. A process that placed itself after the kill makes a
180
+ * removal fail with EBUSY, so the round repeats; once the group is removed no process can enter
181
+ * it. True when the group is gone; a lookup that fails for any reason but absence answers false. */
182
+ export async function removeCgroup(path, deadline, fs = realCgroupFs) {
183
+ try {
184
+ for (;;) {
185
+ if (!fs.isDir(path))
186
+ return true;
187
+ killCgroup(path, fs);
188
+ while (cgroupPopulated(path, fs) && Date.now() < deadline)
189
+ await sleep(POLL_MS);
190
+ const removed = removeTree(path, fs);
191
+ if (removed === true)
192
+ return true;
193
+ if (removed === 'fatal' || Date.now() >= deadline)
194
+ return false;
195
+ await sleep(POLL_MS);
196
+ }
197
+ }
198
+ catch {
199
+ return false;
200
+ }
201
+ }
202
+ /** Removes `path` and its child cgroups, deepest first. `busy` when a cgroup still holds a process. */
203
+ function removeTree(path, fs) {
204
+ for (const child of fs.children(path)) {
205
+ const removed = removeTree(child, fs);
206
+ if (removed !== true)
207
+ return removed;
208
+ }
209
+ try {
210
+ fs.rmdir(path);
211
+ return true;
212
+ }
213
+ catch (error) {
214
+ if (code(error) === 'ENOENT')
215
+ return true;
216
+ return code(error) === 'EBUSY' ? 'busy' : 'fatal';
217
+ }
218
+ }
219
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
220
+ //# sourceMappingURL=os-cgroup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"os-cgroup.js","sourceRoot":"","sources":["../../src/core/os-cgroup.ts"],"names":[],"mappings":"AAAA;8CAC8C;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,S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AC;IAAC,MAAM,CAAC;QAAC,OAAO,KAAK,CAAC;IAAC,CAAC;AAC3B,CAAC;AAED,uGAAuG;AACvG,SAAS,UAAU,CAAC,IAAY,EAAE,EAAY;IAC5C,KAAK,MAAM,KAAK,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACtC,MAAM,OAAO,GAAG,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACtC,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,OAAO,CAAC;IACvC,CAAC;IACD,IAAI,CAAC;QAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAAC,OAAO,IAAI,CAAC;IAAC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAClD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAC1C,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IACpD,CAAC;AACH,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC"}
@@ -0,0 +1,30 @@
1
+ /** Low-level Windows Job Object helpers shared by worker scopes (ADR 0032), per-session
2
+ * containment (hearsay-tools/squawk#1345) and `hsq job start` breakaway. */
3
+ import { type ChildProcess } from 'node:child_process';
4
+ export type JobKeepMode = 'keep' | 'keep-session';
5
+ /** What the backend runs; tests replace it. */
6
+ export type JobHelper = {
7
+ /** Start the keeper that creates and holds `job`; it ends when its stdin closes. */
8
+ keep: (job: string, mode?: JobKeepMode) => ChildProcess;
9
+ /** A synchronous helper operation's stdout. */
10
+ call: (args: string[], timeoutMs: number) => string;
11
+ };
12
+ export declare const realJobHelper: JobHelper;
13
+ /** The argv that runs `file args` inside one or more named jobs (`workerJob`, or `[workerJob, sessionJob]`).
14
+ * The command's own argv travels in a private file the helper reads and deletes, so the wrapper's
15
+ * command line stays short whatever the prompt. */
16
+ export declare function jobCommand(jobs: string | readonly string[], file: string, args: readonly string[]): [string, string[]];
17
+ /** Starts `file args` detached with `CREATE_BREAKAWAY_FROM_JOB`, returning the spawned PID.
18
+ * Breaks out of a session job (`JOB_OBJECT_LIMIT_BREAKAWAY_OK`) while remaining inside any outer
19
+ * worker job (which disallows breakaway). */
20
+ export declare function startBreakawayProcess(file: string, args: readonly string[], cwd: string, env: NodeJS.ProcessEnv, helper?: JobHelper): number;
21
+ /** Whether this host lets this user create a job and start a process inside it at creation. */
22
+ export declare function probeJobs(helper?: JobHelper): {
23
+ ok: true;
24
+ } | {
25
+ reason: string;
26
+ };
27
+ /** End every process in `job` and wait up to `waitMs`: true when none is left or the job is gone. */
28
+ export declare function terminateJob(job: string, waitMs: number, helper?: JobHelper): boolean;
29
+ /** Whether `job` holds no process (a job that is gone holds none). */
30
+ export declare function jobEmpty(job: string, helper?: JobHelper): boolean;
@@ -0,0 +1,80 @@
1
+ /** Low-level Windows Job Object helpers shared by worker scopes (ADR 0032), per-session
2
+ * containment (hearsay-tools/squawk#1345) and `hsq job start` breakaway. */
3
+ import { execFileSync, spawn } from 'node:child_process';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { writeFileSync } from 'node:fs';
6
+ import { tmpdir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { POWERSHELL, powershellEnv } from './process-stat.js';
10
+ const script = fileURLToPath(new URL('../../scripts/windows-worker-job.ps1', import.meta.url));
11
+ /** The helper DLL the probe compiled, passed by path to every later call: a worker's environment
12
+ * has its own temp directory, where the cache is not. */
13
+ let compiled;
14
+ const powershellArgs = () => ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, ...(compiled ? ['-Assembly', compiled] : [])];
15
+ export const realJobHelper = {
16
+ keep: (job, mode = 'keep') => {
17
+ const keeper = spawn(POWERSHELL, [...powershellArgs(), mode, job], { env: powershellEnv(), stdio: ['pipe', 'ignore', 'ignore'], windowsHide: true });
18
+ keeper.on('error', () => undefined);
19
+ keeper.unref();
20
+ // The pipe must not hold the controller's event loop open; its end is the job's end.
21
+ keeper.stdin?.unref?.();
22
+ return keeper;
23
+ },
24
+ call: (args, timeoutMs) => execFileSync(POWERSHELL, [...powershellArgs(), ...args], {
25
+ env: powershellEnv(), encoding: 'utf8', windowsHide: true, timeout: timeoutMs, maxBuffer: 64 * 1024,
26
+ }).trim(),
27
+ };
28
+ function writeArgvFile(prefix, file, args) {
29
+ const argvFile = join(tmpdir(), `${prefix}-${randomUUID()}`);
30
+ writeFileSync(argvFile, [file, ...args].join('\0'), { encoding: 'utf8', mode: 0o600, flag: 'wx' });
31
+ return argvFile;
32
+ }
33
+ /** The argv that runs `file args` inside one or more named jobs (`workerJob`, or `[workerJob, sessionJob]`).
34
+ * The command's own argv travels in a private file the helper reads and deletes, so the wrapper's
35
+ * command line stays short whatever the prompt. */
36
+ export function jobCommand(jobs, file, args) {
37
+ const jobArg = typeof jobs === 'string' ? jobs : jobs.join(',');
38
+ const argvFile = writeArgvFile('squawk-worker-argv', file, args);
39
+ return [POWERSHELL, [...powershellArgs(), 'run', jobArg, argvFile]];
40
+ }
41
+ /** Starts `file args` detached with `CREATE_BREAKAWAY_FROM_JOB`, returning the spawned PID.
42
+ * Breaks out of a session job (`JOB_OBJECT_LIMIT_BREAKAWAY_OK`) while remaining inside any outer
43
+ * worker job (which disallows breakaway). */
44
+ export function startBreakawayProcess(file, args, cwd, env, helper = realJobHelper) {
45
+ const argvFile = writeArgvFile('squawk-breakaway-argv', file, args);
46
+ const out = helper === realJobHelper
47
+ ? execFileSync(POWERSHELL, [...powershellArgs(), 'breakaway', argvFile], {
48
+ cwd, env: powershellEnv(env), encoding: 'utf8', windowsHide: true, timeout: 30_000, maxBuffer: 64 * 1024,
49
+ }).trim()
50
+ : helper.call(['breakaway', argvFile], 30_000);
51
+ const pid = Number(out);
52
+ if (!Number.isSafeInteger(pid) || pid <= 0)
53
+ throw new Error(`unexpected breakaway pid: ${out}`);
54
+ return pid;
55
+ }
56
+ /** Whether this host lets this user create a job and start a process inside it at creation. */
57
+ export function probeJobs(helper = realJobHelper) {
58
+ try {
59
+ const [state, ...dll] = helper.call(['probe'], 60_000).split(' ');
60
+ if (state !== 'ok')
61
+ return { reason: 'the job probe did not confirm' };
62
+ if (dll.length)
63
+ compiled = dll.join(' ');
64
+ return { ok: true };
65
+ }
66
+ catch (error) {
67
+ return { reason: `cannot run a process inside a job (${error.message.split('\n')[0]})` };
68
+ }
69
+ }
70
+ /** End every process in `job` and wait up to `waitMs`: true when none is left or the job is gone. */
71
+ export function terminateJob(job, waitMs, helper = realJobHelper) {
72
+ const state = helper.call(['terminate', job, String(waitMs)], waitMs + 60_000);
73
+ return state === 'empty' || state === 'absent';
74
+ }
75
+ /** Whether `job` holds no process (a job that is gone holds none). */
76
+ export function jobEmpty(job, helper = realJobHelper) {
77
+ const state = helper.call(['query', job], 60_000);
78
+ return state === 'absent' || state === '0';
79
+ }
80
+ //# sourceMappingURL=os-win-job.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"os-win-job.js","sourceRoot":"","sources":["../../src/core/os-win-job.ts"],"names":[],"mappings":"AAAA;4EAC4E;AAC5E,OAAO,EAAE,YAAY,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE9D,MAAM,M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AI,CAAC,CAAC,WAAW,EAAE,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;IAC/E,OAAO,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,QAAQ,CAAC;AACjD,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,QAAQ,CAAC,GAAW,EAAE,MAAM,GAAc,aAAa;IACrE,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;IAClD,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,GAAG,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Per-session OS process containment (hearsay-tools/squawk#1345).
3
+ *
4
+ * Matches ADR 0032's host backends without scanning host processes:
5
+ * - Linux with delegated cgroup v2: each session spawns inside `squawk-session-<id>`, nested under
6
+ * the worker's cgroup when inside a worker.
7
+ * - Windows with Job Objects: each session spawns inside `Local\squawk-session-<id>` (with
8
+ * `JOB_OBJECT_LIMIT_BREAKAWAY_OK` and without `KILL_ON_JOB_CLOSE`), nested under the worker's
9
+ * Job Object when inside a worker.
10
+ * - macOS and Linux without delegation: degrades quietly to existing process-group cleanup.
11
+ *
12
+ * On abnormal exit (non-zero exit, unexpected signal, Stop or forced kill), every process left in
13
+ * the session container ends (SIGTERM grace, then SIGKILL / TerminateJobObject). On normal exit,
14
+ * surviving detached daemons are evacuated to the parent container so they survive while the
15
+ * empty session container is removed.
16
+ */
17
+ import type { ChildProcess } from 'node:child_process';
18
+ import { type CgroupFs } from './os-cgroup.ts';
19
+ import { type JobHelper } from './os-win-job.ts';
20
+ export declare const SESSION_CGROUP_PREFIX = "squawk-session-";
21
+ export declare const SESSION_JOB_PREFIX = "Local\\squawk-session-";
22
+ export type SessionContainmentHost = {
23
+ backend: 'cgroup';
24
+ base: string;
25
+ } | {
26
+ backend: 'job';
27
+ } | {
28
+ backend: 'none';
29
+ };
30
+ export type SessionContainer = {
31
+ kind: 'cgroup';
32
+ path: string;
33
+ parent: string;
34
+ fs: CgroupFs;
35
+ } | {
36
+ kind: 'job';
37
+ name: string;
38
+ keeper: ChildProcess;
39
+ helper: JobHelper;
40
+ };
41
+ /** Wait until every tracked Windows session keeper has exited, bounded by `timeoutMs`. */
42
+ export declare function waitForSessionKeepers(timeoutMs?: number): Promise<void>;
43
+ /** Detect once per controller whether this host supports OS session containment. */
44
+ export declare function sessionContainment(fs?: CgroupFs, helper?: JobHelper): SessionContainmentHost;
45
+ /** Tests override or reset (`undefined`) the detected host containment backend. */
46
+ export declare function setSessionContainment(value: SessionContainmentHost | undefined): void;
47
+ /** True when this host places sessions in an OS process container (`cgroup` or `job`). */
48
+ export declare function isSessionContained(): boolean;
49
+ /** Whether `bin` resolves to an executable file on this host. Relative and empty PATH segments
50
+ * resolve against the child `cwd` to match native `execvp` / Windows lookup. Missing binaries
51
+ * bypass container wrappers so `spawn` emits native `ENOENT`/`EACCES` directly. */
52
+ export declare function executableReachable(bin: string, cwd: string, env: NodeJS.ProcessEnv): boolean;
53
+ export interface PrepareContainerOptions {
54
+ cwd: string;
55
+ env: NodeJS.ProcessEnv;
56
+ parentCgroup?: string | undefined;
57
+ parentJob?: string | undefined;
58
+ fs?: CgroupFs | undefined;
59
+ helper?: JobHelper | undefined;
60
+ }
61
+ export interface PreparedSessionLaunch {
62
+ file: string;
63
+ argv: string[];
64
+ container: SessionContainer | undefined;
65
+ }
66
+ /** Wraps `(bin, args)` in a per-session OS container when supported and `bin` is reachable. */
67
+ export declare function prepareSessionContainer(bin: string, args: readonly string[], options: PrepareContainerOptions): PreparedSessionLaunch;
68
+ /** Clean up a container whose spawn never succeeded or returned a non-ChildProcess mock. */
69
+ export declare function discardSessionContainer(container: SessionContainer | undefined): void;
70
+ /** Normal session exit: evacuate surviving detached processes up to the parent container and
71
+ * remove the empty session container without signalling them. */
72
+ export declare function releaseSessionContainer(container: SessionContainer | undefined): void;
73
+ /** Forward a signal to live processes in a session container (used on Squawk shutdown or probe kill). */
74
+ export declare function signalSessionContainer(container: SessionContainer | undefined, signal: NodeJS.Signals): void;
75
+ /** Abnormal session exit: SIGTERM remaining processes in the container, wait up to `graceMs`
76
+ * (exiting immediately once empty), then force-kill and remove the container. Uses referenced
77
+ * timers so a short-lived host (`hsq run`) stays up until detached MCP servers are gone. */
78
+ export declare function reapSessionContainer(container: SessionContainer | undefined, graceMs: number): void;