@agentshouse/kit 0.2.1-ccf188e02985d → 0.2.1-cd423aab3dbcc

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 (164) hide show
  1. package/README.md +35 -42
  2. package/dist/acp.js +66 -12
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +122 -53
  5. package/dist/api.js +15 -10
  6. package/dist/binaries.js +60 -0
  7. package/dist/bridge.js +100 -45
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +54 -0
  11. package/dist/clis.js +62 -50
  12. package/dist/connect.js +121 -0
  13. package/dist/connection.js +120 -0
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +617 -240
  16. package/dist/copies.js +1277 -623
  17. package/dist/earlier.js +273 -0
  18. package/dist/end.js +12 -5
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +206 -38
  21. package/dist/git.js +2 -72
  22. package/dist/grok.js +39 -0
  23. package/dist/home.js +86 -29
  24. package/dist/house-cli.js +180 -189
  25. package/dist/house-main.js +3 -3
  26. package/dist/instructions.js +29 -11
  27. package/dist/keys.js +238 -0
  28. package/dist/kit-cli.js +18 -8
  29. package/dist/kit-main.js +3 -3
  30. package/dist/login.js +36 -22
  31. package/dist/logout.js +2 -2
  32. package/dist/manifest.js +75 -0
  33. package/dist/mcp.js +47 -7
  34. package/dist/owner.js +46 -0
  35. package/dist/placement.js +15 -20
  36. package/dist/refusals.js +50 -23
  37. package/dist/relay.js +21 -0
  38. package/dist/resident.js +141 -90
  39. package/dist/scope.js +15 -4
  40. package/dist/scripts.js +319 -0
  41. package/dist/secret-input.js +1 -1
  42. package/dist/settings.js +247 -0
  43. package/dist/sign-in.js +67 -21
  44. package/dist/silence.js +28 -0
  45. package/dist/skills.js +42 -97
  46. package/dist/supervisor.js +163 -0
  47. package/dist/transcription.js +88 -45
  48. package/dist/update.js +118 -120
  49. package/dist/wire.js +30 -4
  50. package/dist/work.js +27 -2
  51. package/dist/workspace.js +113 -0
  52. package/package.json +25 -22
  53. package/dist/authority-main.js +0 -22
  54. package/dist/bootstrap.json +0 -24
  55. package/dist/chatgpt.js +0 -32
  56. package/dist/clis-main.js +0 -23
  57. package/dist/configure-main.js +0 -6
  58. package/dist/enrol-main.js +0 -10
  59. package/dist/git-main.js +0 -153
  60. package/dist/inputs.js +0 -37
  61. package/dist/parts.js +0 -82
  62. package/dist/service-main.js +0 -9
  63. package/dist/service.js +0 -55
  64. package/dist/stream.js +0 -123
  65. package/dist/translate.js +0 -51
  66. package/how-we-work.md +0 -33
  67. package/skills/ask-matt/LICENSE +0 -21
  68. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  69. package/skills/ask-matt/SKILL.md +0 -97
  70. package/skills/ask-matt/agents/openai.yaml +0 -5
  71. package/skills/code-review/LICENSE +0 -21
  72. package/skills/code-review/SKILL.md +0 -89
  73. package/skills/code-review/agents/openai.yaml +0 -3
  74. package/skills/codebase-design/DEEPENING.md +0 -37
  75. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  76. package/skills/codebase-design/LICENSE +0 -21
  77. package/skills/codebase-design/SKILL.md +0 -114
  78. package/skills/codebase-design/agents/openai.yaml +0 -3
  79. package/skills/diagnosing-bugs/LICENSE +0 -21
  80. package/skills/diagnosing-bugs/SKILL.md +0 -138
  81. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  82. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  83. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  84. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  85. package/skills/domain-modeling/LICENSE +0 -21
  86. package/skills/domain-modeling/SKILL.md +0 -74
  87. package/skills/domain-modeling/agents/openai.yaml +0 -3
  88. package/skills/grill-me/LICENSE +0 -21
  89. package/skills/grill-me/SKILL.md +0 -7
  90. package/skills/grill-me/agents/openai.yaml +0 -5
  91. package/skills/grill-with-docs/LICENSE +0 -21
  92. package/skills/grill-with-docs/SKILL.md +0 -7
  93. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  94. package/skills/grilling/LICENSE +0 -21
  95. package/skills/grilling/SKILL.md +0 -30
  96. package/skills/grilling/agents/openai.yaml +0 -3
  97. package/skills/handoff/LICENSE +0 -21
  98. package/skills/handoff/SKILL.md +0 -16
  99. package/skills/handoff/agents/openai.yaml +0 -5
  100. package/skills/implement/LICENSE +0 -21
  101. package/skills/implement/SKILL.md +0 -17
  102. package/skills/implement/agents/openai.yaml +0 -5
  103. package/skills/implement-spec/LICENSE +0 -21
  104. package/skills/implement-spec/SKILL.md +0 -40
  105. package/skills/implement-spec/agents/openai.yaml +0 -5
  106. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  107. package/skills/improve-codebase-architecture/LICENSE +0 -21
  108. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  109. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  110. package/skills/pr/CREDITS.md +0 -3
  111. package/skills/pr/LICENSE +0 -21
  112. package/skills/pr/SKILL.md +0 -170
  113. package/skills/pr/agents/openai.yaml +0 -3
  114. package/skills/prototype/LICENSE +0 -21
  115. package/skills/prototype/LOGIC.md +0 -67
  116. package/skills/prototype/SKILL.md +0 -26
  117. package/skills/prototype/UI.md +0 -112
  118. package/skills/prototype/agents/openai.yaml +0 -3
  119. package/skills/research/LICENSE +0 -21
  120. package/skills/research/SKILL.md +0 -12
  121. package/skills/research/agents/openai.yaml +0 -3
  122. package/skills/retro/LICENSE +0 -21
  123. package/skills/retro/SKILL.md +0 -44
  124. package/skills/retro/agents/openai.yaml +0 -5
  125. package/skills/tdd/LICENSE +0 -21
  126. package/skills/tdd/SKILL.md +0 -38
  127. package/skills/tdd/agents/openai.yaml +0 -3
  128. package/skills/tdd/mocking.md +0 -59
  129. package/skills/tdd/tests.md +0 -77
  130. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  131. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  132. package/skills/teach/LICENSE +0 -21
  133. package/skills/teach/MISSION-FORMAT.md +0 -31
  134. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  135. package/skills/teach/SKILL.md +0 -140
  136. package/skills/teach/agents/openai.yaml +0 -5
  137. package/skills/to-questionnaire/LICENSE +0 -21
  138. package/skills/to-questionnaire/SKILL.md +0 -54
  139. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  140. package/skills/to-spec/LICENSE +0 -21
  141. package/skills/to-spec/SKILL.md +0 -75
  142. package/skills/to-spec/agents/openai.yaml +0 -5
  143. package/skills/to-tickets/LICENSE +0 -21
  144. package/skills/to-tickets/SKILL.md +0 -105
  145. package/skills/to-tickets/agents/openai.yaml +0 -5
  146. package/skills/triage/AGENT-BRIEF.md +0 -207
  147. package/skills/triage/LICENSE +0 -21
  148. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  149. package/skills/triage/SKILL.md +0 -112
  150. package/skills/triage/agents/openai.yaml +0 -5
  151. package/skills/wait-what/LICENSE +0 -21
  152. package/skills/wait-what/SKILL.md +0 -7
  153. package/skills/wait-what/agents/openai.yaml +0 -5
  154. package/skills/wayfinder/LICENSE +0 -21
  155. package/skills/wayfinder/SKILL.md +0 -128
  156. package/skills/wayfinder/agents/openai.yaml +0 -5
  157. package/skills/wizard/LICENSE +0 -21
  158. package/skills/wizard/SKILL.md +0 -44
  159. package/skills/wizard/agents/openai.yaml +0 -3
  160. package/skills/wizard/template.sh +0 -223
  161. package/skills/writing-for-agents/LICENSE +0 -21
  162. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  163. package/skills/writing-for-agents/SKILL.md +0 -81
  164. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/sign-in.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
