@agentshouse/kit 0.2.1-c15804a0fa28d → 0.2.1-c23bd93c02c83

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 (101) hide show
  1. package/README.md +32 -31
  2. package/dist/acp.js +16 -93
  3. package/dist/agents.js +153 -44
  4. package/dist/api.js +34 -2
  5. package/dist/app-git.js +48 -0
  6. package/dist/bootstrap.json +4 -4
  7. package/dist/bridge.js +35 -56
  8. package/dist/chatgpt.js +32 -0
  9. package/dist/clis.js +137 -65
  10. package/dist/codex-main.js +58 -0
  11. package/dist/conversations.js +352 -244
  12. package/dist/copies.js +157 -116
  13. package/dist/end.js +23 -0
  14. package/dist/enrol-main.js +7 -1
  15. package/dist/events.js +524 -0
  16. package/dist/files.js +21 -1
  17. package/dist/git.js +10 -8
  18. package/dist/home.js +96 -7
  19. package/dist/house-cli.js +291 -0
  20. package/dist/house-main.js +7 -159
  21. package/dist/instructions.js +10 -32
  22. package/dist/kit-cli.js +68 -0
  23. package/dist/kit-main.js +8 -19
  24. package/dist/login.js +118 -103
  25. package/dist/logout.js +14 -13
  26. package/dist/parts.js +82 -0
  27. package/dist/placement.js +30 -0
  28. package/dist/refusals.js +12 -0
  29. package/dist/relay.js +12 -2
  30. package/dist/resident.js +84 -32
  31. package/dist/scope.js +203 -0
  32. package/dist/secret-input.js +4 -1
  33. package/dist/service-main.js +9 -0
  34. package/dist/service.js +33 -0
  35. package/dist/shell.js +3 -0
  36. package/dist/sign-in.js +34 -9
  37. package/dist/skills.js +81 -12
  38. package/dist/stream.js +87 -11
  39. package/dist/transcription.js +57 -9
  40. package/dist/update.js +30 -6
  41. package/dist/wire.js +6 -0
  42. package/dist/work.js +346 -0
  43. package/how-we-work.md +13 -3
  44. package/package.json +3 -2
  45. package/skills/ask-matt/SKILL.md +17 -11
  46. package/skills/ask-matt/agents/openai.yaml +1 -0
  47. package/skills/code-review/SKILL.md +5 -5
  48. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  49. package/skills/codebase-design/SKILL.md +0 -2
  50. package/skills/diagnosing-bugs/SKILL.md +2 -4
  51. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  52. package/skills/domain-modeling/SKILL.md +12 -14
  53. package/skills/grill-me/SKILL.md +1 -2
  54. package/skills/grill-me/agents/openai.yaml +1 -0
  55. package/skills/grill-with-docs/SKILL.md +1 -2
  56. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  57. package/skills/grilling/SKILL.md +2 -2
  58. package/skills/handoff/SKILL.md +2 -3
  59. package/skills/handoff/agents/openai.yaml +1 -0
  60. package/skills/implement/SKILL.md +5 -4
  61. package/skills/implement/agents/openai.yaml +1 -0
  62. package/skills/implement-spec/SKILL.md +40 -0
  63. package/skills/implement-spec/agents/openai.yaml +5 -0
  64. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  65. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  66. package/skills/pr/CREDITS.md +3 -0
  67. package/skills/pr/LICENSE +21 -0
  68. package/skills/pr/SKILL.md +170 -0
  69. package/skills/pr/agents/openai.yaml +3 -0
  70. package/skills/prototype/SKILL.md +0 -2
  71. package/skills/research/SKILL.md +0 -2
  72. package/skills/retro/LICENSE +21 -0
  73. package/skills/retro/SKILL.md +44 -0
  74. package/skills/retro/agents/openai.yaml +5 -0
  75. package/skills/tdd/SKILL.md +2 -4
  76. package/skills/teach/SKILL.md +3 -4
  77. package/skills/teach/agents/openai.yaml +1 -0
  78. package/skills/to-questionnaire/SKILL.md +1 -2
  79. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  80. package/skills/to-spec/SKILL.md +1 -2
  81. package/skills/to-spec/agents/openai.yaml +1 -0
  82. package/skills/to-tickets/SKILL.md +3 -4
  83. package/skills/to-tickets/agents/openai.yaml +1 -0
  84. package/skills/triage/AGENT-BRIEF.md +207 -0
  85. package/skills/triage/LICENSE +21 -0
  86. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  87. package/skills/triage/SKILL.md +112 -0
  88. package/skills/triage/agents/openai.yaml +5 -0
  89. package/skills/wait-what/SKILL.md +2 -3
  90. package/skills/wait-what/agents/openai.yaml +1 -0
  91. package/skills/wayfinder/SKILL.md +5 -6
  92. package/skills/wayfinder/agents/openai.yaml +1 -0
  93. package/skills/wizard/LICENSE +21 -0
  94. package/skills/wizard/SKILL.md +44 -0
  95. package/skills/wizard/agents/openai.yaml +3 -0
  96. package/skills/wizard/template.sh +223 -0
  97. package/skills/writing-for-agents/SKILL.md +0 -2
  98. package/dist/blocks.js +0 -51
  99. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  100. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  101. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/dist/resident.js CHANGED
