@agentshouse/kit 0.2.1-alpha.8 → 0.2.1-c05cd91c26b1d

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 (150) hide show
  1. package/README.md +46 -21
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +48 -85
  4. package/dist/agents.js +312 -53
  5. package/dist/api.js +40 -4
  6. package/dist/app-git.js +48 -0
  7. package/dist/bootstrap.json +10 -14
  8. package/dist/bridge.js +92 -77
  9. package/dist/chatgpt.js +32 -0
  10. package/dist/clis-main.js +23 -0
  11. package/dist/clis.js +213 -71
  12. package/dist/codex-main.js +58 -0
  13. package/dist/configure-main.js +6 -0
  14. package/dist/conversations.js +429 -232
  15. package/dist/copies.js +233 -171
  16. package/dist/end.js +23 -0
  17. package/dist/enrol-main.js +7 -1
  18. package/dist/events.js +525 -0
  19. package/dist/files.js +24 -3
  20. package/dist/git-main.js +2 -2
  21. package/dist/git.js +15 -9
  22. package/dist/home.js +141 -10
  23. package/dist/house-cli.js +291 -0
  24. package/dist/house-main.js +5 -102
  25. package/dist/inputs.js +37 -0
  26. package/dist/instructions.js +10 -31
  27. package/dist/kit-cli.js +68 -0
  28. package/dist/kit-main.js +8 -16
  29. package/dist/login.js +129 -94
  30. package/dist/logout.js +19 -0
  31. package/dist/mcp.js +39 -0
  32. package/dist/operation.js +7 -4
  33. package/dist/parts.js +82 -0
  34. package/dist/placement.js +30 -0
  35. package/dist/refusals.js +53 -0
  36. package/dist/relay.js +20 -0
  37. package/dist/resident.js +123 -40
  38. package/dist/scope.js +203 -0
  39. package/dist/secret-input.js +7 -2
  40. package/dist/service-main.js +9 -0
  41. package/dist/service.js +33 -0
  42. package/dist/shell.js +3 -0
  43. package/dist/sign-in.js +47 -28
  44. package/dist/skills.js +147 -0
  45. package/dist/stream.js +89 -13
  46. package/dist/transcription.js +170 -0
  47. package/dist/update.js +138 -0
  48. package/dist/wire.js +6 -0
  49. package/dist/work.js +346 -0
  50. package/how-we-work.md +33 -0
  51. package/package.json +8 -8
  52. package/skills/ask-matt/LICENSE +21 -0
  53. package/skills/ask-matt/PHASE-BOUNDARIES.md +55 -0
  54. package/skills/ask-matt/SKILL.md +97 -0
  55. package/skills/ask-matt/agents/openai.yaml +5 -0
  56. package/skills/code-review/LICENSE +21 -0
  57. package/skills/code-review/SKILL.md +89 -0
  58. package/skills/code-review/agents/openai.yaml +3 -0
  59. package/skills/codebase-design/DEEPENING.md +37 -0
  60. package/skills/codebase-design/DESIGN-IT-TWICE.md +44 -0
  61. package/skills/codebase-design/LICENSE +21 -0
  62. package/skills/codebase-design/SKILL.md +114 -0
  63. package/skills/codebase-design/agents/openai.yaml +3 -0
  64. package/skills/diagnosing-bugs/LICENSE +21 -0
  65. package/skills/diagnosing-bugs/SKILL.md +138 -0
  66. package/skills/diagnosing-bugs/agents/openai.yaml +3 -0
  67. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +44 -0
  68. package/skills/domain-modeling/ADR-FORMAT.md +47 -0
  69. package/skills/domain-modeling/GLOSSARY-FORMAT.md +60 -0
  70. package/skills/domain-modeling/LICENSE +21 -0
  71. package/skills/domain-modeling/SKILL.md +74 -0
  72. package/skills/domain-modeling/agents/openai.yaml +3 -0
  73. package/skills/grill-me/LICENSE +21 -0
  74. package/skills/grill-me/SKILL.md +7 -0
  75. package/skills/grill-me/agents/openai.yaml +5 -0
  76. package/skills/grill-with-docs/LICENSE +21 -0
  77. package/skills/grill-with-docs/SKILL.md +7 -0
  78. package/skills/grill-with-docs/agents/openai.yaml +5 -0
  79. package/skills/grilling/LICENSE +21 -0
  80. package/skills/grilling/SKILL.md +30 -0
  81. package/skills/grilling/agents/openai.yaml +3 -0
  82. package/skills/handoff/LICENSE +21 -0
  83. package/skills/handoff/SKILL.md +16 -0
  84. package/skills/handoff/agents/openai.yaml +5 -0
  85. package/skills/implement/LICENSE +21 -0
  86. package/skills/implement/SKILL.md +17 -0
  87. package/skills/implement/agents/openai.yaml +5 -0
  88. package/skills/implement-spec/LICENSE +21 -0
  89. package/skills/implement-spec/SKILL.md +40 -0
  90. package/skills/implement-spec/agents/openai.yaml +5 -0
  91. package/skills/improve-codebase-architecture/HTML-REPORT.md +123 -0
  92. package/skills/improve-codebase-architecture/LICENSE +21 -0
  93. package/skills/improve-codebase-architecture/SKILL.md +71 -0
  94. package/skills/improve-codebase-architecture/agents/openai.yaml +5 -0
  95. package/skills/pr/CREDITS.md +3 -0
  96. package/skills/pr/LICENSE +21 -0
  97. package/skills/pr/SKILL.md +170 -0
  98. package/skills/pr/agents/openai.yaml +3 -0
  99. package/skills/prototype/LICENSE +21 -0
  100. package/skills/prototype/LOGIC.md +67 -0
  101. package/skills/prototype/SKILL.md +26 -0
  102. package/skills/prototype/UI.md +112 -0
  103. package/skills/prototype/agents/openai.yaml +3 -0
  104. package/skills/research/LICENSE +21 -0
  105. package/skills/research/SKILL.md +12 -0
  106. package/skills/research/agents/openai.yaml +3 -0
  107. package/skills/retro/LICENSE +21 -0
  108. package/skills/retro/SKILL.md +44 -0
  109. package/skills/retro/agents/openai.yaml +5 -0
  110. package/skills/tdd/LICENSE +21 -0
  111. package/skills/tdd/SKILL.md +38 -0
  112. package/skills/tdd/agents/openai.yaml +3 -0
  113. package/skills/tdd/mocking.md +59 -0
  114. package/skills/tdd/tests.md +77 -0
  115. package/skills/teach/GLOSSARY-FORMAT.md +35 -0
  116. package/skills/teach/LEARNING-RECORD-FORMAT.md +46 -0
  117. package/skills/teach/LICENSE +21 -0
  118. package/skills/teach/MISSION-FORMAT.md +31 -0
  119. package/skills/teach/RESOURCES-FORMAT.md +32 -0
  120. package/skills/teach/SKILL.md +140 -0
  121. package/skills/teach/agents/openai.yaml +5 -0
  122. package/skills/to-questionnaire/LICENSE +21 -0
  123. package/skills/to-questionnaire/SKILL.md +54 -0
  124. package/skills/to-questionnaire/agents/openai.yaml +5 -0
  125. package/skills/to-spec/LICENSE +21 -0
  126. package/skills/to-spec/SKILL.md +75 -0
  127. package/skills/to-spec/agents/openai.yaml +5 -0
  128. package/skills/to-tickets/LICENSE +21 -0
  129. package/skills/to-tickets/SKILL.md +105 -0
  130. package/skills/to-tickets/agents/openai.yaml +5 -0
  131. package/skills/triage/AGENT-BRIEF.md +207 -0
  132. package/skills/triage/LICENSE +21 -0
  133. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  134. package/skills/triage/SKILL.md +112 -0
  135. package/skills/triage/agents/openai.yaml +5 -0
  136. package/skills/wait-what/LICENSE +21 -0
  137. package/skills/wait-what/SKILL.md +7 -0
  138. package/skills/wait-what/agents/openai.yaml +5 -0
  139. package/skills/wayfinder/LICENSE +21 -0
  140. package/skills/wayfinder/SKILL.md +128 -0
  141. package/skills/wayfinder/agents/openai.yaml +5 -0
  142. package/skills/wizard/LICENSE +21 -0
  143. package/skills/wizard/SKILL.md +44 -0
  144. package/skills/wizard/agents/openai.yaml +3 -0
  145. package/skills/wizard/template.sh +223 -0
  146. package/skills/writing-for-agents/LICENSE +21 -0
  147. package/skills/writing-for-agents/SKILL-MECHANICS.md +22 -0
  148. package/skills/writing-for-agents/SKILL.md +81 -0
  149. package/skills/writing-for-agents/agents/openai.yaml +3 -0
  150. package/dist/blocks.js +0 -51