- import { CLIS, withoutProxy } from './clis.js';
3
+ import { CLIS, cliEnvironment } from './clis.js';
4
4
  import { killTree } from './scope.js';
5
5
  import { holdSecretInput } from './secret-input.js';
6
6
  const ESCAPE = /\u001b\[[\d;]*m/g;
@@ -9,54 +9,100 @@ const CODE = /^[A-Z0-9]+-[A-Z0-9]+$/;
9
9
  function causeOf(error) {
10
10
  return error instanceof Error ? error.message : String(error);
11
11
  }
12
+ function keySteps(name) {
13
+ return [
14
+ { kind: 'collect', label: 'API key', name: 'key' },
15
+ {
16
+ kind: 'collect',
17
+ label: 'Endpoint, for another provider',
18
+ name: 'endpoint',
19
+ description: `Leave Endpoint empty for ${name}’s own. Both stay on this computer.`,
20
+ optional: true,
21
+ },
22
+ ];
23
+ }
24
+ function endpointOf(given) {
25
+ const endpoint = given.trim();
26
+ if (endpoint === '')
27
+ return null;
28
+ let protocol;
29
+ try {
30
+ protocol = new URL(endpoint).protocol;
31
+ }
32
+ catch {
33
+ protocol = '';
34
+ }
35
+ if (protocol !== 'https:' && protocol !== 'http:')
36
+ throw new Error('the endpoint is no http or https address');
37
+ return endpoint;
38
+ }
12
39
  function endOf(signal) {
13
40
  return new Promise((resolve) => signal.addEventListener('abort', () => resolve(true), { once: true }));
14
41
  }
15
42
  export class SignIns {
16
43
  house;
17
44
  agents;
18
- inputs;
19
- constructor(house, agents, inputs) {
45
+ calls;
46
+ constructor(house, agents, calls) {
20
47
  this.house = house;
21
48
  this.agents = agents;
22
- this.inputs = inputs;
49
+ this.calls = calls;
23
50
  }
24
- start(input) {
25
- void this.inputs.carry(input.input_id, () => this.signIn(input));
51
+ start(call) {
52
+ void this.calls.carry(call.input_id, () => this.signIn(call));
26
53
  }
27
- async signIn(input) {
54
+ async signIn(call) {
28
55
  const ending = new AbortController();
29
56
  // House stops waiting for a sign-in ten minutes after it wrote it and sends the seconds left, so its install and login end with the page.
30
- const timer = setTimeout(() => ending.abort(), input.ends_in * 1000);
31
- const ended = await Promise.race([this.signedIn(input, ending.signal), endOf(ending.signal)]);
57
+ const timer = setTimeout(() => ending.abort(), call.ends_in * 1000);
58
+ const ended = await Promise.race([this.signedIn(call, ending.signal), endOf(ending.signal)]);
32
59
  clearTimeout(timer);
33
60
  if (ended)
34
- process.stderr.write(`kit: the ${input.cli} sign-in reached the end House set for it\n`);
35
- return ended ? { ack: {} } : { ack: {}, acknowledged: () => this.agents.reread(input.cli) };
61
+ process.stderr.write(`kit: the ${call.cli} sign-in reached the end House set for it\n`);
62
+ return ended ? { result: {} } : { result: {}, returned: () => this.agents.reread(call.cli) };
36
63
  }
37
- async signedIn(input, signal) {
38
- await this.login(input, signal);
64
+ async signedIn(call, signal) {
65
+ await (call.api_key === true ? this.keyed(call, signal) : this.login(call, signal));
39
66
  if (!signal.aborted)
40
- await this.agents.recheck(input.cli, signal);
67
+ await this.agents.recheck(call.cli, signal);
41
68
  return false;
42
69
  }
43
- async login(input, signal) {
70
+ async keyed(call, signal) {
71
+ const { name, key } = CLIS[call.cli];
72
+ let secret = '';
73
+ try {
74
+ const cli = await this.agents.located(call.cli, signal);
75
+ const given = await holdSecretInput(this.house, call.input_id, keySteps(name), () => !signal.aborted);
76
+ if (given === null || signal.aborted)
77
+ return;
78
+ secret = given.key.trim();
79
+ await key.write(secret, endpointOf(given.endpoint), cli, signal);
80
+ }
81
+ catch (error) {
82
+ const cause = secret === '' ? causeOf(error) : causeOf(error).replaceAll(secret, 'the key');
83
+ if (!signal.aborted)
84
+ process.stderr.write(`kit: the ${call.cli} sign-in failed: ${cause}\n`);
85
+ }
86
+ }
87
+ async login(call, signal) {
44
88
  let cli;
89
+ let env;
45
90
  try {
46
- cli = await this.agents.located(input.cli, signal);
91
+ cli = await this.agents.located(call.cli, signal);
92
+ env = await cliEnvironment(call.cli);
47
93
  }
48
94
  catch (error) {
49
95
  if (!signal.aborted)
50
- process.stderr.write(`kit: the ${input.cli} sign-in failed: ${causeOf(error)}\n`);
96
+ process.stderr.write(`kit: the ${call.cli} sign-in failed: ${causeOf(error)}\n`);
51
97
  return;
52
98
  }
53
99
  if (signal.aborted)
54
100
  return;
55
- const login = CLIS[input.cli].login;
101
+ const login = CLIS[call.cli].login;
56
102
  const child = spawn(cli, login.args, {
57
103
  stdio: ['pipe', 'pipe', 'pipe'],
58
104
  detached: true,
59
- env: withoutProxy(),
105
+ env,
60
106
  });
61
107
  const running = () => child.exitCode === null && child.signalCode === null;
62
108
  const stop = () => killTree(child);
@@ -84,7 +130,7 @@ export class SignIns {
84
130
  return;
85
131
  held = true;
86
132
  const steps = [{ kind: 'visit', label: 'Open this link and sign in', url: link }, step];
87
- void holdSecretInput(this.house, input.input_id, steps, running).then((content) => {
133
+ void holdSecretInput(this.house, call.input_id, steps, running).then((content) => {
88
134
  if (!running())
89
135
  return;
90
136
  if (content === null)
@@ -101,6 +147,6 @@ export class SignIns {
101
147
  });
102
148
  signal.removeEventListener('abort', stop);
103
149
  if (failed !== null && !signal.aborted)
104
- process.stderr.write(`kit: the ${input.cli} sign-in failed: ${failed}\n`);
150
+ process.stderr.write(`kit: the ${call.cli} sign-in failed: ${failed}\n`);
105
151
  }
106
152
  }
@@ -0,0 +1,28 @@
1
+ const SYSTEM_CLOCK = {
2
+ later: (delay, callback) => setTimeout(callback, delay),
3
+ clear: (timer) => clearTimeout(timer),
4
+ };
5
+ export class Silence {
6
+ timer = null;
7
+ interval;
8
+ silent;
9
+ clock;
10
+ constructor(interval, silent, clock = SYSTEM_CLOCK) {
11
+ this.interval = interval;
12
+ this.silent = silent;
13
+ this.clock = clock;
14
+ }
15
+ heard() {
16
+ this.stop();
17
+ this.timer = this.clock.later(this.interval, () => {
18
+ this.timer = null;
19
+ this.silent();
20
+ });
21
+ }
22
+ stop() {
23
+ if (this.timer === null)
24
+ return;
25
+ this.clock.clear(this.timer);
26
+ this.timer = null;
27
+ }
28
+ }
package/dist/skills.js CHANGED
@@ -1,31 +1,14 @@
1
- import { createHash } from 'node:crypto';
2
- import { readFileSync } from 'node:fs';
3
- import { cp, lstat, mkdir, readdir, realpath, rm, symlink } from 'node:fs/promises';
1
+ import { cp, lstat, mkdir, realpath, rm, symlink, writeFile } from 'node:fs/promises';
4
2
  import { homedir } from 'node:os';
5
3
  import { join, relative } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
4
+ import { GUIDE, listSkills } from '@agentshouse/skills';
7
5
  import { parse } from 'yaml';
8
- import { KIT_VERSION } from './clis.js';
6
+ import { KIT_RELEASE } from './clis.js';
9
7
  import { kitHome, readConfiguration, readHome, writeHome } from './home.js';
10
- import { refusalOf } from './refusals.js';
11
- const HOW_WE_WORK = '/rooms/private/how-we-work.md';
12
- const SKILL_SET = fileURLToPath(new URL('../skills/', import.meta.url));
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
- ];
21
8
  const RECORD = 'skill-set.json';
22
- const WRITTEN = 'how-we-work.json';
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: (.+)$/;
9
+ const ENTRY = 'SKILL.md';
10
+ const FRONTMATTER = /^---\n([\s\S]*?)\n---\n/u;
11
+ const ORIGIN = '<origin>';
29
12
  function skillsDirectory() {
30
13
  return join(homedir(), '.agents', 'skills');
31
14
  }
@@ -43,105 +26,67 @@ async function present(path) {
43
26
  throw error;
44
27
  }
45
28
  }
46
- async function install() {
47
- const names = [];
48
- for (const name of (await readdir(SKILL_SET)).sort()) {
49
- if (!(await present(join(skillsDirectory(), name))) && !(await present(join(claudeDirectory(), name)))) {
50
- names.push(name);
29
+ function skillName(text) {
30
+ const front = FRONTMATTER.exec(text);
31
+ const fields = (front === null ? null : parse(front[1]));
32
+ return typeof fields?.name === 'string' && typeof fields.description === 'string' ? fields.name : undefined;
33
+ }
34
+ function skillSet(origin) {
35
+ const upstream = listSkills().map(({ name, directory }) => ({
36
+ name,
37
+ place: (destination) => cp(directory, destination, { recursive: true }),
38
+ }));
39
+ const pages = GUIDE.flatMap(({ text }) => {
40
+ const name = skillName(text);
41
+ if (name === undefined)
42
+ return [];
43
+ const place = async (destination) => {
44
+ await mkdir(destination);
45
+ await writeFile(join(destination, ENTRY), text.replaceAll(ORIGIN, origin));
46
+ };
47
+ return [{ name, place }];
48
+ });
49
+ return [...upstream, ...pages].sort((left, right) => (left.name < right.name ? -1 : 1));
50
+ }
51
+ async function install(origin) {
52
+ const placed = [];
53
+ for (const skill of skillSet(origin)) {
54
+ if (!(await present(join(skillsDirectory(), skill.name))) && !(await present(join(claudeDirectory(), skill.name)))) {
55
+ placed.push(skill);
51
56
  }
52
57
  }
58
+ const names = placed.map((skill) => skill.name);
53
59
  await writeHome(RECORD, { names });
54
60
  await mkdir(skillsDirectory(), { recursive: true });
55
61
  await mkdir(claudeDirectory(), { recursive: true });
56
62
  const skills = await realpath(skillsDirectory());
57
63
  const claude = await realpath(claudeDirectory());
58
- for (const name of names) {
59
- await cp(join(SKILL_SET, name), join(skillsDirectory(), name), { recursive: true });
64
+ for (const { name, place } of placed) {
65
+ await place(join(skillsDirectory(), name));
60
66
  if (claude !== skills)
61
67
  await symlink(relative(claude, join(skills, name)), join(claudeDirectory(), name));
62
68
  }
63
- await writeHome(RECORD, { version: KIT_VERSION, names });
69
+ await writeHome(RECORD, { version: KIT_RELEASE, origin, names });
64
70
  }
65
- export async function placeSkillSet() {
71
+ export async function placeSkillSet(origin) {
66
72
  try {
67
- await replaceSkillSet();
73
+ await replaceSkillSet(origin);
68
74
  }
69
75
  catch (error) {
70
76
  process.stderr.write(`kit: the skills could not be placed: ${error.message}\n`);
71
77
  }
72
78
  }
73
- async function replaceSkillSet() {
79
+ async function replaceSkillSet(origin) {
74
80
  const accepted = (await readConfiguration()).skills;
75
81
  const installed = await readHome(RECORD);
76
- if (accepted && installed?.version === KIT_VERSION)
82
+ if (accepted && installed?.version === KIT_RELEASE && installed.origin === origin)
77
83
  return;
78
84
  for (const name of installed?.names ?? []) {
79
85
  await rm(join(claudeDirectory(), name), { recursive: true, force: true });
80
86
  await rm(join(skillsDirectory(), name), { recursive: true, force: true });
81
87
  }
82
88
  if (accepted)
83
- await install();
89
+ await install(origin);
84
90
  else
85
91
  await rm(join(kitHome(), RECORD), { force: true });
86
92
  }
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
- }
131
- export async function createHowWeWork(bridge) {
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')
139
- return;
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')
144
- return;
145
- }
146
- await writeHome(WRITTEN, current);
147
- }
@@ -0,0 +1,163 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { oneFolder } from './home.js';
8
+ const SERVICE = 'house-kit';
9
+ const UNIT = `${SERVICE}.service`;
10
+ // launchctl, loginctl and systemctl answer at once and lingering starts the account's service manager within a second, so ten seconds only bound a stuck one.
11
+ const MANAGER_MS = 10_000;
12
+ // The service manager lingering starts answers within a second, so a check every tenth of a second starts Kit as soon as it does.
13
+ const MANAGER_CHECK_MS = 100;
14
+ // A Kit that failed restarts after five seconds, back soon without spinning on a failure that repeats; a Kit that ended itself stays stopped.
15
+ const RESTART_SECONDS = 5;
16
+ export function userUnit() {
17
+ return join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'systemd', 'user', UNIT);
18
+ }
19
+ export function launchAgent() {
20
+ return join(homedir(), 'Library', 'LaunchAgents', `${SERVICE}.plist`);
21
+ }
22
+ export function launcher() {
23
+ return join(oneFolder(), 'bin', 'kit');
24
+ }
25
+ export function systemd() {
26
+ return existsSync('/run/systemd/system');
27
+ }
28
+ function userBus() {
29
+ if (process.env.XDG_RUNTIME_DIR)
30
+ return process.env;
31
+ return { ...process.env, XDG_RUNTIME_DIR: `/run/user/${process.getuid()}` };
32
+ }
33
+ export function manage(command, args) {
34
+ return spawnSync(command, args, { encoding: 'utf8', timeout: MANAGER_MS, env: command === 'systemctl' ? userBus() : process.env });
35
+ }
36
+ export function required(command, args, failed) {
37
+ const ran = manage(command, args);
38
+ if (ran.status === 0)
39
+ return;
40
+ const cause = ran.error?.message ?? (ran.stderr.trim() || `${command} exited with ${ran.status ?? 'a signal'}`);
41
+ throw new Error(`${failed}: ${cause}`);
42
+ }
43
+ function unitWord(text) {
44
+ return `"${text.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%')}"`;
45
+ }
46
+ function xmlText(text) {
47
+ return text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
48
+ }
49
+ function unitText() {
50
+ return `[Unit]
51
+ Description=Kit
52
+
53
+ [Service]
54
+ ExecStart=${unitWord(launcher())} resident
55
+ Restart=on-failure
56
+ RestartSec=${RESTART_SECONDS}
57
+ Delegate=yes
58
+ OOMPolicy=continue
59
+
60
+ [Install]
61
+ WantedBy=default.target
62
+ `;
63
+ }
64
+ function plistText() {
65
+ return `<?xml version="1.0" encoding="UTF-8"?>
66
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
67
+ <plist version="1.0">
68
+ <dict>
69
+ \t<key>Label</key>
70
+ \t<string>${SERVICE}</string>
71
+ \t<key>ProgramArguments</key>
72
+ \t<array>
73
+ \t\t<string>${xmlText(launcher())}</string>
74
+ \t\t<string>resident</string>
75
+ \t</array>
76
+ \t<key>RunAtLoad</key>
77
+ \t<true/>
78
+ \t<key>KeepAlive</key>
79
+ \t<dict>
80
+ \t\t<key>SuccessfulExit</key>
81
+ \t\t<false/>
82
+ \t</dict>
83
+ \t<key>ProcessType</key>
84
+ \t<string>Interactive</string>
85
+ \t<key>StandardErrorPath</key>
86
+ \t<string>${xmlText(join(oneFolder(), 'kit.log'))}</string>
87
+ </dict>
88
+ </plist>
89
+ `;
90
+ }
91
+ async function define(path, text) {
92
+ if ((await readFile(path, 'utf8').catch(() => null)) === text)
93
+ return false;
94
+ await mkdir(dirname(path), { recursive: true });
95
+ await writeFile(`${path}.new`, text);
96
+ await rename(`${path}.new`, path);
97
+ return true;
98
+ }
99
+ export function defineSupervisor() {
100
+ return process.platform === 'darwin' ? define(launchAgent(), plistText()) : define(userUnit(), unitText());
101
+ }
102
+ export async function linger() {
103
+ required('loginctl', ['enable-linger', String(process.getuid())], 'lingering could not be turned on for this account');
104
+ if (process.getuid() === 0)
105
+ required('systemctl', ['start', 'user@0.service'], "root's service manager could not be started");
106
+ const stuck = Date.now() + MANAGER_MS;
107
+ while (manage('systemctl', ['--user', 'show-environment']).status !== 0) {
108
+ if (Date.now() >= stuck) {
109
+ throw new Error(`this account's service manager did not start within ${MANAGER_MS / 1000} seconds; restart this computer, then run this command again`);
110
+ }
111
+ await delay(MANAGER_CHECK_MS);
112
+ }
113
+ }
114
+ function macos() {
115
+ const target = `gui/${process.getuid()}`;
116
+ return { target, service: `${target}/${SERVICE}` };
117
+ }
118
+ export async function supervise(changed, restart) {
119
+ if (process.platform === 'darwin') {
120
+ const { target, service } = macos();
121
+ const printed = manage('launchctl', ['print', service]);
122
+ const loaded = printed.status === 0;
123
+ if (loaded && changed)
124
+ required('launchctl', ['bootout', service], 'the Kit service could not be stopped');
125
+ if (!loaded || changed) {
126
+ manage('launchctl', ['enable', service]);
127
+ required('launchctl', ['bootstrap', target, launchAgent()], 'the Kit service could not be started');
128
+ }
129
+ else if (restart) {
130
+ required('launchctl', ['kickstart', '-k', service], 'the Kit service could not be restarted');
131
+ }
132
+ else if (!/^\tstate = running$/m.test(printed.stdout)) {
133
+ required('launchctl', ['kickstart', service], 'the Kit service could not be started');
134
+ }
135
+ return;
136
+ }
137
+ await linger();
138
+ if (changed)
139
+ required('systemctl', ['--user', 'daemon-reload'], 'systemd could not read the Kit service');
140
+ required('systemctl', ['--user', '--quiet', 'enable', UNIT], 'the Kit service could not be enabled');
141
+ if (manage('systemctl', ['--user', '--quiet', 'is-active', UNIT]).status !== 0) {
142
+ required('systemctl', ['--user', 'start', UNIT], 'the Kit service could not be started');
143
+ }
144
+ else if (changed || restart) {
145
+ required('systemctl', ['--user', 'restart', UNIT], 'the Kit service could not be restarted');
146
+ }
147
+ }
148
+ export function startService() {
149
+ if (process.platform === 'darwin') {
150
+ const { service } = macos();
151
+ const printed = manage('launchctl', ['print', service]);
152
+ if (printed.status !== 0 || /^\tstate = running$/m.test(printed.stdout))
153
+ return false;
154
+ required('launchctl', ['kickstart', service], 'the Kit service could not be started');
155
+ return true;
156
+ }
157
+ if (manage('systemctl', ['--user', '--quiet', 'is-enabled', UNIT]).status !== 0)
158
+ return false;
159
+ if (manage('systemctl', ['--user', '--quiet', 'is-active', UNIT]).status === 0)
160
+ return false;
161
+ required('systemctl', ['--user', 'start', UNIT], 'the Kit service could not be started');
162
+ return true;
163
+ }