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

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 (136) hide show
  1. package/README.md +48 -29
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +49 -86
  4. package/dist/agents.js +333 -52
  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 +93 -78
  9. package/dist/calls.js +63 -0
  10. package/dist/chatgpt.js +32 -0
  11. package/dist/clis-main.js +23 -0
  12. package/dist/clis.js +217 -72
  13. package/dist/codex-main.js +58 -0
  14. package/dist/connection.js +126 -0
  15. package/dist/conversations.js +642 -263
  16. package/dist/copies.js +237 -173
  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-main.js +2 -2
  22. package/dist/git.js +16 -10
  23. package/dist/home.js +127 -9
  24. package/dist/house-cli.js +300 -0
  25. package/dist/house-main.js +5 -102
  26. package/dist/instructions.js +16 -17
  27. package/dist/kit-cli.js +68 -0
  28. package/dist/kit-main.js +8 -16
  29. package/dist/login.js +128 -95
  30. package/dist/logout.js +19 -0
  31. package/dist/mcp.js +41 -0
  32. package/dist/operation.js +7 -4
  33. package/dist/parts.js +82 -0
  34. package/dist/placement.js +39 -0
  35. package/dist/refusals.js +53 -0
  36. package/dist/relay.js +20 -0
  37. package/dist/resident.js +139 -52
  38. package/dist/scope.js +206 -0
  39. package/dist/secret-input.js +7 -2
  40. package/dist/service-main.js +9 -0
  41. package/dist/service.js +55 -0
  42. package/dist/shell.js +3 -0
  43. package/dist/sign-in.js +50 -31
  44. package/dist/skills.js +20 -37
  45. package/dist/transcription.js +201 -0
  46. package/dist/translate.js +2 -8
  47. package/dist/update.js +138 -0
  48. package/dist/web-wizard.js +100 -0
  49. package/dist/wire.js +22 -0
  50. package/dist/work.js +346 -0
  51. package/package.json +9 -11
  52. package/dist/blocks.js +0 -51
  53. package/dist/stream.js +0 -47
  54. package/how-we-work.md +0 -25
  55. package/skills/ask-matt/LICENSE +0 -21
  56. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  57. package/skills/ask-matt/SKILL.md +0 -91
  58. package/skills/ask-matt/agents/openai.yaml +0 -4
  59. package/skills/code-review/LICENSE +0 -21
  60. package/skills/code-review/SKILL.md +0 -89
  61. package/skills/code-review/agents/openai.yaml +0 -3
  62. package/skills/codebase-design/DEEPENING.md +0 -37
  63. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  64. package/skills/codebase-design/LICENSE +0 -21
  65. package/skills/codebase-design/SKILL.md +0 -116
  66. package/skills/codebase-design/agents/openai.yaml +0 -3
  67. package/skills/diagnosing-bugs/LICENSE +0 -21
  68. package/skills/diagnosing-bugs/SKILL.md +0 -140
  69. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  70. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  71. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  72. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  73. package/skills/domain-modeling/LICENSE +0 -21
  74. package/skills/domain-modeling/SKILL.md +0 -76
  75. package/skills/domain-modeling/agents/openai.yaml +0 -3
  76. package/skills/grill-me/LICENSE +0 -21
  77. package/skills/grill-me/SKILL.md +0 -8
  78. package/skills/grill-me/agents/openai.yaml +0 -4
  79. package/skills/grill-with-docs/LICENSE +0 -21
  80. package/skills/grill-with-docs/SKILL.md +0 -8
  81. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  82. package/skills/grilling/LICENSE +0 -21
  83. package/skills/grilling/SKILL.md +0 -30
  84. package/skills/grilling/agents/openai.yaml +0 -3
  85. package/skills/handoff/LICENSE +0 -21
  86. package/skills/handoff/SKILL.md +0 -17
  87. package/skills/handoff/agents/openai.yaml +0 -4
  88. package/skills/implement/LICENSE +0 -21
  89. package/skills/implement/SKILL.md +0 -16
  90. package/skills/implement/agents/openai.yaml +0 -4
  91. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  92. package/skills/improve-codebase-architecture/LICENSE +0 -21
  93. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  94. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  95. package/skills/prototype/LICENSE +0 -21
  96. package/skills/prototype/LOGIC.md +0 -67
  97. package/skills/prototype/SKILL.md +0 -28
  98. package/skills/prototype/UI.md +0 -112
  99. package/skills/prototype/agents/openai.yaml +0 -3
  100. package/skills/research/LICENSE +0 -21
  101. package/skills/research/SKILL.md +0 -14
  102. package/skills/research/agents/openai.yaml +0 -3
  103. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  104. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  105. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  106. package/skills/tdd/LICENSE +0 -21
  107. package/skills/tdd/SKILL.md +0 -40
  108. package/skills/tdd/agents/openai.yaml +0 -3
  109. package/skills/tdd/mocking.md +0 -59
  110. package/skills/tdd/tests.md +0 -77
  111. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  112. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  113. package/skills/teach/LICENSE +0 -21
  114. package/skills/teach/MISSION-FORMAT.md +0 -31
  115. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  116. package/skills/teach/SKILL.md +0 -141
  117. package/skills/teach/agents/openai.yaml +0 -4
  118. package/skills/to-questionnaire/LICENSE +0 -21
  119. package/skills/to-questionnaire/SKILL.md +0 -55
  120. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  121. package/skills/to-spec/LICENSE +0 -21
  122. package/skills/to-spec/SKILL.md +0 -76
  123. package/skills/to-spec/agents/openai.yaml +0 -4
  124. package/skills/to-tickets/LICENSE +0 -21
  125. package/skills/to-tickets/SKILL.md +0 -106
  126. package/skills/to-tickets/agents/openai.yaml +0 -4
  127. package/skills/wait-what/LICENSE +0 -21
  128. package/skills/wait-what/SKILL.md +0 -8
  129. package/skills/wait-what/agents/openai.yaml +0 -4
  130. package/skills/wayfinder/LICENSE +0 -21
  131. package/skills/wayfinder/SKILL.md +0 -129
  132. package/skills/wayfinder/agents/openai.yaml +0 -4
  133. package/skills/writing-for-agents/LICENSE +0 -21
  134. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  135. package/skills/writing-for-agents/SKILL.md +0 -83
  136. package/skills/writing-for-agents/agents/openai.yaml +0 -3
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,39 @@
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
+ export function service() {
6
+ if (process.platform !== 'linux' || !process.env.INVOCATION_ID)
7
+ return null;
8
+ return process.env.MANAGERPID ? 'user' : 'system';
9
+ }
10
+ export function throughSudo() {
11
+ return service() === 'system' && process.getuid() !== 0;
12
+ }
13
+ export async function updatesItself() {
14
+ if (service() === null)
15
+ return false;
16
+ if (!throughSudo())
17
+ return true;
18
+ // sudo answers at once, so ten seconds only bounds a stuck sudo.
19
+ return (await run('sudo', ['-n', 'true'], 10_000)).status === 0;
20
+ }
21
+ function recorded(name) {
22
+ try {
23
+ return readFileSync(join(kitHome(), name), 'utf8').trim();
24
+ }
25
+ catch (error) {
26
+ if (error.code === 'ENOENT')
27
+ return null;
28
+ throw error;
29
+ }
30
+ }
31
+ export function installCommand() {
32
+ return recorded('install-command');
33
+ }
34
+ export function machine() {
35
+ const placed = recorded('placement');
36
+ if (placed === 'container' || placed === 'server' || placed === 'windows')
37
+ return placed;
38
+ return process.platform === 'darwin' ? 'macos' : 'linux';
39
+ }
@@ -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,87 +1,165 @@
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_METHODS, 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 { Calls } from './calls.js';
16
+ import { killDescendants } from './scope.js';
17
+ import { quoted } from './shell.js';
13
18
  import { SignIns } from './sign-in.js';
