@agentshouse/kit 0.2.1-c8179f06883b6 → 0.2.1-c845e172df1af

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 (97) hide show
  1. package/README.md +30 -29
  2. package/dist/acp.js +36 -16
  3. package/dist/agents.js +106 -23
  4. package/dist/api.js +5 -5
  5. package/dist/app-git.js +10 -26
  6. package/dist/bootstrap.json +4 -4
  7. package/dist/bridge.js +3 -6
  8. package/dist/calls.js +63 -0
  9. package/dist/chatgpt.js +32 -0
  10. package/dist/clis.js +14 -4
  11. package/dist/connection.js +125 -0
  12. package/dist/conversations.js +323 -127
  13. package/dist/copies.js +89 -52
  14. package/dist/end.js +9 -4
  15. package/dist/events.js +6 -2
  16. package/dist/files.js +117 -22
  17. package/dist/git.js +11 -9
  18. package/dist/home.js +56 -5
  19. package/dist/house-cli.js +327 -0
  20. package/dist/house-main.js +7 -228
  21. package/dist/instructions.js +4 -28
  22. package/dist/kit-cli.js +68 -0
  23. package/dist/kit-main.js +8 -67
  24. package/dist/login.js +40 -16
  25. package/dist/logout.js +0 -2
  26. package/dist/mcp.js +4 -2
  27. package/dist/placement.js +9 -18
  28. package/dist/resident.js +82 -37
  29. package/dist/scope.js +3 -0
  30. package/dist/service.js +23 -1
  31. package/dist/sign-in.js +19 -37
  32. package/dist/skills.js +84 -15
  33. package/dist/transcription.js +3 -3
  34. package/dist/translate.js +2 -8
  35. package/dist/update.js +43 -45
  36. package/dist/wire.js +19 -3
  37. package/dist/work.js +3 -5
  38. package/how-we-work.md +13 -3
  39. package/package.json +4 -3
  40. package/skills/ask-matt/SKILL.md +17 -11
  41. package/skills/ask-matt/agents/openai.yaml +1 -0
  42. package/skills/code-review/SKILL.md +5 -5
  43. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  44. package/skills/codebase-design/SKILL.md +0 -2
  45. package/skills/diagnosing-bugs/SKILL.md +2 -4
  46. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  47. package/skills/domain-modeling/SKILL.md +12 -14
  48. package/skills/grill-me/SKILL.md +1 -2
  49. package/skills/grill-me/agents/openai.yaml +1 -0
  50. package/skills/grill-with-docs/SKILL.md +1 -2
  51. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  52. package/skills/grilling/SKILL.md +2 -2
  53. package/skills/handoff/SKILL.md +2 -3
  54. package/skills/handoff/agents/openai.yaml +1 -0
  55. package/skills/implement/SKILL.md +5 -4
  56. package/skills/implement/agents/openai.yaml +1 -0
  57. package/skills/implement-spec/SKILL.md +40 -0
  58. package/skills/implement-spec/agents/openai.yaml +5 -0
  59. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  60. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  61. package/skills/pr/CREDITS.md +3 -0
  62. package/skills/pr/LICENSE +21 -0
  63. package/skills/pr/SKILL.md +170 -0
  64. package/skills/pr/agents/openai.yaml +3 -0
  65. package/skills/prototype/SKILL.md +0 -2
  66. package/skills/research/SKILL.md +0 -2
  67. package/skills/retro/LICENSE +21 -0
  68. package/skills/retro/SKILL.md +44 -0
  69. package/skills/retro/agents/openai.yaml +5 -0
  70. package/skills/tdd/SKILL.md +2 -4
  71. package/skills/teach/SKILL.md +3 -4
  72. package/skills/teach/agents/openai.yaml +1 -0
  73. package/skills/to-questionnaire/SKILL.md +1 -2
  74. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  75. package/skills/to-spec/SKILL.md +1 -2
  76. package/skills/to-spec/agents/openai.yaml +1 -0
  77. package/skills/to-tickets/SKILL.md +3 -4
  78. package/skills/to-tickets/agents/openai.yaml +1 -0
  79. package/skills/triage/AGENT-BRIEF.md +207 -0
  80. package/skills/triage/LICENSE +21 -0
  81. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  82. package/skills/triage/SKILL.md +112 -0
  83. package/skills/triage/agents/openai.yaml +5 -0
  84. package/skills/wait-what/SKILL.md +2 -3
  85. package/skills/wait-what/agents/openai.yaml +1 -0
  86. package/skills/wayfinder/SKILL.md +5 -6
  87. package/skills/wayfinder/agents/openai.yaml +1 -0
  88. package/skills/wizard/LICENSE +21 -0
  89. package/skills/wizard/SKILL.md +44 -0
  90. package/skills/wizard/agents/openai.yaml +3 -0
  91. package/skills/wizard/template.sh +223 -0
  92. package/skills/writing-for-agents/SKILL.md +0 -2
  93. package/dist/codex.js +0 -61
  94. package/dist/stream.js +0 -77
  95. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  96. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  97. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