package/dist/resident.js CHANGED
@@ -1,85 +1,163 @@
1
1
  import { once } from 'node:events';
2
+ import { watch } from 'node:fs';
2
3
  import { mkdir, rm, writeFile } from 'node:fs/promises';
3
- import { createServer } from 'node:http';
4
- import { extname, join } from 'node:path';
4
+ import { createServer, get } from 'node:http';
5
+ import { dirname, extname, join } from 'node:path';
6
+ import { DatabaseSync } from 'node:sqlite';
5
7
  import { fileURLToPath } from 'node:url';
6
- import { killDescendants } from './acp.js';
7
8
  import { Agents } from './agents.js';
8
9
  import { house } from './api.js';
9
10
  import { received } from './bridge.js';
10
- import { Conversations } from './conversations.js';
11
- import { WorkingCopies } from './copies.js';
12
- import { kitHome, readEnrolment } from './home.js';
11
+ import { CONVERSATION_INPUTS, Conversations } from './conversations.js';
12
+ import { LocalCopies } from './copies.js';
13
+ import { restart } from './end.js';
14
+ import { agentBase, enrolled, forgetRestart, kitHome, ownerLock, ownerSocket, restartAsked } from './home.js';
15
+ import { Inputs } from './inputs.js';
16
+ import { killDescendants } from './scope.js';
17
+ import { quoted } from './shell.js';
13
18
  import { SignIns } from './sign-in.js';