14
19
  import { placeSkillSet } from './skills.js';
15
- import { holdStream } from './stream.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';
16
24
  function report(error) {
17
25
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
18
26
  }
19
27
  function logged(work) {
20
28
  work.catch(report);
21
29
  }
22
- function quoted(value) {
23
- 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 });
24
34
  }
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
- });
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
+ }
31
45
  }
32
46
  async function serveOwner(copies) {
33
- const socketPath = join(kitHome(), 'owner.sock');
34
- 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
+ }
35
53
  const server = createServer(async (request, response) => {
36
54
  try {
37
- 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 {
38
69
  response.writeHead(404).end();
39
70
  return;
40
71
  }
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));
72
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answered));
44
73
  }
45
74
  catch (error) {
46
75
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
47
76
  }
48
77
  });
49
- server.listen(socketPath);
78
+ server.on('close', () => lock.close());
79
+ await rm(ownerSocket(), { force: true });
80
+ server.listen(ownerSocket());
50
81
  await once(server, 'listening');
51
82
  }
52
- 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
- }
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
+ }
95
+ function connected() {
96
+ return new Promise((resolve) => {
97
+ const watcher = watch(kitHome(), () => {
98
+ if (!enrolled())
99
+ return;
100
+ watcher.close();
101
+ resolve();
102
+ });
103
+ if (!enrolled()) {
104
+ process.stderr.write('kit: this Environment is not connected; run kit login\n');
105
+ return;
106
+ }
107
+ watcher.close();
108
+ resolve();
109
+ });
110
+ }
111
+ async function started() {
112
+ await connected();
113
+ await forgetRestart();
114
+ watch(kitHome(), () => {
115
+ if (enrolled())
116
+ return;
117
+ killDescendants();
118
+ process.exit(1);
119
+ });
58
120
  await placeSkillSet();
59
- process.env.HOUSE_KIT_RESIDENT = String(process.pid);
60
- const agents = new Agents(house);
61
- const copies = new WorkingCopies(house);
121
+ await mkdir(agentBase(), { recursive: true });
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 });
127
+ const copies = new LocalCopies(house);
62
128
  await copies.load();