@@ -1,56 +1,95 @@
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_INPUTS, 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, restartAsked } from './home.js';
15
+ import { killDescendants } from './scope.js';
16
+ import { quoted } from './shell.js';
14
17
  import { SignIns } from './sign-in.js';
15
18
  import { placeSkillSet } from './skills.js';
16
19
  import { holdStream } from './stream.js';
17
20
  import { Updates } from './update.js';
21
+ import { codexLauncher } from './work.js';
18
22
  function report(error) {
19
23
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
20
24
  }
21
25
  function logged(work) {
22
26
  work.catch(report);
23
27
  }
24
- function quoted(value) {
25
- return `'${value.replaceAll("'", `'\\''`)}'`;
28
+ async function installShim(path, module) {
29
+ const main = fileURLToPath(new URL(`./${module}${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
30
+ await mkdir(dirname(path), { recursive: true });
31
+ await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
26
32
  }
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
- });
33
+ function claimed(lock) {
34
+ try {
35
+ lock.exec('BEGIN EXCLUSIVE');
36
+ return true;
37
+ }
38
+ catch (error) {
39
+ if (error.errcode === 5)
40
+ return false;
41
+ throw error;
42
+ }
33
43
  }
34
44
  async function serveOwner(copies) {
35
- const socketPath = join(kitHome(), 'owner.sock');
36
- await rm(socketPath, { force: true });
45
+ const lock = new DatabaseSync(ownerLock());
46
+ if (!claimed(lock)) {
47
+ lock.close();
48
+ const running = await runningResident();
49
+ throw new Error(`${running === null ? 'another Kit' : `Kit ${running}`} already runs this Environment from Kit home ${kitHome()}; stop it first to run another here`);
50
+ }
37
51
  const server = createServer(async (request, response) => {
38
52
  try {
39
- if (request.url !== '/git/push') {
53
+ const text = await received(request);
54
+ let answered;
55
+ if (request.url === '/resident') {
56
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ pid: process.pid }));
57
+ return;
58
+ }
59
+ if (request.url === '/git/fetch') {
60
+ answered = await copies.fetch();
61
+ }
62
+ else if (request.url === '/git/push') {
63
+ const { cwd, commit } = JSON.parse(text);
64
+ answered = await copies.push(cwd, commit, copies.owner);
65
+ }
66
+ else {
40
67
  response.writeHead(404).end();
41
68
  return;
42
69
  }
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));
70
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answered));
46
71
  }
47
72
  catch (error) {
48
73
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
49
74
  }
50
75
  });
51
- server.listen(socketPath);
76
+ server.on('close', () => lock.close());
77
+ await rm(ownerSocket(), { force: true });
78
+ server.listen(ownerSocket());
52
79
  await once(server, 'listening');
53
80
  }
