@agentshouse/kit 0.2.1-cd646adba3f64 → 0.2.1-cdc381ebf021f

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 (141) hide show
  1. package/README.md +42 -48
  2. package/dist/acp.js +102 -108
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +227 -68
  5. package/dist/api.js +19 -10
  6. package/dist/app-git.js +10 -26
  7. package/dist/bridge.js +18 -47
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +157 -100
  12. package/dist/codex-main.js +58 -0
  13. package/dist/connect.js +108 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +106 -0
  16. package/dist/conversations.js +815 -335
  17. package/dist/copies.js +439 -232
  18. package/dist/earlier.js +263 -0
  19. package/dist/end.js +23 -5
  20. package/dist/events.js +793 -0
  21. package/dist/files.js +139 -17
  22. package/dist/git.js +57 -21
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +122 -8
  25. package/dist/house-cli.js +359 -0
  26. package/dist/house-main.js +7 -159
  27. package/dist/instructions.js +7 -11
  28. package/dist/kit-cli.js +78 -0
  29. package/dist/kit-main.js +8 -22
  30. package/dist/login.js +132 -107
  31. package/dist/logout.js +15 -17
  32. package/dist/mcp.js +6 -2
  33. package/dist/owner.js +46 -0
  34. package/dist/placement.js +25 -0
  35. package/dist/relay.js +33 -2
  36. package/dist/resident.js +160 -58
  37. package/dist/scope.js +214 -0
  38. package/dist/scripts.js +303 -0
  39. package/dist/secret-input.js +1 -1
  40. package/dist/settings.js +188 -0
  41. package/dist/sign-in.js +40 -33
  42. package/dist/silence.js +28 -0
  43. package/dist/skills.js +49 -35
  44. package/dist/supervisor.js +163 -0
  45. package/dist/transcription.js +90 -47
  46. package/dist/translate.js +19 -16
  47. package/dist/update.js +119 -102
  48. package/dist/wire.js +32 -0
  49. package/dist/work.js +353 -0
  50. package/dist/workspace.js +103 -0
  51. package/package.json +25 -21
  52. package/dist/authority-main.js +0 -22
  53. package/dist/blocks.js +0 -51
  54. package/dist/bootstrap.json +0 -24
  55. package/dist/clis-main.js +0 -23
  56. package/dist/configure-main.js +0 -6
  57. package/dist/enrol-main.js +0 -4
  58. package/dist/stream.js +0 -72
  59. package/how-we-work.md +0 -23
  60. package/skills/ask-matt/LICENSE +0 -21
  61. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  62. package/skills/ask-matt/SKILL.md +0 -91
  63. package/skills/ask-matt/agents/openai.yaml +0 -4
  64. package/skills/code-review/LICENSE +0 -21
  65. package/skills/code-review/SKILL.md +0 -89
  66. package/skills/code-review/agents/openai.yaml +0 -3
  67. package/skills/codebase-design/DEEPENING.md +0 -37
  68. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  69. package/skills/codebase-design/LICENSE +0 -21
  70. package/skills/codebase-design/SKILL.md +0 -116
  71. package/skills/codebase-design/agents/openai.yaml +0 -3
  72. package/skills/diagnosing-bugs/LICENSE +0 -21
  73. package/skills/diagnosing-bugs/SKILL.md +0 -140
  74. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  75. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  76. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  77. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  78. package/skills/domain-modeling/LICENSE +0 -21
  79. package/skills/domain-modeling/SKILL.md +0 -76
  80. package/skills/domain-modeling/agents/openai.yaml +0 -3
  81. package/skills/grill-me/LICENSE +0 -21
  82. package/skills/grill-me/SKILL.md +0 -8
  83. package/skills/grill-me/agents/openai.yaml +0 -4
  84. package/skills/grill-with-docs/LICENSE +0 -21
  85. package/skills/grill-with-docs/SKILL.md +0 -8
  86. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  87. package/skills/grilling/LICENSE +0 -21
  88. package/skills/grilling/SKILL.md +0 -30
  89. package/skills/grilling/agents/openai.yaml +0 -3
  90. package/skills/handoff/LICENSE +0 -21
  91. package/skills/handoff/SKILL.md +0 -17
  92. package/skills/handoff/agents/openai.yaml +0 -4
  93. package/skills/implement/LICENSE +0 -21
  94. package/skills/implement/SKILL.md +0 -16
  95. package/skills/implement/agents/openai.yaml +0 -4
  96. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  97. package/skills/improve-codebase-architecture/LICENSE +0 -21
  98. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  99. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  100. package/skills/prototype/LICENSE +0 -21
  101. package/skills/prototype/LOGIC.md +0 -67
  102. package/skills/prototype/SKILL.md +0 -28
  103. package/skills/prototype/UI.md +0 -112
  104. package/skills/prototype/agents/openai.yaml +0 -3
  105. package/skills/research/LICENSE +0 -21
  106. package/skills/research/SKILL.md +0 -14
  107. package/skills/research/agents/openai.yaml +0 -3
  108. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  109. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  110. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  111. package/skills/tdd/LICENSE +0 -21
  112. package/skills/tdd/SKILL.md +0 -40
  113. package/skills/tdd/agents/openai.yaml +0 -3
  114. package/skills/tdd/mocking.md +0 -59
  115. package/skills/tdd/tests.md +0 -77
  116. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  117. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  118. package/skills/teach/LICENSE +0 -21
  119. package/skills/teach/MISSION-FORMAT.md +0 -31
  120. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  121. package/skills/teach/SKILL.md +0 -141
  122. package/skills/teach/agents/openai.yaml +0 -4
  123. package/skills/to-questionnaire/LICENSE +0 -21
  124. package/skills/to-questionnaire/SKILL.md +0 -55
  125. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  126. package/skills/to-spec/LICENSE +0 -21
  127. package/skills/to-spec/SKILL.md +0 -76
  128. package/skills/to-spec/agents/openai.yaml +0 -4
  129. package/skills/to-tickets/LICENSE +0 -21
  130. package/skills/to-tickets/SKILL.md +0 -106
  131. package/skills/to-tickets/agents/openai.yaml +0 -4
  132. package/skills/wait-what/LICENSE +0 -21
  133. package/skills/wait-what/SKILL.md +0 -8
  134. package/skills/wait-what/agents/openai.yaml +0 -4
  135. package/skills/wayfinder/LICENSE +0 -21
  136. package/skills/wayfinder/SKILL.md +0 -129
  137. package/skills/wayfinder/agents/openai.yaml +0 -4
  138. package/skills/writing-for-agents/LICENSE +0 -21
  139. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  140. package/skills/writing-for-agents/SKILL.md +0 -83
  141. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/resident.js CHANGED
