@agentshouse/kit 0.2.1-c5d36e97b0fea → 0.2.1-c5d51f1e4ce19

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 (89) hide show
  1. package/README.md +25 -24
  2. package/dist/agents.js +73 -7
  3. package/dist/api.js +6 -2
  4. package/dist/bootstrap.json +4 -4
  5. package/dist/chatgpt.js +32 -0
  6. package/dist/clis.js +42 -9
  7. package/dist/conversations.js +29 -9
  8. package/dist/copies.js +36 -26
  9. package/dist/end.js +17 -3
  10. package/dist/enrol-main.js +7 -1
  11. package/dist/events.js +3 -0
  12. package/dist/files.js +7 -1
  13. package/dist/git.js +11 -8
  14. package/dist/home.js +81 -6
  15. package/dist/house-cli.js +291 -0
  16. package/dist/house-main.js +7 -188
  17. package/dist/instructions.js +7 -31
  18. package/dist/kit-cli.js +68 -0
  19. package/dist/kit-main.js +8 -22
  20. package/dist/login.js +102 -21
  21. package/dist/parts.js +34 -16
  22. package/dist/placement.js +48 -0
  23. package/dist/relay.js +12 -2
  24. package/dist/resident.js +15 -6
  25. package/dist/service-main.js +9 -0
  26. package/dist/service.js +33 -0
  27. package/dist/skills.js +81 -12
  28. package/dist/stream.js +66 -15
  29. package/dist/transcription.js +3 -3
  30. package/dist/update.js +28 -6
  31. package/dist/wire.js +6 -0
  32. package/how-we-work.md +13 -3
  33. package/package.json +3 -2
  34. package/skills/ask-matt/SKILL.md +17 -11
  35. package/skills/ask-matt/agents/openai.yaml +1 -0
  36. package/skills/code-review/SKILL.md +5 -5
  37. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  38. package/skills/codebase-design/SKILL.md +0 -2
  39. package/skills/diagnosing-bugs/SKILL.md +2 -4
  40. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  41. package/skills/domain-modeling/SKILL.md +12 -14
  42. package/skills/grill-me/SKILL.md +1 -2
  43. package/skills/grill-me/agents/openai.yaml +1 -0
  44. package/skills/grill-with-docs/SKILL.md +1 -2
  45. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  46. package/skills/grilling/SKILL.md +2 -2
  47. package/skills/handoff/SKILL.md +2 -3
  48. package/skills/handoff/agents/openai.yaml +1 -0
  49. package/skills/implement/SKILL.md +5 -4
  50. package/skills/implement/agents/openai.yaml +1 -0
  51. package/skills/implement-spec/SKILL.md +40 -0
  52. package/skills/implement-spec/agents/openai.yaml +5 -0
  53. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  54. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  55. package/skills/pr/CREDITS.md +3 -0
  56. package/skills/pr/LICENSE +21 -0
  57. package/skills/pr/SKILL.md +170 -0
  58. package/skills/pr/agents/openai.yaml +3 -0
  59. package/skills/prototype/SKILL.md +0 -2
  60. package/skills/research/SKILL.md +0 -2
  61. package/skills/retro/LICENSE +21 -0
  62. package/skills/retro/SKILL.md +44 -0
  63. package/skills/retro/agents/openai.yaml +5 -0
  64. package/skills/tdd/SKILL.md +2 -4
  65. package/skills/teach/SKILL.md +3 -4
  66. package/skills/teach/agents/openai.yaml +1 -0
  67. package/skills/to-questionnaire/SKILL.md +1 -2
  68. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  69. package/skills/to-spec/SKILL.md +1 -2
  70. package/skills/to-spec/agents/openai.yaml +1 -0
  71. package/skills/to-tickets/SKILL.md +3 -4
  72. package/skills/to-tickets/agents/openai.yaml +1 -0
  73. package/skills/triage/AGENT-BRIEF.md +207 -0
  74. package/skills/triage/LICENSE +21 -0
  75. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  76. package/skills/triage/SKILL.md +112 -0
  77. package/skills/triage/agents/openai.yaml +5 -0
  78. package/skills/wait-what/SKILL.md +2 -3
  79. package/skills/wait-what/agents/openai.yaml +1 -0
  80. package/skills/wayfinder/SKILL.md +5 -6
  81. package/skills/wayfinder/agents/openai.yaml +1 -0
  82. package/skills/wizard/LICENSE +21 -0
  83. package/skills/wizard/SKILL.md +44 -0
  84. package/skills/wizard/agents/openai.yaml +3 -0
  85. package/skills/wizard/template.sh +223 -0
  86. package/skills/writing-for-agents/SKILL.md +0 -2
  87. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  88. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  89. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/dist/login.js CHANGED