63
- await installShim();
64
129
  await serveOwner(copies);
65
- 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;
66
137
  let reported = false;
67
- const idle = () => conversations.idle() && signIns.idle();
138
+ const idle = () => calls.idle() && conversations.idle() && agents.idle();
68
139
  const changed = () => {
69
140
  if (!idle()) {
70
141
  reported = false;
71
142
  }
143
+ else if (restartAsked() && conversations.quiet()) {
144
+ restart('restarting for an updated CLI');
145
+ }
72
146
  else if (!reported) {
73
147
  reported = true;
74
148
  logged(house.deliver('/kit/idle', {}, idle));
75
149
  }
76
150
  };
151
+ const calls = new Calls(house, changed);
77
152
  const conversations = new Conversations({
78
153
  house,
79
154
  agents,
80
155
  copies,
81
- send: (frame) => stream?.send(frame) ?? false,
156
+ calls,
157
+ send: (notification) => connection?.send(notification) ?? false,
82
158
  changed,
83
159
  });
84
- const signIns = new SignIns(house, agents, changed);
160
+ const signIns = new SignIns(house, agents, calls);
161
+ const update = new KitUpdate(calls);
162
+ const wizards = new WebWizards(calls, (notification) => connection?.send(notification) ?? false);
85
163
  for (const signal of ['SIGTERM', 'SIGINT']) {
86
164
  process.once(signal, () => {
87
165
  killDescendants();
@@ -89,28 +167,37 @@ export async function resident() {
89
167
  });
90
168
  }
91
169
  await house.deliver('/kit/restarted', {}).catch(report);
170
+ await update.resumed().catch(report);
92
171
  logged(agents.refresh());
93
- stream = holdStream({
172
+ connection = holdConnection({
94
173
  opened: () => {
95
174
  conversations.opened();
96
175
  changed();
97
- logged(copies.select());
176
+ logged(copies.connected());
98
177
  },
99
- frame: (arrived) => {
100
- if (arrived.type === 'work_available' && arrived.subject === 'agents')
101
- 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
- if (arrived.type === 'input') {
108
- reported = false;
109
- if (arrived.kind === 'sign_in')
110
- signIns.start(arrived);
111
- else
112
- conversations.input(arrived);
178
+ closed: () => wizards.disconnected(),
179
+ call: (call) => {
180
+ if (call.kind === 'sign_in')
181
+ signIns.start(call);
182
+ else if (call.kind === 'update')
183
+ update.start(call);
184
+ else if (call.kind === 'run_wizard')
185
+ wizards.start(call);
186
+ else if (CONVERSATION_METHODS.has(call.kind))
187
+ conversations.call(call);
188
+ else {
189
+ const refused = { refused: `This Kit does not know ${call.kind}; update the Kit` };
190
+ void calls.carry(call.input_id, async () => ({ result: refused }));
113
191
  }
114
192
  },
193
+ notification: (notification) => {
194
+ if (notification.type === 'watching')
195
+ conversations.watching(notification.watching === true);
196
+ if (notification.type === 'authority_changed')
197
+ logged(copies.changed(notification.rooms));
198
+ if (notification.type === 'work_available' && notification.subject === 'agents')
199
+ logged(agents.refresh());
200
+ wizards.notified(notification);
201
+ },
115
202
  });
116
203
  }
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,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;