@agentshouse/kit 0.2.1-cb6679d048e60 → 0.2.1-cb997daca91ed

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