@@ -2,11 +2,16 @@ import { spawn } from 'node:child_process';
2
2
  import { createHash, randomBytes } from 'node:crypto';
3
3
  import { hostname } from 'node:os';
4
4
  import { parseArgs } from 'node:util';
5
- import { post, retrying } from './api.js';
5
+ import { HouseRefusal, post, retrying } from './api.js';
6
6
  import { placeAppGit } from './app-git.js';
7
- import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
7
+ import { writeCodexRule } from './clis.js';
8
+ import { forgetDisconnected, forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent, } from './home.js';
8
9
  import { callHouse, rpc } from './mcp.js';
9
- const DEFAULT_HOUSE = 'https://agents.house';
10
+ import { refusalOf } from './refusals.js';
11
+ import { selectRelay } from './relay.js';
12
+ import { startService } from './service.js';
13
+ import { placeSkillSet } from './skills.js';
14
+ export const DEFAULT_HOUSE = 'https://agents.house';
10
15
  const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
11
16
  // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
12
17
  const POLL_INTERVAL_MS = 2000;
@@ -15,7 +20,7 @@ function open(link) {
15
20
  .on('error', () => undefined)
16
21
  .unref();
17
22
  }
18
- async function accepted(house, credential) {
23
+ export async function accepted(house, credential) {
19
24
  const checked = await callHouse(house, credential, rpc('tools/list', {}));
20
25
  if (checked.status === 200)
21
26
  return true;
@@ -23,39 +28,115 @@ async function accepted(house, credential) {
23
28
  return false;
24
29
  throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
25
30
  }
31
+ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private]
32
+ kit login [--house <origin>] --code <code>
33
+ --house <origin> the House to connect to, ${DEFAULT_HOUSE} unless one is stored
34
+ --environment <id> reconnect this Environment
35
+ --rooms <ref>[,<ref>...] give this Environment only these Rooms
36
+ --no-private give this Environment every Room but your Private Room
37
+ --code <code> connect this machine with a login code
38
+ `;
39
+ function gone(error) {
40
+ return error instanceof HouseRefusal && refusalOf(error.text)?.code === 'kit_environment_not_found';
41
+ }
42
+ function chosenRooms(rooms, noPrivate) {
43
+ if (rooms !== undefined && noPrivate)
44
+ throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
45
+ if (rooms !== undefined)
46
+ return { rooms: { reach: 'selected', refs: rooms.split(',') } };
47
+ return noPrivate ? { rooms: { reach: 'all_but_private' } } : {};
48
+ }
26
49
  export async function login(argv) {
27
50
  const { values } = parseArgs({
28
51
  args: argv,
29
52
  options: {
30
53
  house: { type: 'string' },
31
54
  environment: { type: 'string' },
55
+ rooms: { type: 'string' },
56
+ 'no-private': { type: 'boolean', default: false },
57
+ code: { type: 'string' },
58
+ help: { type: 'boolean', default: false },
32
59
  },
33
60
  });
61
+ if (values.help) {
62
+ process.stdout.write(USAGE);
63
+ return;
64
+ }
65
+ if (values.code !== undefined && values.rooms !== undefined)
66
+ throw new Error('--code cannot be used with --rooms');
67
+ if (values.code !== undefined && values['no-private'])
68
+ throw new Error('--code cannot be used with --no-private');
69
+ if (values.code !== undefined && values.environment !== undefined)
70
+ throw new Error('--code cannot be used with --environment');
71
+ const rooms = chosenRooms(values.rooms, values['no-private']);
34
72
  const enrolled = (await readEnrolment()) ?? (await readDisconnected());
73
+ if (values.code !== undefined && enrolled !== null) {
74
+ throw new Error(`--code connects a new machine; this Kit home records Environment ${enrolled.environment}, so run kit login to reconnect it`);
75
+ }
76
+ const relay = process.env.HOUSE_KIT_RELAY || undefined;
77
+ selectRelay(relay);
35
78
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
36
79
  const replaces = process.env.HOUSE_KIT_REPLACES;
37
- const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
80
+ const remembered = replaces === undefined && values.environment === undefined && enrolled?.house === house ? enrolled.environment : undefined;
81
+ const environment = replaces === undefined ? (values.environment ?? remembered) : undefined;
38
82
  const ownAgent = await readOwnAgent();
39
- const held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
40
- const verifier = randomBytes(32).toString('base64url');
41
- const started = await retrying(() => post(house, '/kit', {
42
- ...(environment === undefined
43
- ? { act: 'new_environment', label: hostname(), ...(replaces === undefined ? {} : { replaces }) }
44
- : { act: 'existing_environment', environment_id: environment }),
45
- code_challenge: createHash('sha256').update(verifier).digest('base64url'),
46
- ...(held ? {} : { headless: true }),
47
- }));
48
- process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
49
- open(started.start_url);
50
- const exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
51
- await writeEnrolment({ house, environment: exchanged.environment, credential: exchanged.credential });
83
+ let held = false;
84
+ let exchanged;
85
+ if (values.code !== undefined) {
86
+ exchanged = await post(house, '/kit/token', { code: values.code, label: hostname() });
87
+ }
88
+ else {
89
+ held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
90
+ const verifier = randomBytes(32).toString('base64url');
91
+ const start = (named) => retrying(() => post(house, '/kit', {
92
+ label: hostname(),
93
+ ...(named === undefined
94
+ ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
95
+ : { act: 'existing_environment', environment_id: named }),
96
+ ...rooms,
97
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
98
+ ...(held ? {} : { headless: true }),
99
+ }));
100
+ let started;
101
+ try {
102
+ started = await start(environment);
103
+ }
104
+ catch (error) {
105
+ if (remembered === undefined || !gone(error))
106
+ throw error;
107
+ await forgetDisconnected();
108
+ process.stdout.write(`House no longer holds Environment ${remembered}; connecting this computer as a new one.\n`);
109
+ started = await start(undefined);
110
+ }
111
+ process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
112
+ open(started.start_url);
113
+ exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
114
+ }
115
+ await placeSkillSet();
116
+ await writeCodexRule().catch((error) => process.stderr.write(`kit: ${error.message}\n`));
117
+ const relayRecord = relay === undefined ? {} : { relay };
118
+ await writeEnrolment({
119
+ house,
120
+ ...relayRecord,
121
+ environment: exchanged.environment,
122
+ credential: exchanged.credential,
123
+ });
52
124
  process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
53
125
  if (exchanged.headless_credential !== undefined) {
54
- await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
126
+ await writeOwnAgent({ house, ...relayRecord, user: exchanged.user, credential: exchanged.headless_credential });
55
127
  }
56
- else if (held && ownAgent.user !== exchanged.user) {
128
+ else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
57
129
  await forgetOwnAgent();
58
130
  process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
59
131
  }
60
- await placeAppGit(ownAgent, await readOwnAgent());
132
+ else if (held && ownAgent !== null) {
133
+ await writeOwnAgent({ house, ...relayRecord, user: ownAgent.user, credential: ownAgent.credential });
134
+ }
135
+ await placeAppGit(ownAgent, await readOwnAgent()).catch((error) => process.stderr.write(`kit: ${error.message}\n`));
136
+ try {
137
+ startService();
138
+ }
139
+ catch (error) {
140
+ process.stderr.write(`kit: ${error.message}\n`);
141
+ }
61
142
  }
package/dist/parts.js CHANGED
@@ -2,7 +2,10 @@ export class Parts {
2
2
  parts = [];
3
3
  context = null;
4
4
  emit;
5
+ made = [];
6
+ events = 0;
5
7
  writing = null;
8
+ counting = null;
6
9
  planned = null;
7
10
  constructor(emit) {
8
11
  this.emit = emit;
@@ -10,32 +13,34 @@ export class Parts {
10
13
  write(type, id, text) {
11
14
  if (text === '')
12
15
  return;
13
- const last = this.parts.length - 1;
14
- const part = this.parts[last];
15
- if (this.writing?.type === type && this.writing.id === id && part?.type === type) {
16
- part.text += text;
17
- this.emit({ op: 'append', index: last, text });
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 });
18
19
  return;
19
20
  }
20
- this.start({ type, text });
21
- this.writing = { type, id };
21
+ this.writing = { type, id, index: this.start({ type, text }) };
22
22
  }
23
23
  command() {
24
- const last = this.parts.length - 1;
25
- const part = this.parts[last];
26
- if (part?.type !== 'commands') {
27
- this.start({ type: 'commands', count: 1 });
24
+ if (this.counting === null) {
25
+ this.counting = this.start({ type: 'commands', count: 1 });
28
26
  return;
29
27
  }
28
+ const part = this.parts[this.counting];
30
29
  part.count++;
31
- this.emit({ op: 'count', index: last, count: part.count });
30
+ this.emit({ op: 'count', index: this.counting, count: part.count });
32
31
  }
33
32
  start(part) {
34
33
  this.writing = null;
35
- this.parts.push(part);
36
- const index = this.parts.length - 1;
37
- this.emit({ op: 'start', index, part });
38
- return index;
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);
39
44
  }
40
45
  done(index, result) {
41
46
  const part = this.parts[index];
@@ -55,10 +60,23 @@ export class Parts {
55
60
  this.context = context;
56
61
  this.emit({ op: 'context', ...context });
57
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
+ }
58
69
  operations() {
59
70
  return [
60
71
  ...this.parts.map((part, index) => ({ op: 'start', index, part })),
61
72
  ...(this.context === null ? [] : [{ op: 'context', ...this.context }]),
62
73
  ];
63
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
+ }
64
82
  }
@@ -0,0 +1,48 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { run } from './clis.js';
4
+ import { kitHome } from './home.js';
5
+ import { relayOrigin } from './relay.js';
6
+ export function service() {
7
+ if (process.platform !== 'linux' || !process.env.INVOCATION_ID)
8
+ return null;
9
+ return process.env.MANAGERPID ? 'user' : 'system';
10
+ }
11
+ export function throughSudo() {
12
+ return service() === 'system' && process.getuid() !== 0;
13
+ }
14
+ export async function updatesItself() {
15
+ if (service() === null)
16
+ return false;
17
+ if (!throughSudo())
18
+ return true;
19
+ // sudo answers at once, so ten seconds only bounds a stuck sudo.
20
+ return (await run('sudo', ['-n', 'true'], 10_000)).status === 0;
21
+ }
22
+ function installed() {
23
+ try {
24
+ return readFileSync(join(kitHome(), 'placement'), 'utf8').trim();
25
+ }
26
+ catch (error) {
27
+ if (error.code === 'ENOENT')
28
+ return null;
29
+ throw error;
30
+ }
31
+ }
32
+ function entries(house) {
33
+ const host = new URL(house).host;
34
+ const relay = relayOrigin();
35
+ if (relay === undefined)
36
+ return [`curl -fsSL ${host}/kit | sh`, `irm ${host}/kit.ps1 | iex`];
37
+ const entry = `${relay}/${host}/kit`;
38
+ return [`curl -fsSL ${entry} | HOUSE_KIT_RELAY=${relay} sh`, `$env:HOUSE_KIT_RELAY='${relay}'; irm ${entry}.ps1 | iex`];
39
+ }
40
+ export function installCommand(house) {
41
+ const [shell, windows] = entries(house);
42
+ const placement = installed();
43
+ if (placement === 'native')
44
+ return shell;
45
+ if (placement === 'server')
46
+ return `${shell} -s -- --linux`;
47
+ return `${shell} -s -- --container, or ${windows} on Windows`;
48
+ }
package/dist/relay.js CHANGED
@@ -1,7 +1,17 @@
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
+ }
1
11
  export function relayed(target) {
2
12
  const url = new URL(target);
3
- const relay = process.env.HOUSE_KIT_RELAY;
4
- if (relay === undefined || relay === '')
13
+ const relay = relayOrigin();
14
+ if (relay === undefined)
5
15
  return url;
6
16
  const through = new URL(`${url.host}${url.pathname}${url.search}`, `${relay}/`);
7
17
  if (url.protocol === 'wss:' || url.protocol === 'ws:')
package/dist/resident.js CHANGED
@@ -7,9 +7,10 @@ import { fileURLToPath } from 'node:url';
7
7
  import { Agents } from './agents.js';
8
8
  import { house } from './api.js';
9
9
  import { received } from './bridge.js';
10
- import { Conversations } from './conversations.js';
10
+ import { CONVERSATION_INPUTS, Conversations } from './conversations.js';
11
11
  import { LocalCopies } from './copies.js';
12
- import { agentBase, enrolled, kitHome } from './home.js';
12
+ import { restart } from './end.js';
13
+ import { agentBase, enrolled, forgetRestart, kitHome, restartAsked } from './home.js';
13
14
  import { killDescendants } from './scope.js';
14
15
  import { quoted } from './shell.js';
15
16
  import { SignIns } from './sign-in.js';
@@ -73,6 +74,7 @@ function connected() {
73
74
  }
74
75
  export async function resident() {
75
76
  await connected();
77
+ await forgetRestart();
76
78
  watch(kitHome(), () => {
77
79
  if (enrolled())
78
80
  return;
@@ -82,7 +84,7 @@ export async function resident() {
82
84
  await placeSkillSet();
83
85
  await mkdir(agentBase(), { recursive: true });
84
86
  process.env.HOUSE_KIT_RESIDENT = String(process.pid);
85
- const agents = new Agents(house);
87
+ const agents = new Agents(house, () => changed());
86
88
  const copies = new LocalCopies(house);
87
89
  await copies.load();
88
90
  await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
@@ -90,11 +92,14 @@ export async function resident() {
90
92
  await serveOwner(copies);
91
93
  let stream = null;
92
94
  let reported = false;
93
- const idle = () => conversations.idle() && signIns.idle();
95
+ const idle = () => conversations.idle() && signIns.idle() && agents.idle();
94
96
  const changed = () => {
95
97
  if (!idle()) {
96
98
  reported = false;
97
99
  }
100
+ else if (restartAsked() && conversations.quiet()) {
101
+ restart('restarting for an updated CLI');
102
+ }
98
103
  else if (!reported) {
99
104
  reported = true;
100
105
  logged(house.deliver('/kit/idle', {}, idle));
@@ -122,7 +127,7 @@ export async function resident() {
122
127
  opened: () => {
123
128
  conversations.opened();
124
129
  changed();
125
- logged(copies.select());
130
+ logged(copies.connected());
126
131
  },
127
132
  frame: (arrived) => {
128
133
  if (arrived.type === 'watching')
@@ -135,8 +140,12 @@ export async function resident() {
135
140
  signIns.start(arrived);
136
141
  else if (arrived.kind === 'update')
137
142
  updates.start(arrived);
138
- else
143
+ else if (CONVERSATION_INPUTS.has(arrived.kind))
139
144
  conversations.input(arrived);
145
+ else {
146
+ const refused = { refused: `This Kit does not know ${arrived.kind}; update the Kit` };
147
+ logged(house.deliver(`/kit/inputs/${arrived.input_id}/ack`, refused).finally(changed));
148
+ }
140
149
  }
141
150
  },
142
151
  });
@@ -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/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
2
  import { finalRefusal, HouseRefusal, retryDelay } from './api.js';
3
- import { end, REPLACED, SIGN_IN_AGAIN } from './end.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;
39
- opening.onopen = () => {
40
- opened = true;
41
- failures = 0;
42
- socket = opening;
43
- handlers.opened();
44
- };
45
- opening.onmessage = (event) => {
46
- handlers.frame(JSON.parse(String(event.data)));
47
- };
48
- opening.onerror = () => undefined;
49
- opening.onclose = (event) => {
70
+ let silence = null;
71
+ const closed = (event) => {
72
+ silence?.stop();
73
+ silence = null;
50
74
  if (socket === opening)
51
75
  socket = null;
52
76
  process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
53
77
  if (event.reason === 'replaced')
54
78
  end(REPLACED);
55
- if (event.reason === 'credential_rejected' || refused?.status === 401)
56
- end(SIGN_IN_AGAIN);
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(house);
57
85
  if (finalRefusal(refused))
58
86
  end(refused.message);
59
87
  // 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
88
  setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
61
89
  };
90
+ opening.onopen = () => {
91
+ opened = true;
92
+ failures = 0;
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();
103
+ handlers.opened();
104
+ };
105
+ opening.onmessage = (event) => {
106
+ silence?.heard();
107
+ const frame = JSON.parse(String(event.data));
108
+ if (frame.type !== 'beat')
109
+ handlers.frame(frame);
110
+ };
111
+ opening.onerror = () => undefined;
112
+ opening.onclose = closed;
62
113
  };
63
114
  void connect();
64
115
  return {