@agentshouse/kit 0.2.1-alpha.9 → 0.2.1-c073f4e9391b2

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 (48) hide show
  1. package/README.md +44 -26
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +18 -75
  4. package/dist/agents.js +266 -53
  5. package/dist/api.js +40 -4
  6. package/dist/app-git.js +64 -0
  7. package/dist/bootstrap.json +10 -14
  8. package/dist/bridge.js +89 -71
  9. package/dist/chatgpt.js +25 -0
  10. package/dist/clis-main.js +23 -0
  11. package/dist/clis.js +203 -71
  12. package/dist/codex-main.js +58 -0
  13. package/dist/conversations.js +328 -199
  14. package/dist/copies.js +188 -161
  15. package/dist/end.js +22 -0
  16. package/dist/enrol-main.js +7 -1
  17. package/dist/events.js +521 -0
  18. package/dist/files.js +16 -1
  19. package/dist/git-main.js +2 -2
  20. package/dist/git.js +6 -2
  21. package/dist/home.js +72 -5
  22. package/dist/house-main.js +181 -57
  23. package/dist/instructions.js +16 -13
  24. package/dist/kit-main.js +55 -4
  25. package/dist/login.js +108 -97
  26. package/dist/logout.js +21 -0
  27. package/dist/mcp.js +39 -0
  28. package/dist/operation.js +7 -4
  29. package/dist/parts.js +82 -0
  30. package/dist/placement.js +48 -0
  31. package/dist/refusals.js +53 -0
  32. package/dist/relay.js +20 -0
  33. package/dist/resident.js +70 -34
  34. package/dist/scope.js +203 -0
  35. package/dist/secret-input.js +7 -2
  36. package/dist/service-main.js +9 -0
  37. package/dist/service.js +33 -0
  38. package/dist/shell.js +3 -0
  39. package/dist/sign-in.js +48 -11
  40. package/dist/skills.js +5 -10
  41. package/dist/stream.js +37 -7
  42. package/dist/transcription.js +170 -0
  43. package/dist/update.js +140 -0
  44. package/dist/wire.js +6 -0
  45. package/dist/work.js +348 -0
  46. package/how-we-work.md +10 -12
  47. package/package.json +4 -7
  48. package/dist/blocks.js +0 -51
package/dist/mcp.js ADDED
@@ -0,0 +1,39 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { KIT_VERSION } from './clis.js';
3
+ import { relayed } from './relay.js';
4
+ const MCP_PROTOCOL_VERSION = '2026-07-28';
5
+ export const UNREACHABLE = 'House is unreachable; call again in a minute';
6
+ export function rpc(method, params) {
7
+ return { jsonrpc: '2.0', id: randomUUID(), method, params };
8
+ }
9
+ export function mcpBody(message, operation) {
10
+ return JSON.stringify({
11
+ ...message,
12
+ params: {
13
+ ...message.params,
14
+ _meta: {
15
+ 'io.modelcontextprotocol/protocolVersion': MCP_PROTOCOL_VERSION,
16
+ 'io.modelcontextprotocol/clientInfo': { name: '@agentshouse/kit', version: KIT_VERSION },
17
+ 'io.modelcontextprotocol/clientCapabilities': {},
18
+ ...(operation === null ? {} : { 'agents.house/agent-operation': operation }),
19
+ },
20
+ },
21
+ });
22
+ }
23
+ export async function callHouse(origin, credential, message, operation = null, signal) {
24
+ const tool = message.method === 'tools/call' ? String(message.params.name) : null;
25
+ const answer = await fetch(relayed(new URL('/', origin)), {
26
+ method: 'POST',
27
+ headers: {
28
+ 'content-type': 'application/json',
29
+ authorization: `Bearer ${credential}`,
30
+ accept: 'application/json, text/event-stream',
31
+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,
32
+ 'mcp-method': message.method,
33
+ ...(tool === null ? {} : { 'mcp-name': tool }),
34
+ },
35
+ body: mcpBody(message, operation),
36
+ signal,
37
+ });
38
+ return { status: answer.status, text: await answer.text() };
39
+ }
package/dist/operation.js CHANGED
@@ -1,9 +1,12 @@
1
1
  import { randomBytes } from 'node:crypto';
