@agentshouse/kit 0.2.1-cbabe8ad337ff → 0.2.1-cc719fffeec71

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 (96) hide show
  1. package/README.md +30 -29
  2. package/dist/acp.js +34 -14
  3. package/dist/agents.js +109 -22
  4. package/dist/api.js +6 -2
  5. package/dist/app-git.js +10 -26
  6. package/dist/bootstrap.json +4 -4
  7. package/dist/bridge.js +10 -24
  8. package/dist/chatgpt.js +32 -0
  9. package/dist/clis.js +51 -9
  10. package/dist/conversations.js +140 -70
  11. package/dist/copies.js +195 -119
  12. package/dist/end.js +18 -3
  13. package/dist/enrol-main.js +7 -1
  14. package/dist/events.js +4 -0
  15. package/dist/files.js +8 -2
  16. package/dist/git.js +10 -8
  17. package/dist/home.js +96 -7
  18. package/dist/house-cli.js +291 -0
  19. package/dist/house-main.js +7 -177
  20. package/dist/inputs.js +37 -0
  21. package/dist/instructions.js +10 -32
  22. package/dist/kit-cli.js +68 -0
  23. package/dist/kit-main.js +8 -22
  24. package/dist/login.js +112 -22
  25. package/dist/logout.js +0 -2
  26. package/dist/parts.js +34 -16
  27. package/dist/placement.js +30 -0
  28. package/dist/relay.js +12 -2
  29. package/dist/resident.js +82 -26
  30. package/dist/service-main.js +9 -0
  31. package/dist/service.js +55 -0
  32. package/dist/sign-in.js +5 -23
  33. package/dist/skills.js +81 -12
  34. package/dist/stream.js +68 -17
  35. package/dist/transcription.js +3 -3
  36. package/dist/update.js +48 -29
  37. package/dist/wire.js +6 -0
  38. package/dist/work.js +3 -5
  39. package/how-we-work.md +13 -3
  40. package/package.json +3 -2
  41. package/skills/ask-matt/SKILL.md +17 -11
  42. package/skills/ask-matt/agents/openai.yaml +1 -0
  43. package/skills/code-review/SKILL.md +5 -5
  44. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  45. package/skills/codebase-design/SKILL.md +0 -2
  46. package/skills/diagnosing-bugs/SKILL.md +2 -4
  47. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  48. package/skills/domain-modeling/SKILL.md +12 -14
  49. package/skills/grill-me/SKILL.md +1 -2
  50. package/skills/grill-me/agents/openai.yaml +1 -0
  51. package/skills/grill-with-docs/SKILL.md +1 -2
  52. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  53. package/skills/grilling/SKILL.md +2 -2
  54. package/skills/handoff/SKILL.md +2 -3
  55. package/skills/handoff/agents/openai.yaml +1 -0
  56. package/skills/implement/SKILL.md +5 -4
  57. package/skills/implement/agents/openai.yaml +1 -0
  58. package/skills/implement-spec/SKILL.md +40 -0
  59. package/skills/implement-spec/agents/openai.yaml +5 -0
  60. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  61. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  62. package/skills/pr/CREDITS.md +3 -0
  63. package/skills/pr/LICENSE +21 -0
  64. package/skills/pr/SKILL.md +170 -0
  65. package/skills/pr/agents/openai.yaml +3 -0
  66. package/skills/prototype/SKILL.md +0 -2
  67. package/skills/research/SKILL.md +0 -2
  68. package/skills/retro/LICENSE +21 -0
  69. package/skills/retro/SKILL.md +44 -0
  70. package/skills/retro/agents/openai.yaml +5 -0
  71. package/skills/tdd/SKILL.md +2 -4
  72. package/skills/teach/SKILL.md +3 -4
  73. package/skills/teach/agents/openai.yaml +1 -0
  74. package/skills/to-questionnaire/SKILL.md +1 -2
  75. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  76. package/skills/to-spec/SKILL.md +1 -2
  77. package/skills/to-spec/agents/openai.yaml +1 -0
  78. package/skills/to-tickets/SKILL.md +3 -4
  79. package/skills/to-tickets/agents/openai.yaml +1 -0
  80. package/skills/triage/AGENT-BRIEF.md +207 -0
  81. package/skills/triage/LICENSE +21 -0
  82. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  83. package/skills/triage/SKILL.md +112 -0
  84. package/skills/triage/agents/openai.yaml +5 -0
  85. package/skills/wait-what/SKILL.md +2 -3
  86. package/skills/wait-what/agents/openai.yaml +1 -0
  87. package/skills/wayfinder/SKILL.md +5 -6
  88. package/skills/wayfinder/agents/openai.yaml +1 -0
  89. package/skills/wizard/LICENSE +21 -0
  90. package/skills/wizard/SKILL.md +44 -0
  91. package/skills/wizard/agents/openai.yaml +3 -0
  92. package/skills/wizard/template.sh +223 -0
  93. package/skills/writing-for-agents/SKILL.md +0 -2
  94. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  95. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  96. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/dist/resident.js CHANGED