19
+ import { placeSkillSet } from './skills.js';
14
20
  import { holdStream } from './stream.js';
21
+ import { Updates } from './update.js';
22
+ import { codexLauncher } from './work.js';
15
23
  function report(error) {
16
24
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
17
25
  }
18
26
  function logged(work) {
19
27
  work.catch(report);
20
28
  }
21
- function quoted(value) {
22
- return `'${value.replaceAll("'", `'\\''`)}'`;
29
+ async function installShim(path, module) {
30
+ const main = fileURLToPath(new URL(`./${module}${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
31
+ await mkdir(dirname(path), { recursive: true });
32
+ await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
23
33
  }
24
- async function installShim() {
25
- const main = fileURLToPath(new URL(`./git-main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
26
- await mkdir(join(kitHome(), 'shim'), { recursive: true });
27
- await writeFile(join(kitHome(), 'shim', 'git'), `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, {
28
- mode: 0o755,
29
- });
34
+ function claimed(lock) {
35
+ try {
36
+ lock.exec('BEGIN EXCLUSIVE');
37
+ return true;
38
+ }
39
+ catch (error) {
40
+ if (error.errcode === 5)
41
+ return false;
42
+ throw error;
43
+ }
30
44
  }
31
45
  async function serveOwner(copies) {
32
- const socketPath = join(kitHome(), 'owner.sock');
33
- await rm(socketPath, { force: true });
46
+ const lock = new DatabaseSync(ownerLock());
47
+ if (!claimed(lock)) {
48
+ lock.close();
49
+ const running = await runningResident();
50
+ throw new Error(`${running === null ? 'another Kit' : `Kit ${running}`} already runs this Environment from Kit home ${kitHome()}; stop it first to run another here`);
51
+ }
34
52
  const server = createServer(async (request, response) => {
35
53
  try {
36
- if (request.url !== '/git/push') {
54
+ const text = await received(request);
55
+ let answered;
56
+ if (request.url === '/resident') {
57
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ pid: process.pid }));
58
+ return;
59
+ }
60
+ if (request.url === '/git/fetch') {
61
+ answered = await copies.fetch();
62
+ }
63
+ else if (request.url === '/git/push') {
64
+ const { cwd, commit } = JSON.parse(text);
65
+ answered = await copies.push(cwd, commit, copies.owner);
66
+ }
67
+ else {
37
68
  response.writeHead(404).end();
38
69
  return;
39
70
  }
40
- const { cwd, commit } = JSON.parse(await received(request));
41
- const pushed = await copies.push(cwd, commit, copies.owner);
42
- response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(pushed));
71
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answered));
43
72
  }
44
73
  catch (error) {
45
74
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
46
75
  }
47
76
  });