@@ -1,36 +1,12 @@
1
1
  import { HOUSE_REF } from './git.js';
2
- import { HOW_WE_WORK } from './skills.js';
2
+ import { readHowWeWork } from './skills.js';
3
3
  const SOURCE_LINE = "From House:";
4
4
  const HOUSE_LINE = "Work with House through the `house` CLI: run `house --help`, and `house find_command` for House's guides and formats.";
5
5
  const FILE_LINE = 'To give the User a file, upload it with `house upload` and link it; for an App, a Site or a website, follow `house find_command \'{"query":"app"}\'`. Never start a server.';
6
6
  const READ_LINE = "Optional per-Room instructions: `/rooms/private/rooms/<handle>/AGENTS.md`.";
7
+ const REQUEST_LINE = "For another Agent's help, `send_routine_request`; its mail comes back into this conversation. If an Agent of your User has no Routine to call, write one in the Private Room and `create_routine_access` with your User as its only caller.";
7
8
  const COPIES_LINE = `House Local copies; before work run \`house fetch\` and rebase onto \`${HOUSE_REF}\`; after it commit, then \`house push\`:`;
8
- const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
9
- const FAILED = /^exit: [1-9]\d*$/;
10
- const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
11
- function cutOf(lines) {
12
- const cut = CUT.exec(lines[0] ?? '');
13
- return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
14
- }
15
- async function howWeWork(bridge) {
16
- let document = '';
17
- for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
18
- const read = await bridge.tool('shell', { command });
19
- const text = read.content.map((content) => content.text).join('\n');
20
- const lines = text.split('\n');
21
- if (read.isError === true || (FAILED.test(lines[0] ?? '') && lines[1]?.startsWith('stderr: '))) {
22
- const refusal = read.isError === true ? text : lines.slice(1).join('\n').replace(/^stderr: /gm, '');
23
- if (UNREADABLE.test(refusal))
24
- return '';
25
- throw new Error(refusal);
26
- }
27
- const cut = cutOf(lines);
28
- document += lines.slice(cut === null ? 0 : 1).join('\n');
29
- command = cut?.[2];
30
- }
31
- return document.replace(/\n$/, '');
32
- }
33
9
  export async function instructions(bridge, base, copies) {
34
- const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
35
- return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
10
+ const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, REQUEST_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
11
+ return [lines.join('\n'), base, (await readHowWeWork(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
36
12
  }
@@ -0,0 +1,68 @@
1
+ import { setGlobalProxyFromEnv } from 'node:http';
2
+ import { parseArgs } from 'node:util';
3
+ import { answerGitCredential } from './app-git.js';
4
+ import { chatgpt } from './chatgpt.js';
5
+ import { login } from './login.js';
6
+ import { logout } from './logout.js';
7
+ import { resident } from './resident.js';
8
+ const USAGE = 'usage: kit <login|logout|resident|chatgpt>\n';
9
+ const COMMANDS = new Map([
10
+ [
11
+ 'logout',
12
+ {
13
+ usage: 'usage: kit logout',
14
+ about: "disconnects this computer, stops the Kit process and ends your own agent's connection",
15
+ operands: 0,
16
+ run: logout,
17
+ },
18
+ ],
19
+ [
20
+ 'resident',
21
+ {
22
+ usage: 'usage: kit resident',
23
+ about: "keeps this Environment connected; Kit's service runs it",
24
+ operands: 0,
25
+ run: resident,
26
+ },
27
+ ],
28
+ [
29
+ 'git-credential',
30
+ {
31
+ usage: 'usage: kit git-credential <get|store|erase>',
32
+ about: "answers git with your own agent's House credential; git runs it",
33
+ operands: 1,
34
+ run: ([operation]) => answerGitCredential(operation),
35
+ },
36
+ ],
37
+ ]);
38
+ const [command, ...argv] = process.argv.slice(2);
39
+ setGlobalProxyFromEnv();
40
+ async function run() {
41
+ if (command === 'login')
42
+ return login(argv);
43
+ if (command === 'chatgpt')
44
+ return chatgpt(argv);
45
+ if (command === '--help') {
46
+ parseArgs({ args: argv });
47
+ process.stdout.write(USAGE);
48
+ return;
49
+ }
50
+ const chosen = COMMANDS.get(command ?? '');
51
+ if (chosen === undefined) {
52
+ process.stderr.write(USAGE);
53
+ process.exitCode = 2;
54
+ return;
55
+ }
56
+ const { values, positionals } = parseArgs({ args: argv, options: { help: { type: 'boolean', default: false } }, allowPositionals: true });
57
+ if (positionals.length > chosen.operands)
58
+ throw new Error(`unexpected argument ${positionals[chosen.operands]}; ${chosen.usage}`);
59
+ if (values.help) {
60
+ process.stdout.write(`${chosen.usage}\n ${chosen.about}\n`);
61
+ return;
62
+ }
63
+ return chosen.run(positionals);
64
+ }
65
+ run().catch((error) => {
66
+ process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
67
+ process.exitCode = 1;
68
+ });
package/dist/kit-main.js CHANGED
@@ -1,69 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { setGlobalProxyFromEnv } from 'node:http';
3
- import { parseArgs } from 'node:util';
4
- import { answerGitCredential } from './app-git.js';
5
- import { codex } from './codex.js';
6
- import { login } from './login.js';
7
- import { logout } from './logout.js';
8
- import { resident } from './resident.js';
9
- const USAGE = 'usage: kit <login|logout|resident|codex>\n';
10
- const COMMANDS = new Map([
11
- [
12
- 'logout',
13
- {
14
- usage: 'usage: kit logout',
15
- about: "disconnects this computer, stops House Kit and ends your own agent's connection",
16
- operands: 0,
17
- run: logout,
18
- },
19
- ],
20
- [
21
- 'resident',
22
- {
23
- usage: 'usage: kit resident',
24
- about: "keeps this Environment connected; House Kit's service runs it",
25
- operands: 0,
26
- run: resident,
27
- },
28
- ],
29
- [
30
- 'git-credential',
31
- {
32
- usage: 'usage: kit git-credential <get|store|erase>',
33
- about: "answers git with your own agent's House credential; git runs it",
34
- operands: 1,
35
- run: ([operation]) => answerGitCredential(operation),
36
- },
37
- ],
38
- ]);
39
- const [command, ...argv] = process.argv.slice(2);
40
- setGlobalProxyFromEnv();
41
- async function run() {
42
- if (command === 'login')
43
- return login(argv);
44
- if (command === 'codex')
45
- return codex(argv);
46
- if (command === '--help') {
47
- parseArgs({ args: argv });
48
- process.stdout.write(USAGE);
49
- return;
50
- }
51
- const chosen = COMMANDS.get(command ?? '');
52
- if (chosen === undefined) {
53
- process.stderr.write(USAGE);
54
- process.exitCode = 2;
55
- return;
56
- }
57
- const { values, positionals } = parseArgs({ args: argv, options: { help: { type: 'boolean', default: false } }, allowPositionals: true });
58
- if (positionals.length > chosen.operands)
59
- throw new Error(`unexpected argument ${positionals[chosen.operands]}; ${chosen.usage}`);
60
- if (values.help) {
61
- process.stdout.write(`${chosen.usage}\n ${chosen.about}\n`);
62
- return;
63
- }
64
- return chosen.run(positionals);
65
- }
66
- run().catch((error) => {
67
- process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
2
+ const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);
3
+ if (major < 24 || (major === 24 && minor < 14)) {
4
+ process.stderr.write(`kit: the Kit needs Node 24.14.0 or newer; this is ${process.versions.node}\n`);
68
5
  process.exitCode = 1;
69
- });
6
+ }
7
+ else {
8
+ await import('./kit-cli.js');
9
+ }
10
+ export {};
package/dist/login.js CHANGED
@@ -2,11 +2,12 @@ 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
7
  import { writeCodexRule } from './clis.js';
8
- import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
8
+ import { forgetDisconnected, forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent, } from './home.js';
9
9
  import { callHouse, rpc } from './mcp.js';
10
+ import { refusalOf } from './refusals.js';
10
11
  import { selectRelay } from './relay.js';
11
12
  import { startService } from './service.js';
12
13
  import { placeSkillSet } from './skills.js';
@@ -35,6 +36,16 @@ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms
35
36
  --no-private give this Environment every Room but your Private Room
36
37
  --code <code> connect this machine with a login code
37
38
  `;
39
+ function connected(house, named, environment) {
40
+ if (named === undefined)
41
+ return `Environment ${environment} is connected to ${house}.\n`;
42
+ if (named === environment)
43
+ return `Environment ${environment} is reconnected to ${house}.\n`;
44
+ return `Environment ${named} stays with its account; this computer is connected to ${house} as new Environment ${environment} of the account that confirmed.\n`;
45
+ }
46
+ function gone(error) {
47
+ return error instanceof HouseRefusal && refusalOf(error.text)?.code === 'kit_environment_not_found';
48
+ }
38
49
  function chosenRooms(rooms, noPrivate) {
39
50
  if (rooms !== undefined && noPrivate)
40
51
  throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
@@ -73,9 +84,11 @@ export async function login(argv) {
73
84
  selectRelay(relay);
74
85
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
75
86
  const replaces = process.env.HOUSE_KIT_REPLACES;
76
- const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
87
+ const remembered = replaces === undefined && values.environment === undefined && enrolled?.house === house ? enrolled.environment : undefined;
88
+ const environment = replaces === undefined ? (values.environment ?? remembered) : undefined;
77
89
  const ownAgent = await readOwnAgent();
78
90
  let held = false;
91
+ let named = environment;
79
92
  let exchanged;
80
93
  if (values.code !== undefined) {
81
94
  exchanged = await post(house, '/kit/token', { code: values.code, label: hostname() });
@@ -83,41 +96,52 @@ export async function login(argv) {
83
96
  else {
84
97
  held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
85
98
  const verifier = randomBytes(32).toString('base64url');
86
- const started = await retrying(() => post(house, '/kit', {
99
+ const start = () => retrying(() => post(house, '/kit', {
87
100
  label: hostname(),
88
- ...(environment === undefined
101
+ ...(named === undefined
89
102
  ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
90
- : { act: 'existing_environment', environment_id: environment }),
103
+ : { act: 'existing_environment', environment_id: named }),
91
104
  ...rooms,
92
105
  code_challenge: createHash('sha256').update(verifier).digest('base64url'),
93
106
  ...(held ? {} : { headless: true }),
94
107
  }));
108
+ let started;
109
+ try {
110
+ started = await start();
111
+ }
112
+ catch (error) {
113
+ if (remembered === undefined || !gone(error))
114
+ throw error;
115
+ await forgetDisconnected();
116
+ process.stdout.write(`House no longer holds Environment ${remembered}; connecting this computer as a new one.\n`);
117
+ named = undefined;
118
+ started = await start();
119
+ }
95
120
  process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
96
121
  open(started.start_url);
97
122
  exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
98
123
  }
99
- try {
100
- await placeSkillSet();
101
- }
102
- catch (error) {
103
- process.stderr.write(`kit: the skills could not be placed: ${error.message}\n`);
104
- }
124
+ await placeSkillSet();
105
125
  await writeCodexRule().catch((error) => process.stderr.write(`kit: ${error.message}\n`));
126
+ const relayRecord = relay === undefined ? {} : { relay };
106
127
  await writeEnrolment({
107
128
  house,
108
- ...(relay === undefined ? {} : { relay }),
129
+ ...relayRecord,
109
130
  environment: exchanged.environment,
110
131
  credential: exchanged.credential,
111
132
  });
112
- process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
133
+ process.stdout.write(connected(house, named, exchanged.environment));
113
134
  if (exchanged.headless_credential !== undefined) {
114
- await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
135
+ await writeOwnAgent({ house, ...relayRecord, user: exchanged.user, credential: exchanged.headless_credential });
115
136
  }
116
137
  else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
117
138
  await forgetOwnAgent();
118
139
  process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
119
140
  }
120
- await placeAppGit(ownAgent, await readOwnAgent());
141
+ else if (held && ownAgent !== null) {
142
+ await writeOwnAgent({ house, ...relayRecord, user: ownAgent.user, credential: ownAgent.credential });
143
+ }
144
+ await placeAppGit(await readOwnAgent()).catch((error) => process.stderr.write(`kit: ${error.message}\n`));
121
145
  try {
122
146
  startService();
123
147
  }
package/dist/logout.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { HouseRefusal, post } from './api.js';
2
- import { forgetAppGit } from './app-git.js';
3
2
  import { forgetEnrolment, forgetOwnAgent, readEnrolment } from './home.js';
4
3
  export async function logout() {
5
4
  const enrolled = await readEnrolment();
@@ -13,7 +12,6 @@ export async function logout() {
13
12
  }
14
13
  await forgetEnrolment(enrolled);
15
14
  }
16
- await forgetAppGit();
17
15
  await forgetOwnAgent();
18
16
  process.stdout.write(enrolled === null
19
17
  ? 'This computer is not connected to House.\n'
package/dist/mcp.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { KIT_VERSION } from './clis.js';
2
+ import { KIT_RELEASE } from './clis.js';
3
3
  import { relayed } from './relay.js';
4
4
  const MCP_PROTOCOL_VERSION = '2026-07-28';
5
5
  export const UNREACHABLE = 'House is unreachable; call again in a minute';
6
+ export class Unsettled extends Error {
7
+ }
6
8
  export function rpc(method, params) {
7
9
  return { jsonrpc: '2.0', id: randomUUID(), method, params };
8
10
  }
@@ -13,7 +15,7 @@ export function mcpBody(message, operation) {
13
15
  ...message.params,
14
16
  _meta: {
15
17
  'io.modelcontextprotocol/protocolVersion': MCP_PROTOCOL_VERSION,
16
- 'io.modelcontextprotocol/clientInfo': { name: '@agentshouse/kit', version: KIT_VERSION },
18
+ 'io.modelcontextprotocol/clientInfo': { name: '@agentshouse/kit', version: KIT_RELEASE },
17
19
  'io.modelcontextprotocol/clientCapabilities': {},
18
20
  ...(operation === null ? {} : { 'agents.house/agent-operation': operation }),
19
21
  },
package/dist/placement.js CHANGED
@@ -2,7 +2,6 @@ import { readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { run } from './clis.js';
4
4
  import { kitHome } from './home.js';
5
- import { relayOrigin } from './relay.js';
6
5
  export function service() {
7
6
  if (process.platform !== 'linux' || !process.env.INVOCATION_ID)
8
7
  return null;
@@ -19,9 +18,9 @@ export async function updatesItself() {
19
18
  // sudo answers at once, so ten seconds only bounds a stuck sudo.
20
19
  return (await run('sudo', ['-n', 'true'], 10_000)).status === 0;
21
20
  }
22
- function installed() {
21
+ function recorded(name) {
23
22
  try {
24
- return readFileSync(join(kitHome(), 'placement'), 'utf8').trim();
23
+ return readFileSync(join(kitHome(), name), 'utf8').trim();
25
24
  }
26
25
  catch (error) {
27
26
  if (error.code === 'ENOENT')
@@ -29,20 +28,12 @@ function installed() {
29
28
  throw error;
30
29
  }
31
30
  }
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`];
31
+ export function installCommand() {
32
+ return recorded('install-command');
39
33
  }
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`;
34
+ export function machine() {
35
+ const placed = recorded('placement');
36
+ if (placed === 'container' || placed === 'server' || placed === 'windows')
37
+ return placed;
38
+ return process.platform === 'darwin' ? 'macos' : 'linux';
48
39
  }
package/dist/resident.js CHANGED
@@ -1,22 +1,24 @@
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 { CONVERSATION_INPUTS, Conversations } from './conversations.js';
11
+ import { CONVERSATION_METHODS, Conversations } from './conversations.js';
11
12
  import { LocalCopies } from './copies.js';
12
13
  import { restart } from './end.js';
13
- import { agentBase, enrolled, forgetRestart, kitHome, restartAsked } from './home.js';
14
+ import { agentBase, enrolled, forgetRestart, kitHome, ownerLock, ownerSocket, restartAsked } from './home.js';
15
+ import { Calls } from './calls.js';
14
16
  import { killDescendants } from './scope.js';
15
17
  import { quoted } from './shell.js';
16
18
  import { SignIns } from './sign-in.js';
17
19
  import { placeSkillSet } from './skills.js';
18
- import { holdStream } from './stream.js';
19
- import { Updates } from './update.js';
20
+ import { holdConnection } from './connection.js';
21
+ import { KitUpdate } from './update.js';
20
22
  import { codexLauncher } from './work.js';
21
23
  function report(error) {
22
24
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
@@ -29,13 +31,32 @@ async function installShim(path, module) {
29
31
  await mkdir(dirname(path), { recursive: true });
30
32
  await writeFile(path, `#!/bin/sh\nexec ${quoted(process.execPath)} ${quoted(main)} "$@"\n`, { mode: 0o755 });
31
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
+ }
32
45
  async function serveOwner(copies) {
33
- const socketPath = join(kitHome(), 'owner.sock');
34
- 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 process' : `Kit process ${running}`} already runs this Environment from Kit home ${kitHome()}; stop it first to run another Kit process here`);
51
+ }
35
52
  const server = createServer(async (request, response) => {
36
53
  try {
37
54
  const text = await received(request);
38
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
+ }
39
60
  if (request.url === '/git/fetch') {
40
61
  answered = await copies.fetch();
41
62
  }
@@ -53,9 +74,23 @@ async function serveOwner(copies) {
53
74
  response.writeHead(502).end(error instanceof Error ? error.message : String(error));
54
75
  }
55
76
  });