@@ -1,15 +1,18 @@
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';
4
+ import { createServer, get } from 'node:http';
5
5
  import { dirname, extname, join } from 'node:path';
6
+ import { DatabaseSync } from 'node:sqlite';
6
7
  import { fileURLToPath } from 'node:url';
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 { CONVERSATION_INPUTS, Conversations } from './conversations.js';
11
12
  import { LocalCopies } from './copies.js';
12
- 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 { Inputs } from './inputs.js';
13
16
  import { killDescendants } from './scope.js';
14
17
  import { quoted } from './shell.js';
15
18
  import { SignIns } from './sign-in.js';
@@ -28,26 +31,66 @@ async function installShim(path, module) {
28
31
  await mkdir(dirname(path), { recursive: true });
29
32
  await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
30
33
  }
34
+ function claimed(lock) {
35
+ try {
36
+ lock.exec('BEGIN EXCLUSIVE');
37
+ return true;
38
+ }
39
+ catch (error) {
40
+ if (error.errcode === 5)
41
+ return false;
42
+ throw error;
43
+ }
44
+ }
31
45
  async function serveOwner(copies) {
32
- const socketPath = join(kitHome(), 'owner.sock');
33
- await rm(socketPath, { force: true });
46
+ const lock = new DatabaseSync(ownerLock());
47
+ if (!claimed(lock)) {
48
+ lock.close();
49
+ const running = await runningResident();
50
+ throw new Error(`${running === null ? 'another Kit' : `Kit ${running}`} already runs this Environment from Kit home ${kitHome()}; stop it first to run another here`);
51
+ }
34
52
  const server = createServer(async (request, response) => {
35
53
  try {
36
- if (request.url !== '/git/push') {
54
+ const text = await received(request);
55
+ let answered;
56
+ if (request.url === '/resident') {
57
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ pid: process.pid }));
58
+ return;
59
+ }
60
+ if (request.url === '/git/fetch') {
61
+ answered = await copies.fetch();
62
+ }
63
+ else if (request.url === '/git/push') {
64
+ const { cwd, commit } = JSON.parse(text);
65
+ answered = await copies.push(cwd, commit, copies.owner);
66
+ }
67
+ else {
37
68
  response.writeHead(404).end();
38
69
  return;
39
70
  }
40
- const { cwd, commit } = JSON.parse(await received(request));
41
- const pushed = await copies.push(cwd, commit, copies.owner);
42
- response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(pushed));
71
+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answered));
43
72
  }
44
73
  catch (error) {
45
74
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
46
75
  }
47
76
  });
48
- server.listen(socketPath);
77
+ server.on('close', () => lock.close());
78
+ await rm(ownerSocket(), { force: true });
79
+ server.listen(ownerSocket());
49
80
  await once(server, 'listening');
50
81
  }