81
+ function runningResident() {
82
+ return new Promise((resolve, reject) => {
83
+ get({ socketPath: ownerSocket(), path: '/resident' }, (answer) => {
84
+ received(answer).then((text) => resolve(JSON.parse(text).pid), reject);
85
+ }).on('error', (error) => {
86
+ if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
87
+ resolve(null);
88
+ else
89
+ reject(error);
90
+ });
91
+ });
92
+ }
54
93
  function connected() {
55
94
  return new Promise((resolve) => {
56
95
  const watcher = watch(kitHome(), () => {
@@ -67,8 +106,9 @@ function connected() {
67
106
  resolve();
68
107
  });
69
108
  }
70
- export async function resident() {
109
+ async function started() {
71
110
  await connected();
111
+ await forgetRestart();
72
112
  watch(kitHome(), () => {
73
113
  if (enrolled())
74
114
  return;
@@ -77,19 +117,30 @@ export async function resident() {
77
117
  });
78
118
  await placeSkillSet();
79
119
  await mkdir(agentBase(), { recursive: true });
80
- process.env.HOUSE_KIT_RESIDENT = String(process.pid);
81
- const agents = new Agents(house);
120
+ await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
121
+ await installShim(codexLauncher(), 'codex-main');
122
+ }
123
+ export async function resident() {
124
+ await mkdir(kitHome(), { recursive: true, mode: 0o700 });
82
125
  const copies = new LocalCopies(house);
83
126
  await copies.load();
84
- await installShim();
85
127
  await serveOwner(copies);
128
+ await started().catch((error) => {
129
+ report(error);
130
+ process.exit(1);
131
+ });
132
+ process.env.HOUSE_KIT_RESIDENT = String(process.pid);
133
+ const agents = new Agents(house, () => changed());
86
134
  let stream = null;
87
135
  let reported = false;
88
- const idle = () => conversations.idle() && signIns.idle();
136
+ const idle = () => conversations.idle() && signIns.idle() && agents.idle();
89
137
  const changed = () => {
90
138
  if (!idle()) {
91
139
  reported = false;
92
140
  }
141
+ else if (restartAsked() && conversations.quiet()) {
142
+ restart('restarting for an updated CLI');
143
+ }
93
144
  else if (!reported) {
94
145
  reported = true;
95
146
  logged(house.deliver('/kit/idle', {}, idle));
@@ -117,24 +168,25 @@ export async function resident() {
117
168
  opened: () => {
118
169
  conversations.opened();
119
170
  changed();
120
- logged(copies.select());
171
+ logged(copies.connected());
121
172
  },
122
173
  frame: (arrived) => {
174
+ if (arrived.type === 'watching')
175
+ conversations.watching(arrived.watching === true);
123
176
  if (arrived.type === 'work_available' && arrived.subject === 'agents')
124
177
  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
178
  if (arrived.type === 'input') {
131
179
  reported = false;
132
180
  if (arrived.kind === 'sign_in')
133
181
  signIns.start(arrived);
134
182
  else if (arrived.kind === 'update')
135
183
  updates.start(arrived);
136
- else
184
+ else if (CONVERSATION_INPUTS.has(arrived.kind))
137
185
  conversations.input(arrived);
186
+ else {
187
+ const refused = { refused: `This Kit does not know ${arrived.kind}; update the Kit` };
188
+ logged(house.deliver(`/kit/inputs/${arrived.input_id}/ack`, refused).finally(changed));
189
+ }
138
190
  }
139
191
  },
140
192
  });
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,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,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,7 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
- import { killTree } from './acp.js';
4
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+/;
@@ -12,6 +12,9 @@ function causeOf(error) {
12
12
  function logged(error) {
13
13
  process.stderr.write(`kit: ${causeOf(error)}\n`);
14
14
  }
15
+ function endOf(signal) {
16
+ return new Promise((resolve) => signal.addEventListener('abort', () => resolve(true), { once: true }));
17
+ }
15
18
  export class SignIns {
16
19
  house;
17
20
  agents;
@@ -30,24 +33,43 @@ export class SignIns {
30
33
  return;
31
34
  this.running.add(input.input_id);
32
35
  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
+ this.signIn(input)
36
37
  .catch(logged)
37
38
  .finally(() => {
38
39
  this.running.delete(input.input_id);
39
40
  this.changed();
40
41
  });
41
42
  }
42
- async login(input) {
43
+ async signIn(input) {
44
+ const ending = new AbortController();
45
+ // 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.
46
+ const timer = setTimeout(() => ending.abort(), input.ends_in * 1000);
47
+ const ended = await Promise.race([this.signedIn(input, ending.signal), endOf(ending.signal)]);
48
+ clearTimeout(timer);
49
+ if (ended)
50
+ process.stderr.write(`kit: the ${input.cli} sign-in reached the end House set for it\n`);
51
+ await this.house.deliver(`/kit/inputs/${input.input_id}/ack`, {});
52
+ if (!ended)
53
+ await this.agents.reread(input.cli);
54
+ }
55
+ async signedIn(input, signal) {
56
+ await this.login(input, signal);
57
+ if (!signal.aborted)
58
+ await this.agents.recheck(input.cli, signal);
59
+ return false;
60
+ }
61
+ async login(input, signal) {
43
62
  let cli;
44
63
  try {
45
- cli = await this.agents.located(input.cli);
64
+ cli = await this.agents.located(input.cli, signal);
46
65
  }
47
66
  catch (error) {
48
- process.stderr.write(`kit: the ${input.cli} sign-in failed: ${causeOf(error)}\n`);
67
+ if (!signal.aborted)
68
+ process.stderr.write(`kit: the ${input.cli} sign-in failed: ${causeOf(error)}\n`);
49
69
  return;
50
70
  }
71
+ if (signal.aborted)
72
+ return;
51
73
  const login = CLIS[input.cli].login;
52
74
  const child = spawn(cli, login.args, {
53
75
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -55,6 +77,8 @@ export class SignIns {
55
77
  env: withoutProxy(),
56
78
  });
57
79
  const running = () => child.exitCode === null && child.signalCode === null;
80
+ const stop = () => killTree(child);
81
+ signal.addEventListener('abort', stop, { once: true });
58
82
  let link;
59
83
  let code;
60
84
  let last = '';
@@ -91,9 +115,10 @@ export class SignIns {
91
115
  createInterface({ input: output }).on('line', read);
92
116
  const failed = await new Promise((resolve) => {
93
117
  child.on('error', (error) => resolve(error.message));
94
- child.on('close', (status, signal) => resolve(status === 0 ? null : `exited with ${status ?? signal}${last ? `: ${last}` : ''}`));
118
+ child.on('close', (status, killed) => resolve(status === 0 ? null : `exited with ${status ?? killed}${last ? `: ${last}` : ''}`));
95
119
  });
96
- if (failed !== null)
120
+ signal.removeEventListener('abort', stop);
121
+ if (failed !== null && !signal.aborted)
97
122
  process.stderr.write(`kit: the ${input.cli} sign-in failed: ${failed}\n`);
98
123
  }
99
124
  }
package/dist/skills.js CHANGED
@@ -1,17 +1,31 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { readFileSync } from 'node:fs';
2
- import { cp, lstat, mkdir, readdir, realpath, rm, symlink, writeFile } from 'node:fs/promises';
3
+ import { cp, lstat, mkdir, readdir, realpath, rm, symlink } from 'node:fs/promises';
3
4
  import { homedir } from 'node:os';
4
5
  import { join, relative } from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
7
+ import { parse } from 'yaml';
6
8
  import { KIT_VERSION } from './clis.js';
7
9
  import { kitHome, readConfiguration, readHome, writeHome } from './home.js';
8
10
  import { refusalOf } from './refusals.js';
9
- export const HOW_WE_WORK = '/rooms/private/how-we-work.md';
11
+ const HOW_WE_WORK = '/rooms/private/how-we-work.md';
10
12
  const SKILL_SET = fileURLToPath(new URL('../skills/', import.meta.url));
11
13
  const HOW_WE_WORK_TEXT = readFileSync(new URL('../how-we-work.md', import.meta.url), 'utf8');
14
+ const SHIPPED_HOW_WE_WORK = [
15
+ 'ae4dda60da7b174f22dc5fa9bf07fc27c25864932a74230de4f9f509ddd91f41',
16
+ '0bdcd43e1603ba6673a3cae56d70bbf90657cbeefd124e91a47be2ca1cbd6c93',
17
+ '4106a87ec66da6f7b2a10e74d18e6559d68d5f4fe7415dae68f5c7bdb9081968',
18
+ 'ac814a2197038f037b657bb719340395f89f319ac9fcdd386629c3fe2cec68f1',
19
+ '29951ee394aad9979eecfed3e5dc32c2c86e2226b6a380db5dbd4f305f4d1156',
20
+ ];
12
21
  const RECORD = 'skill-set.json';
13
- const CREATED = 'how-we-work-created';
22
+ const WRITTEN = 'how-we-work.json';
14
23
  const UNWRITABLE = new Set(['room_not_found', 'operation_denied']);
24
+ const PRESENT = new Set(['path_exists']);
25
+ const CHANGED = new Set(['base_revision_stale', 'path_absent']);
26
+ const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
27
+ const FAILED = /^exit: [1-9]\d*$/;
28
+ const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
15
29
  function skillsDirectory() {
16
30
  return join(homedir(), '.agents', 'skills');
17
31
  }
@@ -49,6 +63,14 @@ async function install() {
49
63
  await writeHome(RECORD, { version: KIT_VERSION, names });
50
64
  }
51
65
  export async function placeSkillSet() {
66
+ try {
67
+ await replaceSkillSet();
68
+ }
69
+ catch (error) {
70
+ process.stderr.write(`kit: the skills could not be placed: ${error.message}\n`);
71
+ }
72
+ }
73
+ async function replaceSkillSet() {
52
74
  const accepted = (await readConfiguration()).skills;
53
75
  const installed = await readHome(RECORD);
54
76
  if (accepted && installed?.version === KIT_VERSION)
@@ -62,17 +84,64 @@ export async function placeSkillSet() {
62
84
  else
63
85
  await rm(join(kitHome(), RECORD), { force: true });
64
86
  }
87
+ function sha256(text) {
88
+ return createHash('sha256').update(text).digest('hex');
89
+ }
90
+ function cutOf(lines) {
91
+ const cut = CUT.exec(lines[0] ?? '');
92
+ return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
93
+ }
94
+ export async function readHowWeWork(bridge) {
95
+ let document = '';
96
+ for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
97
+ const read = await bridge.tool('shell', { command });
98
+ const text = read.content.map((content) => content.text).join('\n');
99
+ const lines = text.split('\n');
100
+ if (read.isError === true || (FAILED.test(lines[0] ?? '') && lines[1]?.startsWith('stderr: '))) {
101
+ const refusal = read.isError === true ? text : lines.slice(1).join('\n').replace(/^stderr: /gm, '');
102
+ if (UNREADABLE.test(refusal))
103
+ return '';
104
+ throw new Error(refusal);
105
+ }
106
+ const cut = cutOf(lines);
107
+ document += lines.slice(cut === null ? 0 : 1).join('\n');
108
+ command = cut?.[2];
109
+ }
110
+ return document;
111
+ }
112
+ async function currentRevision(bridge) {
113
+ const inspected = await bridge.tool('inspect', { path: HOW_WE_WORK });
114
+ const text = inspected.content.map((content) => content.text).join('\n');
115
+ if (inspected.isError === true)
116
+ throw new Error(text);
117
+ return parse(text).revisions[0].revision;
118
+ }
119
+ async function edit(bridge, change, kept) {
120
+ const edited = await bridge.tool('edit', { changes: [{ ...change, path: HOW_WE_WORK, content: HOW_WE_WORK_TEXT }] });
121
+ if (edited.isError !== true)
122
+ return 'written';
123
+ const text = edited.content.map((content) => content.text).join('\n');
124
+ const refusal = refusalOf(text);
125
+ if (UNWRITABLE.has(refusal?.code ?? ''))
126
+ return 'unwritable';
127
+ if (refusal?.code === 'edit_conflict' && refusal.conflicts.some((conflict) => kept.has(conflict)))
128
+ return 'kept';
129
+ throw new Error(text);
130
+ }
65
131
  export async function createHowWeWork(bridge) {
66
- if ((await readHome(RECORD)) === null || (await present(join(kitHome(), CREATED))))
132
+ if (!(await readConfiguration()).skills || (await readHome(RECORD))?.version === undefined)
133
+ return;
134
+ const current = sha256(HOW_WE_WORK_TEXT);
135
+ if ((await readHome(WRITTEN)) === current)
136
+ return;
137
+ const created = await edit(bridge, { op: 'create' }, PRESENT);
138
+ if (created === 'unwritable')
67
139
  return;
68
- const created = await bridge.tool('edit', { changes: [{ op: 'create', path: HOW_WE_WORK, content: HOW_WE_WORK_TEXT }] });
69
- if (created.isError === true) {
70
- const text = created.content.map((content) => content.text).join('\n');
71
- const refusal = refusalOf(text);
72
- if (UNWRITABLE.has(refusal?.code ?? ''))
140
+ if (created === 'kept') {
141
+ const base = await currentRevision(bridge);
142
+ const held = sha256(await readHowWeWork(bridge));
143
+ if (held !== current && SHIPPED_HOW_WE_WORK.includes(held) && (await edit(bridge, { op: 'replace', base }, CHANGED)) === 'unwritable')
73
144
  return;
74
- if (refusal?.code !== 'edit_conflict' || !refusal.conflicts.includes('path_exists'))
75
- throw new Error(text);
76
145
  }
77
- await writeFile(join(kitHome(), CREATED), '');
146
+ await writeHome(WRITTEN, current);
78
147
  }