2
+ export function uuidOf(bytes, version) {
3
+ bytes[6] = (version << 4) | (bytes[6] & 0x0f);
4
+ bytes[8] = 0x80 | (bytes[8] & 0x3f);
5
+ const hex = bytes.toString('hex', 0, 16);
6
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
7
+ }
2
8
  export function operationId() {
3
9
  const bytes = randomBytes(16);
4
10
  bytes.writeUIntBE(Date.now(), 0, 6);
5
- bytes[6] = 0x70 | (bytes[6] & 0x0f);
6
- bytes[8] = 0x80 | (bytes[8] & 0x3f);
7
- const hex = bytes.toString('hex');
8
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
11
+ return uuidOf(bytes, 7);
9
12
  }
package/dist/parts.js ADDED
@@ -0,0 +1,82 @@
1
+ export class Parts {
2
+ parts = [];
3
+ context = null;
4
+ emit;
5
+ made = [];
6
+ events = 0;
7
+ writing = null;
8
+ counting = null;
9
+ planned = null;
10
+ constructor(emit) {
11
+ this.emit = emit;
12
+ }
13
+ write(type, id, text) {
14
+ if (text === '')
15
+ return;
16
+ if (this.writing?.type === type && this.writing.id === id) {
17
+ this.parts[this.writing.index].text += text;
18
+ this.emit({ op: 'append', index: this.writing.index, text });
19
+ return;
20
+ }
21
+ this.writing = { type, id, index: this.start({ type, text }) };
22
+ }
23
+ command() {
24
+ if (this.counting === null) {
25
+ this.counting = this.start({ type: 'commands', count: 1 });
26
+ return;
27
+ }
28
+ const part = this.parts[this.counting];
29
+ part.count++;
30
+ this.emit({ op: 'count', index: this.counting, count: part.count });
31
+ }
32
+ start(part) {
33
+ this.writing = null;
34
+ this.counting = null;
35
+ return this.add(part, ++this.events);
36
+ }
37
+ reserve() {
38
+ this.writing = null;
39
+ this.counting = null;
40
+ return ++this.events;
41
+ }
42
+ arrive(part, reserved) {
43
+ this.add(part, reserved);
44
+ }
45
+ done(index, result) {
46
+ const part = this.parts[index];
47
+ part.status = 'done';
48
+ part.result = result;
49
+ this.emit({ op: 'status', index, status: 'done', result });
50
+ }
51
+ plan(entries) {
52
+ if (this.planned === null) {
53
+ this.planned = this.start({ type: 'plan', entries });
54
+ return;
55
+ }
56
+ this.parts[this.planned].entries = entries;
57
+ this.emit({ op: 'plan', index: this.planned, entries });
58
+ }
59
+ measure(context) {
60
+ this.context = context;
61
+ this.emit({ op: 'context', ...context });
62
+ }
63
+ saved() {
64
+ return this.parts
65
+ .map((part, index) => ({ part, made: this.made[index] }))
66
+ .sort((a, b) => a.made - b.made)
67
+ .map(({ part }) => part);
68
+ }
69
+ operations() {
70
+ return [
71
+ ...this.parts.map((part, index) => ({ op: 'start', index, part })),
72
+ ...(this.context === null ? [] : [{ op: 'context', ...this.context }]),
73
+ ];
74
+ }
75
+ add(part, made) {
76
+ this.parts.push(part);
77
+ this.made.push(made);
78
+ const index = this.parts.length - 1;
79
+ this.emit({ op: 'start', index, part });
80
+ return index;
81
+ }
82
+ }
@@ -0,0 +1,48 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { run } from './clis.js';
4
+ import { kitHome } from './home.js';
5
+ import { relayOrigin } from './relay.js';
6
+ export function service() {
7
+ if (process.platform !== 'linux' || !process.env.INVOCATION_ID)
8
+ return null;
9
+ return process.env.MANAGERPID ? 'user' : 'system';
10
+ }
11
+ export function throughSudo() {
12
+ return service() === 'system' && process.getuid() !== 0;
13
+ }
14
+ export async function updatesItself() {
15
+ if (service() === null)
16
+ return false;
17
+ if (!throughSudo())
18
+ return true;
19
+ // sudo answers at once, so ten seconds only bounds a stuck sudo.
20
+ return (await run('sudo', ['-n', 'true'], 10_000)).status === 0;
21
+ }
22
+ function installed() {
23
+ try {
24
+ return readFileSync(join(kitHome(), 'placement'), 'utf8').trim();
25
+ }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT')
28
+ return null;
29
+ throw error;
30
+ }
31
+ }
32
+ function entries(house) {
33
+ const host = new URL(house).host;
34
+ const relay = relayOrigin();
35
+ if (relay === undefined)
36
+ return [`curl -fsSL ${host}/kit | sh`, `irm ${host}/kit.ps1 | iex`];
37
+ const entry = `${relay}/${host}/kit`;
38
+ return [`curl -fsSL ${entry} | HOUSE_KIT_RELAY=${relay} sh`, `$env:HOUSE_KIT_RELAY='${relay}'; irm ${entry}.ps1 | iex`];
39
+ }
40
+ export function installCommand(house) {
41
+ const [shell, windows] = entries(house);
42
+ const placement = installed();
43
+ if (placement === 'native')
44
+ return shell;
45
+ if (placement === 'server')
46
+ return `${shell} -s -- --linux`;
47
+ return `${shell} -s -- --container, or ${windows} on Windows`;
48
+ }
@@ -0,0 +1,53 @@
1
+ import { parse } from 'yaml';
2
+ const HEAD = /^([a-z][a-z0-9_]*): \S/;
3
+ function conflictCodes(detail) {
4
+ let parsed;
5
+ try {
6
+ parsed = parse(detail);
7
+ }
8
+ catch {
9
+ return [];
10
+ }
11
+ const conflicts = parsed?.conflicts;
12
+ if (!Array.isArray(conflicts))
13
+ return [];
14
+ return conflicts.flatMap((conflict) => typeof conflict?.code === 'string' ? [conflict.code] : []);
15
+ }
16
+ function spoken(text) {
17
+ const head = HEAD.exec(text);
18
+ if (head === null)
19
+ return null;
20
+ const said = text.replace(/\n+$/, '');
21
+ const detail = said.indexOf('\n');
22
+ return { code: head[1], text: said, conflicts: detail === -1 ? [] : conflictCodes(said.slice(detail + 1)) };
23
+ }
24
+ export function retryable(text) {
25
+ let body;
26
+ try {
27
+ body = JSON.parse(text);
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ const error = body?.error;
33
+ const verdict = error?.retryable ?? error?.data?.retryable;
34
+ return typeof verdict === 'boolean' ? verdict : null;
35
+ }
36
+ export function refusalOf(text) {
37
+ let body;
38
+ try {
39
+ body = JSON.parse(text);
40
+ }
41
+ catch {
42
+ return spoken(text);
43
+ }
44
+ const error = body?.error;
45
+ if (typeof error !== 'object' || error === null)
46
+ return null;
47
+ const { code, message, data } = error;
48
+ const said = typeof message === 'string' ? spoken(message) : null;
49
+ if (said !== null)
50
+ return said;
51
+ const named = typeof code === 'string' ? code : typeof data?.code === 'string' ? data.code : null;
52
+ return named === null ? null : { code: named, text: named, conflicts: [] };
53
+ }
package/dist/relay.js ADDED
@@ -0,0 +1,20 @@
1
+ let selected;
2
+ export function selectRelay(relay) {
3
+ selected = relay === undefined || relay === '' ? null : relay;
4
+ }
5
+ export function relayOrigin() {
6
+ if (selected !== undefined)
7
+ return selected ?? undefined;
8
+ const ambient = process.env.HOUSE_KIT_RELAY;
9
+ return ambient === undefined || ambient === '' ? undefined : ambient;
10
+ }
11
+ export function relayed(target) {
12
+ const url = new URL(target);
13
+ const relay = relayOrigin();
14
+ if (relay === undefined)
15
+ return url;
16
+ const through = new URL(`${url.host}${url.pathname}${url.search}`, `${relay}/`);
17
+ if (url.protocol === 'wss:' || url.protocol === 'ws:')
18
+ through.protocol = 'wss:';
19
+ return through;
20
+ }
package/dist/resident.js CHANGED
@@ -1,46 +1,53 @@
1
1
  import { once } from 'node:events';
2
+ import { watch } from 'node:fs';
2
3
  import { mkdir, rm, writeFile } from 'node:fs/promises';
3
4
  import { createServer } from 'node:http';
4
- import { extname, join } from 'node:path';
5
+ import { dirname, extname, join } from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
6
- import { killDescendants } from './acp.js';
7
7
  import { Agents } from './agents.js';
8
8
  import { house } from './api.js';
9
9
  import { received } from './bridge.js';
10
- import { Conversations } from './conversations.js';
11
- import { WorkingCopies } from './copies.js';
12
- import { kitHome, readEnrolment } from './home.js';
10
+ import { CONVERSATION_INPUTS, Conversations } from './conversations.js';
11
+ import { LocalCopies } from './copies.js';
12
+ import { restart } from './end.js';
13
+ import { agentBase, enrolled, forgetRestart, kitHome, restartAsked } from './home.js';
14
+ import { killDescendants } from './scope.js';
15
+ import { quoted } from './shell.js';
13
16
  import { SignIns } from './sign-in.js';
14
17
  import { placeSkillSet } from './skills.js';
15
18
  import { holdStream } from './stream.js';
19
+ import { Updates } from './update.js';
20
+ import { codexLauncher } from './work.js';
16
21
  function report(error) {
17
22
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
18
23
  }
19
24
  function logged(work) {
20
25
  work.catch(report);
21
26
  }
22
- function quoted(value) {
23
- return `'${value.replaceAll("'", `'\\''`)}'`;
24
- }
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
- });
27
+ async function installShim(path, module) {
28
+ const main = fileURLToPath(new URL(`./${module}${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
29
+ await mkdir(dirname(path), { recursive: true });
30
+ await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
31
31
  }
32
32
  async function serveOwner(copies) {
33
33
  const socketPath = join(kitHome(), 'owner.sock');
34
34
  await rm(socketPath, { force: true });
35
35
  const server = createServer(async (request, response) => {
36
36
  try {
37
- if (request.url !== '/git/push') {
37
+ const text = await received(request);
38
+ let answered;
39
+ if (request.url === '/git/fetch') {
40
+ answered = await copies.fetch();
41
+ }
42
+ else if (request.url === '/git/push') {
43
+ const { cwd, commit } = JSON.parse(text);
44
+ answered = await copies.push(cwd, commit, copies.owner);
45
+ }
46
+ else {
38
47
  response.writeHead(404).end();
39
48
  return;
40
49
  }
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));
50
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answered));
44
51
  }
45
52
  catch (error) {
46
53
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
@@ -49,26 +56,50 @@ async function serveOwner(copies) {
49
56
  server.listen(socketPath);
50
57
  await once(server, 'listening');
51
58
  }
59
+ function connected() {
60
+ return new Promise((resolve) => {
61
+ const watcher = watch(kitHome(), () => {
62
+ if (!enrolled())
63
+ return;
64
+ watcher.close();
65
+ resolve();
66
+ });
67
+ if (!enrolled()) {
68
+ process.stderr.write('kit: this Environment is not connected; run kit login\n');
69
+ return;
70
+ }
71
+ watcher.close();
72
+ resolve();
73
+ });
74
+ }
52
75
  export async function resident() {
53
- if ((await readEnrolment()) === null) {
54
- process.stderr.write('kit: this Environment is not enrolled; run kit login\n');
55
- process.exitCode = 1;
56
- return;
57
- }
76
+ await connected();
77
+ await forgetRestart();
78
+ watch(kitHome(), () => {
79
+ if (enrolled())
80
+ return;
81
+ killDescendants();
82
+ process.exit(1);
83
+ });
58
84
  await placeSkillSet();
85
+ await mkdir(agentBase(), { recursive: true });
59
86
  process.env.HOUSE_KIT_RESIDENT = String(process.pid);
60
- const agents = new Agents(house);
61
- const copies = new WorkingCopies(house);
87
+ const agents = new Agents(house, () => changed());
88
+ const copies = new LocalCopies(house);
62
89
  await copies.load();
63
- await installShim();
90
+ await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
91
+ await installShim(codexLauncher(), 'codex-main');
64
92
  await serveOwner(copies);
65
93
  let stream = null;
66
94
  let reported = false;
67
- const idle = () => conversations.idle() && signIns.idle();
95
+ const idle = () => conversations.idle() && signIns.idle() && agents.idle();
68
96
  const changed = () => {
69
97
  if (!idle()) {
70
98
  reported = false;
71
99
  }
100
+ else if (restartAsked() && conversations.quiet()) {
101
+ restart('restarting for an updated CLI');
102
+ }
72
103
  else if (!reported) {
73
104
  reported = true;
74
105
  logged(house.deliver('/kit/idle', {}, idle));
@@ -82,6 +113,7 @@ export async function resident() {
82
113
  changed,
83
114
  });
84
115
  const signIns = new SignIns(house, agents, changed);
116
+ const updates = new Updates(house);
85
117
  for (const signal of ['SIGTERM', 'SIGINT']) {
86
118
  process.once(signal, () => {
87
119
  killDescendants();
@@ -89,27 +121,31 @@ export async function resident() {
89
121
  });
90
122
  }
91
123
  await house.deliver('/kit/restarted', {}).catch(report);
124
+ await updates.resumed().catch(report);
92
125
  logged(agents.refresh());
93
126
  stream = holdStream({
94
127
  opened: () => {
95
128
  conversations.opened();
96
129
  changed();
97
- logged(copies.select());
130
+ logged(copies.connected());
98
131
  },
99
132
  frame: (arrived) => {
133
+ if (arrived.type === 'watching')
134
+ conversations.watching(arrived.watching === true);
100
135
  if (arrived.type === 'work_available' && arrived.subject === 'agents')
101
136
  logged(agents.refresh());
102
- if (arrived.type === 'work_available' && arrived.subject === 'working_copy')
103
- logged(copies.select());
104
- if (arrived.type === 'entries') {
105
- copies.entries(arrived);
106
- }
107
137
  if (arrived.type === 'input') {
108
138
  reported = false;
109
139
  if (arrived.kind === 'sign_in')
110
140
  signIns.start(arrived);
111
- else
141
+ else if (arrived.kind === 'update')
142
+ updates.start(arrived);
143
+ else if (CONVERSATION_INPUTS.has(arrived.kind))
112
144
  conversations.input(arrived);
145
+ else {
146
+ const refused = { refused: `This Kit does not know ${arrived.kind}; update the Kit` };
147
+ logged(house.deliver(`/kit/inputs/${arrived.input_id}/ack`, refused).finally(changed));
148
+ }
113
149
  }
114
150
  },
115
151
  });
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
+ }