82
+ function runningResident() {
83
+ return new Promise((resolve, reject) => {
84
+ get({ socketPath: ownerSocket(), path: '/resident' }, (answer) => {
85
+ received(answer).then((text) => resolve(JSON.parse(text).pid), reject);
86
+ }).on('error', (error) => {
87
+ if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED')
88
+ resolve(null);
89
+ else
90
+ reject(error);
91
+ });
92
+ });
93
+ }
51
94
  function connected() {
52
95
  return new Promise((resolve) => {
53
96
  const watcher = watch(kitHome(), () => {
@@ -64,8 +107,9 @@ function connected() {
64
107
  resolve();
65
108
  });
66
109
  }
67
- export async function resident() {
110
+ async function started() {
68
111
  await connected();
112
+ await forgetRestart();
69
113
  watch(kitHome(), () => {
70
114
  if (enrolled())
71
115
  return;
@@ -74,34 +118,46 @@ export async function resident() {
74
118
  });
75
119
  await placeSkillSet();
76
120
  await mkdir(agentBase(), { recursive: true });
77
- process.env.HOUSE_KIT_RESIDENT = String(process.pid);
78
- const agents = new Agents(house);
79
- const copies = new LocalCopies(house);
80
- await copies.load();
81
121
  await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
82
122
  await installShim(codexLauncher(), 'codex-main');
123
+ }
124
+ export async function resident() {
125
+ await mkdir(kitHome(), { recursive: true, mode: 0o700 });
126
+ const copies = new LocalCopies(house);
127
+ await copies.load();
83
128
  await serveOwner(copies);
129
+ await started().catch((error) => {
130
+ report(error);
131
+ process.exit(1);
132
+ });
133
+ process.env.HOUSE_KIT_RESIDENT = String(process.pid);
134
+ const agents = new Agents(house, () => changed());
84
135
  let stream = null;
85
136
  let reported = false;
86
- const idle = () => conversations.idle() && signIns.idle();
137
+ const idle = () => inputs.idle() && conversations.idle() && agents.idle();
87
138
  const changed = () => {
88
139
  if (!idle()) {
89
140
  reported = false;
90
141
  }
142
+ else if (restartAsked() && conversations.quiet()) {
143
+ restart('restarting for an updated CLI');
144
+ }
91
145
  else if (!reported) {
92
146
  reported = true;
93
147
  logged(house.deliver('/kit/idle', {}, idle));
94
148
  }
95
149
  };
150
+ const inputs = new Inputs(house, changed);
96
151
  const conversations = new Conversations({
97
152
  house,
98
153
  agents,
99
154
  copies,
155
+ inputs,
100
156
  send: (frame) => stream?.send(frame) ?? false,
101
157
  changed,
102
158
  });
103
- const signIns = new SignIns(house, agents, changed);
104
- const updates = new Updates(house);
159
+ const signIns = new SignIns(house, agents, inputs);
160
+ const updates = new Updates(inputs);
105
161
  for (const signal of ['SIGTERM', 'SIGINT']) {
106
162
  process.once(signal, () => {
107
163
  killDescendants();
@@ -115,26 +171,26 @@ export async function resident() {
115
171
  opened: () => {
116
172
  conversations.opened();
117
173
  changed();
118
- logged(copies.select());
174
+ logged(copies.connected());
119
175
  },
120
176
  frame: (arrived) => {
121
177
  if (arrived.type === 'watching')
122
178
  conversations.watching(arrived.watching === true);
179
+ if (arrived.type === 'authority_changed')
180
+ logged(copies.changed(arrived.rooms));
123
181
  if (arrived.type === 'work_available' && arrived.subject === 'agents')
124
182
  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
183
  if (arrived.type === 'input') {
131
- reported = false;
132
184
  if (arrived.kind === 'sign_in')
133
185
  signIns.start(arrived);
134
186
  else if (arrived.kind === 'update')
135
187
  updates.start(arrived);
136
- else
188
+ else if (CONVERSATION_INPUTS.has(arrived.kind))
137
189
  conversations.input(arrived);
190
+ else {
191
+ const refused = { refused: `This Kit does not know ${arrived.kind}; update the Kit` };
192
+ void inputs.carry(String(arrived.input_id), async () => ({ ack: refused }));
193
+ }
138
194
  }
139
195
  },
140
196
  });
@@ -0,0 +1,9 @@
1
+ import { startService } from './service.js';
2
+ try {
3
+ if (startService())
4
+ process.stdout.write('started\n');
5
+ }
6
+ catch (error) {
7
+ process.stderr.write(`kit: ${error.message}\n`);
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,55 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, realpathSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { kitHome } from './home.js';
5
+ const UNIT = 'house-kit.service';
6
+ // launchctl and systemctl answer at once, so ten seconds only bounds a stuck service manager.
7
+ const MANAGER_MS = 10_000;
8
+ function manage(command, args) {
9
+ return spawnSync(command, args, { encoding: 'utf8', timeout: MANAGER_MS });
10
+ }
11
+ function start(command, args) {
12
+ const started = manage(command, args);
13
+ if (started.status === 0)
14
+ return;
15
+ const cause = started.error?.message ?? (started.stderr.trim() || `${command} exited with ${started.status ?? 'a signal'}`);
16
+ throw new Error(`the House Kit service could not be started: ${cause}`);
17
+ }
18
+ function physical(path) {
19
+ return existsSync(path) ? realpathSync(path) : resolve(path);
20
+ }
21
+ function systemdHome(environment) {
22
+ for (const [, quoted, bare] of environment.matchAll(/"((?:[^"\\]|\\.)*)"|(\S+)/g)) {
23
+ const assignment = bare ?? quoted.replace(/\\(.)/g, '$1');
24
+ if (assignment.startsWith('HOUSE_KIT_HOME='))
25
+ return assignment.slice('HOUSE_KIT_HOME='.length);
26
+ }
27
+ return undefined;
28
+ }
29
+ function runsThisHome(served) {
30
+ return served !== undefined && physical(served) === physical(kitHome());
31
+ }
32
+ export function startService() {
33
+ if (process.platform === 'darwin') {
34
+ const service = `gui/${process.getuid()}/house-kit`;
35
+ const printed = manage('launchctl', ['print', service]);
36
+ if (printed.status !== 0 || /^\tstate = running$/m.test(printed.stdout))
37
+ return false;
38
+ if (!runsThisHome(/^\t+HOUSE_KIT_HOME => (.+)$/m.exec(printed.stdout)?.[1]))
39
+ return false;
40
+ start('launchctl', ['kickstart', service]);
41
+ return true;
42
+ }
43
+ for (const scope of [['--user'], []]) {
44
+ if (manage('systemctl', [...scope, 'is-enabled', '--quiet', UNIT]).status !== 0)
45
+ continue;
46
+ const environment = manage('systemctl', [...scope, 'show', '--property=Environment', '--value', UNIT]).stdout;
47
+ if (!runsThisHome(systemdHome(environment)))
48
+ continue;
49
+ if (manage('systemctl', [...scope, 'is-active', '--quiet', UNIT]).status === 0)
50
+ return false;
51
+ start('systemctl', [...scope, 'start', UNIT]);
52
+ return true;
53
+ }
54
+ return false;
55
+ }
package/dist/sign-in.js CHANGED
@@ -9,36 +9,20 @@ 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 logged(error) {
13
- process.stderr.write(`kit: ${causeOf(error)}\n`);
14
- }
15
12
  function endOf(signal) {
16
13
  return new Promise((resolve) => signal.addEventListener('abort', () => resolve(true), { once: true }));
17
14
  }
18
15
  export class SignIns {
19
16
  house;
20
17
  agents;
21
- changed;
22
- running = new Set();
23
- constructor(house, agents, changed) {
18
+ inputs;
19
+ constructor(house, agents, inputs) {
24
20
  this.house = house;
25
21
  this.agents = agents;
26
- this.changed = changed;
27
- }
28
- idle() {
29
- return this.running.size === 0;
22
+ this.inputs = inputs;
30
23
  }
31
24
  start(input) {
32
- if (this.running.has(input.input_id))
33
- return;
34
- this.running.add(input.input_id);
35
- this.changed();
36
- this.signIn(input)
37
- .catch(logged)
38
- .finally(() => {
39
- this.running.delete(input.input_id);
40
- this.changed();
41
- });
25
+ void this.inputs.carry(input.input_id, () => this.signIn(input));
42
26
  }
43
27
  async signIn(input) {
44
28
  const ending = new AbortController();
@@ -48,9 +32,7 @@ export class SignIns {
48
32
  clearTimeout(timer);
49
33
  if (ended)
50
34
  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);
35
+ return ended ? { ack: {} } : { ack: {}, acknowledged: () => this.agents.reread(input.cli) };
54
36
  }
55
37
  async signedIn(input, signal) {
56
38
  await this.login(input, signal);
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
  }
package/dist/stream.js CHANGED
@@ -1,11 +1,42 @@
1
1
  import { subscribe } from 'node:diagnostics_channel';
2
- import { finalRefusal, HouseRefusal, retryDelay } from './api.js';
3
- import { end, REPLACED, SIGN_IN_AGAIN } from './end.js';
2
+ import { HouseRefusal, retryDelay } from './api.js';
3
+ import { end, REPLACED, signInAgain, updateRequired } from './end.js';
4
4
  import { readEnrolment } from './home.js';
5
5
  import { relayed } from './relay.js';
6
+ import { KIT_WIRE, tooOld } from './wire.js';
6
7
  const PATH = '/kit/stream';
7
- const SUBPROTOCOL = 'house.kit.stream.1';
8
+ const SUBPROTOCOL = `house.kit.stream.${KIT_WIRE}`;
8
9
  const REFUSAL_HEADER = 'x-house-refusal';
10
+ // House beats each stream every thirty seconds, so two silent beats mean this Kit cannot hear House.
11
+ export const STREAM_SILENCE_MS = 60_000;
12
+ const SYSTEM_STREAM_CLOCK = {
13
+ later: (delay, callback) => setTimeout(callback, delay),
14
+ clear: (timer) => clearTimeout(timer),
15
+ };
16
+ export class StreamSilence {
17
+ timer = null;
18
+ silent;
19
+ clock;
20
+ interval;
21
+ constructor(silent, clock = SYSTEM_STREAM_CLOCK, interval = STREAM_SILENCE_MS) {
22
+ this.silent = silent;
23
+ this.clock = clock;
24
+ this.interval = interval;
25
+ }
26
+ heard() {
27
+ this.stop();
28
+ this.timer = this.clock.later(this.interval, () => {
29
+ this.timer = null;
30
+ this.silent();
31
+ });
32
+ }
33
+ stop() {
34
+ if (this.timer === null)
35
+ return;
36
+ this.clock.clear(this.timer);
37
+ this.timer = null;
38
+ }
39
+ }
9
40
  function streamUrl(house) {
10
41
  const url = new URL(PATH, house);
11
42
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
@@ -36,29 +67,49 @@ export function holdStream(handlers) {
36
67
  headers: { authorization: `Bearer ${credential}` },
37
68
  });
38
69
  let opened = false;
70
+ let silence = null;
71
+ const closed = (event) => {
72
+ silence?.stop();
73
+ silence = null;
74
+ if (socket === opening)
75
+ socket = null;
76
+ process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
77
+ if (event.reason === 'replaced')
78
+ end(REPLACED);
79
+ if (event.reason === 'credential_rejected' || refused?.status === 401) {
80
+ void signInAgain(credential);
81
+ return;
82
+ }
83
+ if (refused !== null && tooOld(refused.text))
84
+ updateRequired();
85
+ if (!opened && refused !== null)
86
+ process.stderr.write(`kit: ${refused.message}\n`);
87
+ // A closed socket reopens in one to three seconds, spread so Kits one restart closed return apart; an opening House refused or left unanswered backs off on the jittered curve, retryable or not, since a resident outlives a House deploy.
88
+ setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
89
+ };
39
90
  opening.onopen = () => {
40
91
  opened = true;
41
92
  failures = 0;
42
93
  socket = opening;
94
+ silence = new StreamSilence(() => {
95
+ if (socket !== opening)
96
+ return;
97
+ socket = null;
98
+ opening.onclose = null;
99
+ opening.close();
100
+ closed(new CloseEvent('close', { code: 1006, reason: 'heartbeat_missed' }));
101
+ });
102
+ silence.heard();
43
103
  handlers.opened();
44
104
  };
45
105
  opening.onmessage = (event) => {
46
- handlers.frame(JSON.parse(String(event.data)));
106
+ silence?.heard();
107
+ const frame = JSON.parse(String(event.data));
108
+ if (frame.type !== 'beat')
109
+ handlers.frame(frame);
47
110
  };
48
111
  opening.onerror = () => undefined;
49
- opening.onclose = (event) => {
50
- if (socket === opening)
51
- socket = null;
52
- process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
53
- if (event.reason === 'replaced')
54
- end(REPLACED);
55
- if (event.reason === 'credential_rejected' || refused?.status === 401)
56
- end(SIGN_IN_AGAIN);
57
- if (finalRefusal(refused))
58
- end(refused.message);
59
- // A closed socket reopens in one to three seconds, spread so Kits one restart closed return apart; an opening House refused as retryable or left unanswered backs off on the jittered curve.
60
- setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
61
- };
112
+ opening.onclose = closed;
62
113
  };
63
114
  void connect();
64
115
  return {
@@ -49,10 +49,10 @@ async function executed(command, args, signal) {
49
49
  function present(path) {
50
50
  return stat(path).then(() => true, () => false);
51
51
  }
52
- async function cpus() {
52
+ async function threads() {
53
53
  const [quota, period] = (await readFile('/sys/fs/cgroup/cpu.max', 'utf8').catch(() => 'max')).split(' ');
54
54
  const allowed = quota === 'max' ? Infinity : Math.ceil(Number(quota) / Number(period));
55
- return Math.min(availableParallelism(), allowed);
55
+ return Math.max(1, Math.floor(Math.min(availableParallelism(), allowed) / 2));
56
56
  }
57
57
  async function sha256(path) {
58
58
  const hash = createHash('sha256');
@@ -140,7 +140,7 @@ async function transcribed(path, signal) {
140
140
  await executed(installed(pinned.decoder), ['-nostdin', '-hide_banner', '-loglevel', 'error', '-i', path, '-ar', '16000', '-ac', '1', '-c:a', 'pcm_s16le',
141
141
  '-f', 'segment', '-segment_time', String(CHUNK_SECONDS), join(work, '%05d.wav')], signal);
142
142
  const parts = (await readdir(work)).sort().flatMap((part) => ['-f', join(work, part)]);
143
- const text = await executed(installed(pinned.engine), ['-t', String(await cpus()), '-np', '-m', installed(MODEL), ...parts], signal);
143
+ const text = await executed(installed(pinned.engine), ['-t', String(await threads()), '-np', '-m', installed(MODEL), ...parts], signal);
144
144
  return text
145
145
  .split('\n')
146
146
  .map((line) => line.trim())