56
- server.listen(socketPath);
77
+ server.on('close', () => lock.close());
78
+ await rm(ownerSocket(), { force: true });
79
+ server.listen(ownerSocket());
57
80
  await once(server, 'listening');
58
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
+ }
59
94
  function connected() {
60
95
  return new Promise((resolve) => {
61
96
  const watcher = watch(kitHome(), () => {
@@ -72,7 +107,7 @@ function connected() {
72
107
  resolve();
73
108
  });
74
109
  }
75
- export async function resident() {
110
+ async function started() {
76
111
  await connected();
77
112
  await forgetRestart();
78
113
  watch(kitHome(), () => {
@@ -83,16 +118,23 @@ export async function resident() {
83
118
  });
84
119
  await placeSkillSet();
85
120
  await mkdir(agentBase(), { recursive: true });
86
- process.env.HOUSE_KIT_RESIDENT = String(process.pid);
87
- const agents = new Agents(house);
88
- const copies = new LocalCopies(house);
89
- await copies.load();
90
121
  await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
91
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();
92
128
  await serveOwner(copies);
93
- let stream = null;
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());
135
+ let connection = null;
94
136
  let reported = false;
95
- const idle = () => conversations.idle() && signIns.idle();
137
+ const idle = () => calls.idle() && conversations.idle() && agents.idle();
96
138
  const changed = () => {
97
139
  if (!idle()) {
98
140
  reported = false;
@@ -105,15 +147,17 @@ export async function resident() {
105
147
  logged(house.deliver('/kit/idle', {}, idle));
106
148
  }
107
149
  };
150
+ const calls = new Calls(house, changed);
108
151
  const conversations = new Conversations({
109
152
  house,
110
153
  agents,
111
154
  copies,
112
- send: (frame) => stream?.send(frame) ?? false,
155
+ calls,
156
+ send: (notification) => connection?.send(notification) ?? false,
113
157
  changed,
114
158
  });
115
- const signIns = new SignIns(house, agents, changed);
116
- const updates = new Updates(house);
159
+ const signIns = new SignIns(house, agents, calls);
160
+ const update = new KitUpdate(calls);
117
161
  for (const signal of ['SIGTERM', 'SIGINT']) {
118
162
  process.once(signal, () => {
119
163
  killDescendants();
@@ -121,32 +165,33 @@ export async function resident() {
121
165
  });
122
166
  }
123
167
  await house.deliver('/kit/restarted', {}).catch(report);
124
- await updates.resumed().catch(report);
168
+ await update.resumed().catch(report);
125
169
  logged(agents.refresh());
126
- stream = holdStream({
170
+ connection = holdConnection({
127
171
  opened: () => {
128
172
  conversations.opened();
129
173
  changed();
130
174
  logged(copies.connected());
131
175
  },
132
- frame: (arrived) => {
133
- if (arrived.type === 'watching')
134
- conversations.watching(arrived.watching === true);
135
- if (arrived.type === 'work_available' && arrived.subject === 'agents')
136
- logged(agents.refresh());
137
- if (arrived.type === 'input') {
138
- reported = false;
139
- if (arrived.kind === 'sign_in')
140
- signIns.start(arrived);
141
- else if (arrived.kind === 'update')
142
- updates.start(arrived);
143
- else if (CONVERSATION_INPUTS.has(arrived.kind))
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
- }
176
+ call: (call) => {
177
+ if (call.kind === 'sign_in')
178
+ signIns.start(call);
179
+ else if (call.kind === 'update')
180
+ update.start(call);
181
+ else if (CONVERSATION_METHODS.has(call.kind))
182
+ conversations.call(call);
183
+ else {
184
+ const refused = { refused: `This Kit does not know ${call.kind}; update the Kit` };
185
+ void calls.carry(call.input_id, async () => ({ result: refused }));
149
186
  }
150
187
  },
188
+ notification: (notification) => {
189
+ if (notification.type === 'watching')
190
+ conversations.watching(notification.watching === true);
191
+ if (notification.type === 'authority_changed')
192
+ logged(copies.changed(notification.rooms));
193
+ if (notification.type === 'work_available' && notification.subject === 'agents')
194
+ logged(agents.refresh());
195
+ },
151
196
  });
152
197
  }
package/dist/scope.js CHANGED
@@ -4,6 +4,7 @@ import { join } from 'node:path';
4
4
  const LISTING_BYTES = 1 << 28;
5
5
  const CGROUPS = '/sys/fs/cgroup';
6
6
  const GONE = new Set(['ENOENT', 'ESRCH']);
7
+ const EXITED = new Set(['Z', 'X']);
7
8
  function failure(error) {
8
9
  return error.code ?? '';
9
10
  }
@@ -24,6 +25,8 @@ function read(pid) {
24
25
  try {
25
26
  const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
26
27
  const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
28
+ if (EXITED.has(fields[0]))
29
+ return null;
27
30
  const command = readFileSync(`/proc/${pid}/cmdline`, 'utf8').replaceAll('\0', ' ');
28
31
  return { parent: Number(fields[1]), session: fields[3], command };
29
32
  }
package/dist/service.js CHANGED
@@ -1,4 +1,7 @@
1
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';
2
5
  const UNIT = 'house-kit.service';
3
6
  // launchctl and systemctl answer at once, so ten seconds only bounds a stuck service manager.
4
7
  const MANAGER_MS = 10_000;
@@ -10,7 +13,21 @@ function start(command, args) {
10
13
  if (started.status === 0)
11
14
  return;
12
15
  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}`);
16
+ throw new Error(`the 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());
14
31
  }
15
32
  export function startService() {
16
33
  if (process.platform === 'darwin') {
@@ -18,12 +35,17 @@ export function startService() {
18
35
  const printed = manage('launchctl', ['print', service]);
19
36
  if (printed.status !== 0 || /^\tstate = running$/m.test(printed.stdout))
20
37
  return false;
38
+ if (!runsThisHome(/^\t+HOUSE_KIT_HOME => (.+)$/m.exec(printed.stdout)?.[1]))
39
+ return false;
21
40
  start('launchctl', ['kickstart', service]);
22
41
  return true;
23
42
  }
24
43
  for (const scope of [['--user'], []]) {
25
44
  if (manage('systemctl', [...scope, 'is-enabled', '--quiet', UNIT]).status !== 0)
26
45
  continue;
46
+ const environment = manage('systemctl', [...scope, 'show', '--property=Environment', '--value', UNIT]).stdout;
47
+ if (!runsThisHome(systemdHome(environment)))
48
+ continue;
27
49
  if (manage('systemctl', [...scope, 'is-active', '--quiet', UNIT]).status === 0)
28
50
  return false;
29
51
  start('systemctl', [...scope, 'start', UNIT]);