48
- server.listen(socketPath);
77
+ server.on('close', () => lock.close());
78
+ await rm(ownerSocket(), { force: true });
79
+ server.listen(ownerSocket());
49
80
  await once(server, 'listening');
50
81
  }
82
+ function runningResident() {
83
+ return new Promise((resolve, reject) => {
84
+ get({ socketPath: ownerSocket(), path: '/resident' }, (answer) => {
85
+ received(answer).then((text) => resolve(JSON.parse(text).pid), reject);
86
+ }).on('error', (error) => {
87
+ if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
88
+ resolve(null);
89
+ else
90
+ reject(error);
91
+ });
92
+ });
93
+ }
94
+ function connected() {
95
+ return new Promise((resolve) => {
96
+ const watcher = watch(kitHome(), () => {
97
+ if (!enrolled())
98
+ return;
99
+ watcher.close();
100
+ resolve();
101
+ });
102
+ if (!enrolled()) {
103
+ process.stderr.write('kit: this Environment is not connected; run kit login\n');
104
+ return;
105
+ }
106
+ watcher.close();
107
+ resolve();
108
+ });
109
+ }
110
+ async function started() {
111
+ await connected();
112
+ await forgetRestart();
113
+ watch(kitHome(), () => {
114
+ if (enrolled())
115
+ return;
116
+ killDescendants();
117
+ process.exit(1);
118
+ });
119
+ await placeSkillSet();
120
+ await mkdir(agentBase(), { recursive: true });
121
+ await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
122
+ await installShim(codexLauncher(), 'codex-main');
123
+ }
51
124
  export async function resident() {
52
- if ((await readEnrolment()) === null) {
53
- process.stderr.write('kit: this Environment is not enrolled; run kit login\n');
54
- process.exitCode = 1;
55
- return;
56
- }
57
- process.env.HOUSE_KIT_RESIDENT = String(process.pid);
58
- const agents = new Agents(house);
59
- const copies = new WorkingCopies(house);
125
+ await mkdir(kitHome(), { recursive: true, mode: 0o700 });
126
+ const copies = new LocalCopies(house);
60
127
  await copies.load();
61
- await installShim();
62
128
  await serveOwner(copies);
129
+ await started().catch((error) => {
130
+ report(error);
131
+ process.exit(1);
132
+ });
133
+ process.env.HOUSE_KIT_RESIDENT = String(process.pid);
134
+ const agents = new Agents(house, () => changed());
63
135
  let stream = null;
64
136
  let reported = false;
65
- const idle = () => conversations.idle() && signIns.idle();
137
+ const idle = () => inputs.idle() && conversations.idle() && agents.idle();
66
138
  const changed = () => {
67
139
  if (!idle()) {
68
140
  reported = false;
69
141
  }
142
+ else if (restartAsked() && conversations.quiet()) {
143
+ restart('restarting for an updated CLI');
144
+ }
70
145
  else if (!reported) {
71
146
  reported = true;
72
147
  logged(house.deliver('/kit/idle', {}, idle));
73
148
  }
74
149
  };
150
+ const inputs = new Inputs(house, changed);
75
151
  const conversations = new Conversations({
76
152
  house,
77
153
  agents,
78
154
  copies,
155
+ inputs,
79
156
  send: (frame) => stream?.send(frame) ?? false,
80
157
  changed,
81
158
  });
82
- const signIns = new SignIns(house, agents, changed);
159
+ const signIns = new SignIns(house, agents, inputs);
160
+ const updates = new Updates(inputs);
83
161
  for (const signal of ['SIGTERM', 'SIGINT']) {
84
162
  process.once(signal, () => {
85
163
  killDescendants();
@@ -87,27 +165,32 @@ export async function resident() {
87
165
  });
88
166
  }
89
167
  await house.deliver('/kit/restarted', {}).catch(report);
168
+ await updates.resumed().catch(report);
90
169
  logged(agents.refresh());
91
170
  stream = holdStream({
92
171
  opened: () => {
93
172
  conversations.opened();
94
173
  changed();
95
- logged(copies.select());
174
+ logged(copies.connected());
96
175
  },
97
176
  frame: (arrived) => {
177
+ if (arrived.type === 'watching')
178
+ conversations.watching(arrived.watching === true);
179
+ if (arrived.type === 'authority_changed')
180
+ logged(copies.connected());
98
181
  if (arrived.type === 'work_available' && arrived.subject === 'agents')
99
182
  logged(agents.refresh());
100
- if (arrived.type === 'work_available' && arrived.subject === 'working_copy')
101
- logged(copies.select());
102
- if (arrived.type === 'entries') {
103
- copies.entries(arrived);
104
- }
105
183
  if (arrived.type === 'input') {
106
- reported = false;
107
184
  if (arrived.kind === 'sign_in')
108
185
  signIns.start(arrived);
109
- else
186
+ else if (arrived.kind === 'update')
187
+ updates.start(arrived);
188
+ else if (CONVERSATION_INPUTS.has(arrived.kind))
110
189
  conversations.input(arrived);
190
+ else {
191
+ const refused = { refused: `This Kit does not know ${arrived.kind}; update the Kit` };
192
+ void inputs.carry(String(arrived.input_id), async () => ({ ack: refused }));
193
+ }
111
194
  }
112
195
  },
113
196
  });
package/dist/scope.js ADDED
@@ -0,0 +1,203 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdirSync, readdirSync, readFileSync, 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
+ function failure(error) {
8
+ return error.code ?? '';
9
+ }
10
+ function listed(environment) {
11
+ const found = new Map();
12
+ const output = execFileSync('ps', [environment ? '-AEww' : '-Aww', '-o', 'pid=,ppid=,sess=,command='], {
13
+ encoding: 'utf8',
14
+ maxBuffer: LISTING_BYTES,
15
+ });
16
+ for (const line of output.split('\n')) {
17
+ const fields = /^\s*(\d+)\s+(\d+)\s+(\S+)\s?(.*)$/.exec(line);
18
+ if (fields !== null)
19
+ found.set(Number(fields[1]), { parent: Number(fields[2]), session: fields[3], command: fields[4] });
20
+ }
21
+ return found;
22
+ }
23
+ function read(pid) {
24
+ try {
25
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
26
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
27
+ const command = readFileSync(`/proc/${pid}/cmdline`, 'utf8').replaceAll('\0', ' ');
28
+ return { parent: Number(fields[1]), session: fields[3], command };
29
+ }
30
+ catch (error) {
31
+ if (GONE.has(failure(error)))
32
+ return null;
33
+ throw error;
34
+ }
35
+ }
36
+ function processes() {
37
+ if (process.platform === 'darwin')
38
+ return listed(false);
39
+ const found = new Map();
40
+ for (const entry of readdirSync('/proc')) {
41
+ const running = /^\d+$/.test(entry) ? read(entry) : null;
42
+ if (running !== null)
43
+ found.set(Number(entry), running);
44
+ }
45
+ return found;
46
+ }
47
+ function descendants(roots, table = processes()) {
48
+ const children = new Map();
49
+ for (const [pid, { parent }] of table)
50
+ children.set(parent, [...(children.get(parent) ?? []), pid]);
51
+ const tree = [];
52
+ const pending = roots.flatMap((root) => children.get(root) ?? []);
53
+ while (pending.length > 0) {
54
+ const pid = pending.pop();
55
+ tree.push(pid);
56
+ pending.push(...(children.get(pid) ?? []));
57
+ }
58
+ return tree;
59
+ }
60
+ function marked(marker, doubted) {
61
+ if (process.platform === 'darwin') {
62
+ return [...listed(true)].filter(([, { command }]) => ` ${command} `.includes(` ${marker} `)).map(([pid]) => pid);
63
+ }
64
+ return readdirSync('/proc')
65
+ .filter((entry) => /^\d+$/.test(entry) && carries(entry, marker, doubted))
66
+ .map(Number);
67
+ }
68
+ function carries(pid, marker, doubted) {
69
+ try {
70
+ return readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0').includes(marker);
71
+ }
72
+ catch (error) {
73
+ if (GONE.has(failure(error)))
74
+ return false;
75
+ if (failure(error) !== 'EACCES')
76
+ throw error;
77
+ return doubted && statSync(`/proc/${pid}`, { throwIfNoEntry: false })?.uid === process.getuid();
78
+ }
79
+ }
80
+ function killAll(pids) {
81
+ for (const pid of pids) {
82
+ for (const target of [-pid, pid]) {
83
+ try {
84
+ process.kill(target, 'SIGKILL');
85
+ }
86
+ catch { }
87
+ }
88
+ }
89
+ }
90
+ export function killTree(child) {
91
+ killAll([child.pid, ...descendants([child.pid])]);
92
+ }
93
+ export function killMarked(marker) {
94
+ const pids = marked(marker, false);
95
+ killAll([...pids, ...descendants(pids)]);
96
+ }
97
+ export function killDescendants() {
98
+ const pids = marked(`HOUSE_KIT_RESIDENT=${process.pid}`, false);
99
+ killAll([...pids, ...descendants([process.pid, ...pids])]);
100
+ }
101
+ function ownGroup() {
102
+ if (process.platform !== 'linux')
103
+ return null;
104
+ try {
105
+ const line = readFileSync('/proc/self/cgroup', 'utf8')
106
+ .split('\n')
107
+ .find((entry) => entry.startsWith('0::'));
108
+ return line === undefined ? null : join(CGROUPS, line.slice(3));
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ }
114
+ function members(group) {
115
+ const pids = readFileSync(join(group, 'cgroup.procs'), 'utf8').split('\n').filter(Boolean).map(Number);
116
+ for (const entry of readdirSync(group, { withFileTypes: true })) {
117
+ if (entry.isDirectory())
118
+ pids.push(...members(join(group, entry.name)));
119
+ }
120
+ return pids;
121
+ }
122
+ export class Scope {
123
+ marker;
124
+ cli;
125
+ group;
126
+ session = null;
127
+ recorded = null;
128
+ constructor(marker, name, cli) {
129
+ this.marker = marker;
130
+ this.cli = cli;
131
+ const own = ownGroup();
132
+ this.group = own === null ? null : join(own, name);
133
+ try {
134
+ if (this.group !== null)
135
+ mkdirSync(this.group);
136
+ }
137
+ catch {
138
+ this.group = null;
139
+ }
140
+ }
141
+ command(command, args) {
142
+ if (this.group === null)
143
+ return [command, args];
144
+ return ['/bin/sh', ['-c', 'echo $$ > "$0/cgroup.procs" 2>/dev/null; exec "$@"', this.group, command, ...args]];
145
+ }
146
+ entered(pid) {
147
+ this.session = process.platform === 'darwin' ? (listed(false).get(pid)?.session ?? null) : String(pid);
148
+ if (this.group === null)
149
+ return;
150
+ const joined = readFileSync(`/proc/${pid}/cgroup`, 'utf8').split('\n').find((entry) => entry.startsWith('0::'));
151
+ if (joined !== undefined && join(CGROUPS, joined.slice(3)) === this.group)
152
+ return;
153
+ this.close();
154
+ this.group = null;
155
+ }
156
+ record() {
157
+ const found = this.found();
158
+ if (found === null)
159
+ return;
160
+ this.recorded = new Set([...found].filter(([, { session }]) => session === this.session).map(([pid]) => pid));
161
+ }
162
+ working() {
163
+ const found = this.found();
164
+ if (found === null)
165
+ return true;
166
+ if (this.recorded === null)
167
+ return found.size > 0;
168
+ return [...found].some(([pid, { session, command }]) => session !== this.session || !(this.recorded.has(pid) || command.startsWith(`${this.cli}-`)));
169
+ }
170
+ empty() {
171
+ return this.found()?.size === 0;
172
+ }
173
+ kill() {
174
+ killMarked(this.marker);
175
+ if (this.group === null)
176
+ return;
177
+ try {
178
+ writeFileSync(join(this.group, 'cgroup.kill'), '1');
179
+ }
180
+ catch {
181
+ killAll([...(this.found()?.keys() ?? [])]);
182
+ }
183
+ }
184
+ close() {
185
+ if (this.group === null)
186
+ return;
187
+ try {
188
+ rmdirSync(this.group);
189
+ }
190
+ catch { }
191
+ }
192
+ found() {
193
+ try {
194
+ const table = processes();
195
+ const roots = this.group === null ? marked(this.marker, true) : members(this.group);
196
+ const pids = this.group === null ? [...roots, ...descendants(roots, table)] : roots;
197
+ return new Map(pids.flatMap((pid) => (table.has(pid) ? [[pid, table.get(pid)]] : [])));
198
+ }
199
+ catch {
200
+ return null;
201
+ }
202
+ }
203
+ }
@@ -1,15 +1,20 @@
1
+ import { finalRefusal, retryDelay } from './api.js';
1
2
  export async function holdSecretInput(house, subject, steps, waiting) {
2
- while (waiting()) {
3
+ for (let failures = 0; waiting();) {
3
4
  try {
4
5
  const held = await house.post(`/kit/secret-input/${subject}`, { steps });
5
6
  if (held.outcome === 'collected')
6
7
  return held.content;
7
8
  if (held.release !== 'held')
8
9
  return null;
10
+ failures = 0;
9
11
  }
10
12
  catch (error) {
13
+ if (finalRefusal(error))
14
+ return null;
11
15
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
12
- await new Promise((resolve) => setTimeout(resolve, 1000));
16
+ // A wait that did not reach House is held again on the jittered curve for as long as its asker still waits.
17
+ await new Promise((resolve) => setTimeout(resolve, retryDelay(failures++)));
13
18
  }
14
19
  }
15
20
  return null;
@@ -0,0 +1,9 @@
1
+ import { startService } from './service.js';
2
+ try {
3
+ if (startService())
4
+ process.stdout.write('started\n');
5
+ }
6
+ catch (error) {
7
+ process.stderr.write(`kit: ${error.message}\n`);
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,33 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ const UNIT = 'house-kit.service';
3
+ // launchctl and systemctl answer at once, so ten seconds only bounds a stuck service manager.
4
+ const MANAGER_MS = 10_000;
5
+ function manage(command, args) {
6
+ return spawnSync(command, args, { encoding: 'utf8', timeout: MANAGER_MS });
7
+ }
8
+ function start(command, args) {
9
+ const started = manage(command, args);
10
+ if (started.status === 0)
11
+ return;
12
+ const cause = started.error?.message ?? (started.stderr.trim() || `${command} exited with ${started.status ?? 'a signal'}`);
13
+ throw new Error(`the House Kit service could not be started: ${cause}`);
14
+ }
15
+ export function startService() {
16
+ if (process.platform === 'darwin') {
17
+ const service = `gui/${process.getuid()}/house-kit`;
18
+ const printed = manage('launchctl', ['print', service]);
19
+ if (printed.status !== 0 || /^\tstate = running$/m.test(printed.stdout))
20
+ return false;
21
+ start('launchctl', ['kickstart', service]);
22
+ return true;
23
+ }
24
+ for (const scope of [['--user'], []]) {
25
+ if (manage('systemctl', [...scope, 'is-enabled', '--quiet', UNIT]).status !== 0)
26
+ continue;
27
+ if (manage('systemctl', [...scope, 'is-active', '--quiet', UNIT]).status === 0)
28
+ return false;
29
+ start('systemctl', [...scope, 'start', UNIT]);
30
+ return true;
31
+ }
32
+ return false;
33
+ }
package/dist/shell.js ADDED
@@ -0,0 +1,3 @@
1
+ export function quoted(value) {
2
+ return `'${value.replaceAll("'", `'\\''`)}'`;
3
+ }
package/dist/sign-in.js CHANGED
@@ -1,50 +1,66 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
- import { killTree } from './acp.js';
4
- import { CLIS, cliCommand, withoutProxy } from './clis.js';
3
+ import { CLIS, withoutProxy } from './clis.js';
4
+ import { killTree } from './scope.js';
5
5
  import { holdSecretInput } from './secret-input.js';
6
6
  const ESCAPE = /\u001b\[[\d;]*m/g;
7
7
  const LINK = /https:\/\/\S+/;
8
8
  const CODE = /^[A-Z0-9]+-[A-Z0-9]+$/;
9
- function logged(error) {
10
- process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
9
+ function causeOf(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
12
+ function endOf(signal) {
13
+ return new Promise((resolve) => signal.addEventListener('abort', () => resolve(true), { once: true }));
11
14
  }
12
15
  export class SignIns {
13
16
  house;
14
17
  agents;
15
- changed;
16
- running = new Set();
17
- constructor(house, agents, changed) {
18
+ inputs;
19
+ constructor(house, agents, inputs) {
18
20
  this.house = house;
19
21
  this.agents = agents;
20
- this.changed = changed;
21
- }
22
- idle() {
23
- return this.running.size === 0;
22
+ this.inputs = inputs;
24
23
  }
25
24
  start(input) {
26
- if (this.running.has(input.input_id))
27
- return;
28
- this.running.add(input.input_id);
29
- this.changed();
30
- this.login(input)
31
- .then(() => this.agents.report())
32
- .then(() => this.house.deliver(`/kit/inputs/${input.input_id}/ack`, {}))
33
- .catch(logged)
34
- .finally(() => {
35
- this.running.delete(input.input_id);
36
- this.changed();
37
- });
25
+ void this.inputs.carry(input.input_id, () => this.signIn(input));
38
26
  }
39
- async login(input) {
40
- await this.agents.installed();
27
+ async signIn(input) {
28
+ const ending = new AbortController();
29
+ // House stops waiting for a sign-in ten minutes after it wrote it and sends the seconds left, so its install and login end with the page.
30
+ const timer = setTimeout(() => ending.abort(), input.ends_in * 1000);
31
+ const ended = await Promise.race([this.signedIn(input, ending.signal), endOf(ending.signal)]);
32
+ clearTimeout(timer);
33
+ if (ended)
34
+ process.stderr.write(`kit: the ${input.cli} sign-in reached the end House set for it\n`);
35
+ return ended ? { ack: {} } : { ack: {}, acknowledged: () => this.agents.reread(input.cli) };
36
+ }
37
+ async signedIn(input, signal) {
38
+ await this.login(input, signal);
39
+ if (!signal.aborted)
40
+ await this.agents.recheck(input.cli, signal);
41
+ return false;
42
+ }
43
+ async login(input, signal) {
44
+ let cli;
45
+ try {
46
+ cli = await this.agents.located(input.cli, signal);
47
+ }
48
+ catch (error) {
49
+ if (!signal.aborted)
50
+ process.stderr.write(`kit: the ${input.cli} sign-in failed: ${causeOf(error)}\n`);
51
+ return;
52
+ }
53
+ if (signal.aborted)
54
+ return;
41
55
  const login = CLIS[input.cli].login;
42
- const child = spawn(cliCommand(input.cli), login.args, {
56
+ const child = spawn(cli, login.args, {
43
57
  stdio: ['pipe', 'pipe', 'pipe'],
44
58
  detached: true,
45
59
  env: withoutProxy(),
46
60
  });
47
61
  const running = () => child.exitCode === null && child.signalCode === null;
62
+ const stop = () => killTree(child);
63
+ signal.addEventListener('abort', stop, { once: true });
48
64
  let link;
49
65
  let code;
50
66
  let last = '';
@@ -54,6 +70,8 @@ export class SignIns {
54
70
  if (plain === '')
55
71
  return;
56
72
  last = plain;
73
+ if (login.code === 'collect' && plain.includes(login.rejected))
74
+ killTree(child);
57
75
  link ??= LINK.exec(plain)?.[0];
58
76
  if (CODE.test(plain))
59
77
  code ??= plain;
@@ -79,9 +97,10 @@ export class SignIns {
79
97
  createInterface({ input: output }).on('line', read);
80
98
  const failed = await new Promise((resolve) => {
81
99
  child.on('error', (error) => resolve(error.message));
82
- child.on('close', (status, signal) => resolve(status === 0 ? null : `exited with ${status ?? signal}${last ? `: ${last}` : ''}`));
100
+ child.on('close', (status, killed) => resolve(status === 0 ? null : `exited with ${status ?? killed}${last ? `: ${last}` : ''}`));
83
101
  });
84
- if (failed !== null)
102
+ signal.removeEventListener('abort', stop);
103
+ if (failed !== null && !signal.aborted)
85
104
  process.stderr.write(`kit: the ${input.cli} sign-in failed: ${failed}\n`);
86
105
  }
87
106
  }