@@ -2,51 +2,74 @@ import { once } from 'node:events';
2
2
  import { watch } from 'node:fs';
3
3
  import { mkdir, rm, writeFile } from 'node:fs/promises';
4
4
  import { createServer } from 'node:http';
5
- import { extname, join } from 'node:path';
5
+ import { dirname, extname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { killDescendants } from './acp.js';
8
7
  import { Agents } from './agents.js';
9
8
  import { house } from './api.js';
10
9
  import { received } from './bridge.js';
11
10
  import { Conversations } from './conversations.js';
12
11
  import { LocalCopies } from './copies.js';
13
- import { agentBase, enrolled, kitHome } from './home.js';
12
+ import { restart } from './end.js';
13
+ import { agentBase, enrolled, kitHome, ownerSocket, readEnrolment } from './home.js';
14
+ import { Calls } from './calls.js';
15
+ import { KIT_RELEASE } from './clis.js';
16
+ import { moveEarlier } from './earlier.js';
17
+ import { holdOwner } from './owner.js';
18
+ import { killDescendants } from './scope.js';
19
+ import { removeInputs, Scripts } from './scripts.js';
20
+ import { applySettings, enrolledRoutes, resumeWorkspaceMove } from './settings.js';
14
21
  import { quoted } from './shell.js';
15
22
  import { SignIns } from './sign-in.js';
16
23
  import { placeSkillSet } from './skills.js';
17
- import { holdStream } from './stream.js';
18
- import { Updates } from './update.js';
24
+ import { holdConnection } from './connection.js';
25
+ import { KitUpdate } from './update.js';
26
+ import { takeUnservedRelease } from './wire.js';
27
+ import { codexLauncher } from './work.js';
19
28
  function report(error) {
20
29
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
21
30
  }
22
31
  function logged(work) {
23
32
  work.catch(report);
24
33
  }
25
- async function installShim() {
26
- const main = fileURLToPath(new URL(`./git-main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
27
- await mkdir(join(kitHome(), 'shim'), { recursive: true });
28
- await writeFile(join(kitHome(), 'shim', 'git'), `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, {
29
- mode: 0o755,
30
- });
34
+ async function installShim(path, module) {
35
+ const main = fileURLToPath(new URL(`./${module}${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
36
+ await mkdir(dirname(path), { recursive: true });
37
+ await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
31
38
  }
32
- async function serveOwner(copies) {
33
- const socketPath = join(kitHome(), 'owner.sock');
34
- await rm(socketPath, { force: true });
39
+ async function serveOwner(lock, copies, settling) {
35
40
  const server = createServer(async (request, response) => {
36
41
  try {
37
- if (request.url !== '/git/push') {
42
+ const text = await received(request);
43
+ let answered;
44
+ if (request.url === '/resident') {
45
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ pid: process.pid, release: KIT_RELEASE }));
46
+ return;
47
+ }
48
+ if (request.url === '/git/fetch') {
49
+ answered = await copies.fetch();
50
+ }
51
+ else if (request.url === '/git/push') {
52
+ const { cwd, commit } = JSON.parse(text);
53
+ answered = await copies.push(cwd, commit, copies.owner);
54
+ }
55
+ else if (request.url === '/settings') {
56
+ const applied = await settling.settle(JSON.parse(text));
57
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(applied), () => settling.answered(applied));
58
+ return;
59
+ }
60
+ else {
38
61
  response.writeHead(404).end();
39
62
  return;
40
63
  }
41
- const { cwd, commit } = JSON.parse(await received(request));
42
- const pushed = await copies.push(cwd, commit, copies.owner);
43
- response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(pushed));
64
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answered));
44
65
  }
45
66
  catch (error) {
46
67
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
47
68
  }
48
69
  });
49
- server.listen(socketPath);
70
+ server.on('close', () => lock.close());
71
+ await rm(ownerSocket(), { force: true });
72
+ server.listen(ownerSocket());
50
73
  await once(server, 'listening');
51
74
  }
52
75
  function connected() {
@@ -65,75 +88,154 @@ function connected() {
65
88
  resolve();
66
89
  });
67
90
  }
68
- export async function resident() {
91
+ async function started() {
69
92
  await connected();
70
- watch(kitHome(), () => {
71
- if (enrolled())
93
+ await placeSkillSet((await readEnrolment()).house);
94
+ await mkdir(agentBase(), { recursive: true });
95
+ await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
96
+ await installShim(codexLauncher(), 'codex-main');
97
+ }
98
+ export async function resident() {
99
+ await moveEarlier();
100
+ await mkdir(kitHome(), { recursive: true, mode: 0o700 });
101
+ const lock = await holdOwner();
102
+ await resumeWorkspaceMove();
103
+ const copies = new LocalCopies(house);
104
+ await copies.load();
105
+ let running = null;
106
+ let settings = Promise.resolve();
107
+ const settle = (change) => {
108
+ const applied = settings.then(() => applySettings(change, {
109
+ working: () => running !== null && (running.conversations.turnOpen() || running.calls.busy()),
110
+ end: () => {
111
+ running?.conversations.stopped();
112
+ killDescendants();
113
+ },
114
+ routes: async () => {
115
+ if (running === null)
116
+ return enrolledRoutes();
117
+ await running.agents.read();
118
+ return running.agents.desired.routes;
119
+ },
120
+ }));
121
+ settings = applied.catch(() => undefined);
122
+ return applied.then((answer) => {
123
+ if ('settings' in answer && !answer.moved)
124
+ running?.agents.report().catch(report);
125
+ return answer;
126
+ });
127
+ };
128
+ const answered = (applied) => {
129
+ if ('settings' in applied ? !applied.moved : !applied.ended)
72
130
  return;
73
- killDescendants();
131
+ const ended = 'settings' in applied
132
+ ? `the workspace moved to ${applied.settings.workspace}; its supervisor starts Kit there`
133
+ : 'the workspace stays where it was; its supervisor starts Kit again';
134
+ if (running === null)
135
+ restart(ended);
136
+ else
137
+ void running.stop(() => restart(ended));
138
+ };
139
+ await serveOwner(lock, copies, { settle, answered });
140
+ await copies.swept();
141
+ await started().catch((error) => {
142
+ report(error);
74
143
  process.exit(1);
75
144
  });
76
- await placeSkillSet();
77
- await mkdir(agentBase(), { recursive: true });
78
145
  process.env.HOUSE_KIT_RESIDENT = String(process.pid);
79
- const agents = new Agents(house);
80
- const copies = new LocalCopies(house);
81
- await copies.load();
82
- await installShim();
83
- await serveOwner(copies);
84
- let stream = null;
146
+ const agents = new Agents(house, () => changed());
147
+ let connection = null;
85
148
  let reported = false;
86
- const idle = () => conversations.idle() && signIns.idle();
149
+ let stopping = false;
150
+ const stop = async (then) => {
151
+ if (stopping)
152
+ return;
153
+ stopping = true;
154
+ conversations.stopped();
155
+ killDescendants();
156
+ await connection?.close();
157
+ then();
158
+ };
159
+ const idle = () => calls.idle() && conversations.idle() && agents.idle();
87
160
  const changed = () => {
88
161
  if (!idle()) {
89
162
  reported = false;
90
163
  }
164
+ else if (update.placedRelease() !== null && conversations.quiet() && process.env.HOUSE_KIT_SANDBOX !== '1') {
165
+ const placed = update.placedRelease();
166
+ void stop(() => restart(`Kit ${placed} is placed; its supervisor starts it`));
167
+ }
91
168
  else if (!reported) {
92
169
  reported = true;
93
- logged(house.deliver('/kit/idle', {}, idle));
170
+ logged(house.deliver('kits/report-idle', {}, idle));
94
171
  }
95
172
  };
173
+ const calls = new Calls(house, changed);
96
174
  const conversations = new Conversations({
97
175
  house,
98
176
  agents,
99
177
  copies,
100
- send: (frame) => stream?.send(frame) ?? false,
178
+ calls,
179
+ send: (oneWayCall) => connection?.send(oneWayCall) ?? false,
101
180
  changed,
102
181
  });
103
- const signIns = new SignIns(house, agents, changed);
104
- const updates = new Updates(house);
182
+ const signIns = new SignIns(house, agents, calls);
183
+ const update = new KitUpdate(calls);
184
+ takeUnservedRelease((release) => logged(update.takeRefused(release)));
185
+ removeInputs();
186
+ const scripts = new Scripts(calls, (oneWayCall) => connection?.send(oneWayCall) ?? false);
187
+ running = { conversations, agents, calls, stop };
105
188
  for (const signal of ['SIGTERM', 'SIGINT']) {
106
189
  process.once(signal, () => {
107
- killDescendants();
108
- process.kill(process.pid, signal);
190
+ void stop(() => {
191
+ removeInputs();
192
+ process.kill(process.pid, signal);
193
+ });
109
194
  });
110
195
  }
111
- await house.deliver('/kit/restarted', {}).catch(report);
112
- await updates.resumed().catch(report);
196
+ const unenrolled = () => {
197
+ if (!enrolled())
198
+ void stop(() => process.exit(1));
199
+ };
200
+ watch(kitHome(), unenrolled);
201
+ unenrolled();
202
+ await house.deliver('kits/report-restart', {}).catch(report);
113
203
  logged(agents.refresh());
114
- stream = holdStream({
204
+ agents.keepCurrent(() => process.env.HOUSE_KIT_SANDBOX === '1' && reported);
205
+ connection = holdConnection({
115
206
  opened: () => {
116
207
  conversations.opened();
208
+ scripts.connected();
117
209
  changed();
118
- logged(copies.select());
210
+ logged(copies.connected());
119
211
  },
120
- frame: (arrived) => {
121
- if (arrived.type === 'work_available' && arrived.subject === 'agents')
122
- logged(agents.refresh());
123
- if (arrived.type === 'work_available' && arrived.subject === 'local_copy')
124
- logged(copies.select());
125
- if (arrived.type === 'entries') {
126
- copies.entries(arrived);
127
- }
128
- if (arrived.type === 'input') {
129
- reported = false;
130
- if (arrived.kind === 'sign_in')
131
- signIns.start(arrived);
132
- else if (arrived.kind === 'update')
133
- updates.start(arrived);
134
- else
135
- conversations.input(arrived);
212
+ closed: () => scripts.disconnected(),
213
+ call: (call) => {
214
+ if (call.kind === 'sign_in')
215
+ signIns.start(call);
216
+ else if (call.kind === 'update')
217
+ update.take(call);
218
+ else if (call.kind === 'settings') {
219
+ void calls.carrySettings(call.input_id, async () => {
220
+ const applied = await settle(call);
221
+ const result = 'refused' in applied ? { refused: applied.refused } : { settings: applied.settings };
222
+ if ('settings' in applied ? !applied.moved : !applied.ended)
223
+ return { result };
224
+ calls.keepResult(call.input_id, result);
225
+ return new Promise(() => answered(applied));
226
+ });
136
227
  }
228
+ else if (call.kind === 'run_wizard' || call.kind === 'run_function')
229
+ scripts.start(call);
230
+ else
231
+ conversations.call(call);
232
+ },
233
+ oneWayCall: (oneWayCall) => {
234
+ if (oneWayCall.type === 'watching')
235
+ conversations.watching(oneWayCall.watching);
236
+ if (oneWayCall.type === 'work_available' && oneWayCall.subject === 'agents')
237
+ logged(agents.refresh());
238
+ scripts.notified(oneWayCall);
137
239
  },
138
240
  });
139
241
  }
package/dist/scope.js ADDED
@@ -0,0 +1,214 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdirSync, readdirSync, readFileSync, realpathSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ const LISTING_BYTES = 1 << 28;
5
+ const CGROUPS = '/sys/fs/cgroup';
6
+ const GONE = new Set(['ENOENT', 'ESRCH']);
7
+ const EXITED = new Set(['Z', 'X']);
8
+ function failure(error) {
9
+ return error.code ?? '';
10
+ }
11
+ function listed(environment) {
12
+ const found = new Map();
13
+ const output = execFileSync('ps', [environment ? '-AEww' : '-Aww', '-o', 'pid=,ppid=,sess=,command='], {
14
+ encoding: 'utf8',
15
+ maxBuffer: LISTING_BYTES,
16
+ });
17
+ for (const line of output.split('\n')) {
18
+ const fields = /^\s*(\d+)\s+(\d+)\s+(\S+)\s?(.*)$/.exec(line);
19
+ if (fields !== null)
20
+ found.set(Number(fields[1]), { parent: Number(fields[2]), session: fields[3], command: fields[4] });
21
+ }
22
+ return found;
23
+ }
24
+ function read(pid) {
25
+ try {
26
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
27
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
28
+ if (EXITED.has(fields[0]))
29
+ return null;
30
+ const command = readFileSync(`/proc/${pid}/cmdline`, 'utf8').replaceAll('\0', ' ');
31
+ return { parent: Number(fields[1]), session: fields[3], command };
32
+ }
33
+ catch (error) {
34
+ if (GONE.has(failure(error)))
35
+ return null;
36
+ throw error;
37
+ }
38
+ }
39
+ function processes() {
40
+ if (process.platform === 'darwin')
41
+ return listed(false);
42
+ const found = new Map();
43
+ for (const entry of readdirSync('/proc')) {
44
+ const running = /^\d+$/.test(entry) ? read(entry) : null;
45
+ if (running !== null)
46
+ found.set(Number(entry), running);
47
+ }
48
+ return found;
49
+ }
50
+ function descendants(roots, table = processes()) {
51
+ const children = new Map();
52
+ for (const [pid, { parent }] of table)
53
+ children.set(parent, [...(children.get(parent) ?? []), pid]);
54
+ const tree = [];
55
+ const pending = roots.flatMap((root) => children.get(root) ?? []);
56
+ while (pending.length > 0) {
57
+ const pid = pending.pop();
58
+ tree.push(pid);
59
+ pending.push(...(children.get(pid) ?? []));
60
+ }
61
+ return tree;
62
+ }
63
+ function marked(marker, doubted) {
64
+ if (process.platform === 'darwin') {
65
+ return [...listed(true)].filter(([, { command }]) => ` ${command} `.includes(` ${marker} `)).map(([pid]) => pid);
66
+ }
67
+ return readdirSync('/proc')
68
+ .filter((entry) => /^\d+$/.test(entry) && carries(entry, marker, doubted))
69
+ .map(Number);
70
+ }
71
+ function carries(pid, marker, doubted) {
72
+ try {
73
+ return readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0').includes(marker);
74
+ }
75
+ catch (error) {
76
+ if (GONE.has(failure(error)))
77
+ return false;
78
+ if (failure(error) !== 'EACCES')
79
+ throw error;
80
+ return doubted && statSync(`/proc/${pid}`, { throwIfNoEntry: false })?.uid === process.getuid();
81
+ }
82
+ }
83
+ function killAll(pids) {
84
+ for (const pid of pids) {
85
+ for (const target of [-pid, pid]) {
86
+ try {
87
+ process.kill(target, 'SIGKILL');
88
+ }
89
+ catch { }
90
+ }
91
+ }
92
+ }
93
+ export function killTree(child) {
94
+ killAll([child.pid, ...descendants([child.pid])]);
95
+ }
96
+ export function killMarked(marker) {
97
+ const pids = marked(marker, false);
98
+ killAll([...pids, ...descendants(pids)]);
99
+ }
100
+ export function killDescendants() {
101
+ const pids = marked(`HOUSE_KIT_RESIDENT=${process.pid}`, false);
102
+ killAll([...pids, ...descendants([process.pid, ...pids])]);
103
+ }
104
+ function ownGroup() {
105
+ if (process.platform !== 'linux')
106
+ return null;
107
+ try {
108
+ const line = readFileSync('/proc/self/cgroup', 'utf8')
109
+ .split('\n')
110
+ .find((entry) => entry.startsWith('0::'));
111
+ return line === undefined ? null : join(CGROUPS, line.slice(3));
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ }
117
+ function members(group) {
118
+ const pids = readFileSync(join(group, 'cgroup.procs'), 'utf8').split('\n').filter(Boolean).map(Number);
119
+ for (const entry of readdirSync(group, { withFileTypes: true })) {
120
+ if (entry.isDirectory())
121
+ pids.push(...members(join(group, entry.name)));
122
+ }
123
+ return pids;
124
+ }
125
+ function besideCli(cli) {
126
+ try {
127
+ return `${realpathSync(cli)}-`;
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ }
133
+ export class Scope {
134
+ marker;
135
+ helpers;
136
+ group;
137
+ session = null;
138
+ recorded = null;
139
+ constructor(marker, name, cli) {
140
+ this.marker = marker;
141
+ this.helpers = besideCli(cli);
142
+ const own = ownGroup();
143
+ this.group = own === null ? null : join(own, name);
144
+ try {
145
+ if (this.group !== null)
146
+ mkdirSync(this.group);
147
+ }
148
+ catch {
149
+ this.group = null;
150
+ }
151
+ }
152
+ command(command, args) {
153
+ if (this.group === null)
154
+ return [command, args];
155
+ return ['/bin/sh', ['-c', 'echo $$ > "$0/cgroup.procs" 2>/dev/null; exec "$@"', this.group, command, ...args]];
156
+ }
157
+ entered(pid) {
158
+ this.session = process.platform === 'darwin' ? (listed(false).get(pid)?.session ?? null) : String(pid);
159
+ if (this.group === null)
160
+ return;
161
+ const joined = readFileSync(`/proc/${pid}/cgroup`, 'utf8').split('\n').find((entry) => entry.startsWith('0::'));
162
+ if (joined !== undefined && join(CGROUPS, joined.slice(3)) === this.group)
163
+ return;
164
+ this.close();
165
+ this.group = null;
166
+ }
167
+ record() {
168
+ const found = this.found();
169
+ if (found === null)
170
+ return;
171
+ this.recorded = new Set([...found].filter(([, { session }]) => session === this.session).map(([pid]) => pid));
172
+ }
173
+ working() {
174
+ const found = this.found();
175
+ if (found === null)
176
+ return true;
177
+ if (this.recorded === null)
178
+ return found.size > 0;
179
+ return [...found].some(([pid, { session, command }]) => session !== this.session || !(this.recorded.has(pid) || (this.helpers !== null && command.startsWith(this.helpers))));
180
+ }
181
+ empty() {
182
+ return this.found()?.size === 0;
183
+ }
184
+ kill() {
185
+ killMarked(this.marker);
186
+ if (this.group === null)
187
+ return;
188
+ try {
189
+ writeFileSync(join(this.group, 'cgroup.kill'), '1');
190
+ }
191
+ catch {
192
+ killAll([...(this.found()?.keys() ?? [])]);
193
+ }
194
+ }
195
+ close() {
196
+ if (this.group === null)
197
+ return;
198
+ try {
199
+ rmdirSync(this.group);
200
+ }
201
+ catch { }
202
+ }
203
+ found() {
204
+ try {
205
+ const table = processes();
206
+ const roots = this.group === null ? marked(this.marker, true) : members(this.group);
207
+ const pids = this.group === null ? [...roots, ...descendants(roots, table)] : roots;
208
+ return new Map(pids.flatMap((pid) => (table.has(pid) ? [[pid, table.get(pid)]] : [])));
209
+ }
210
+ catch {
211
+ return null;
212
+ }
213
+ }
214
+ }