@agentshouse/kit 0.2.1-cf110d15f69c8 → 0.2.1-cf2c570b41f24

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 (147) hide show
  1. package/README.md +38 -44
  2. package/dist/acp.js +96 -22
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +221 -65
  5. package/dist/api.js +21 -3
  6. package/dist/app-git.js +10 -26
  7. package/dist/binaries.js +60 -0
  8. package/dist/bridge.js +101 -49
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +88 -0
  11. package/dist/chunks.js +54 -0
  12. package/dist/clis.js +80 -52
  13. package/dist/connect.js +121 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +106 -0
  16. package/dist/conversations.js +711 -267
  17. package/dist/copies.js +1293 -595
  18. package/dist/earlier.js +273 -0
  19. package/dist/end.js +15 -3
  20. package/dist/events.js +553 -281
  21. package/dist/files.js +206 -32
  22. package/dist/git.js +2 -70
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +123 -15
  25. package/dist/house-cli.js +282 -0
  26. package/dist/house-main.js +7 -206
  27. package/dist/instructions.js +7 -13
  28. package/dist/keys.js +238 -0
  29. package/dist/kit-cli.js +78 -0
  30. package/dist/kit-main.js +8 -22
  31. package/dist/login.js +71 -39
  32. package/dist/logout.js +2 -4
  33. package/dist/manifest.js +75 -0
  34. package/dist/mcp.js +47 -7
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +25 -0
  37. package/dist/refusals.js +50 -23
  38. package/dist/relay.js +22 -1
  39. package/dist/resident.js +153 -53
  40. package/dist/scope.js +15 -4
  41. package/dist/scripts.js +319 -0
  42. package/dist/secret-input.js +1 -1
  43. package/dist/settings.js +247 -0
  44. package/dist/sign-in.js +66 -38
  45. package/dist/silence.js +28 -0
  46. package/dist/skills.js +49 -35
  47. package/dist/supervisor.js +163 -0
  48. package/dist/transcription.js +90 -47
  49. package/dist/update.js +119 -102
  50. package/dist/wire.js +32 -0
  51. package/dist/work.js +30 -7
  52. package/dist/workspace.js +113 -0
  53. package/package.json +25 -21
  54. package/dist/authority-main.js +0 -22
  55. package/dist/bootstrap.json +0 -24
  56. package/dist/clis-main.js +0 -23
  57. package/dist/configure-main.js +0 -6
  58. package/dist/enrol-main.js +0 -10
  59. package/dist/git-main.js +0 -153
  60. package/dist/parts.js +0 -82
  61. package/dist/service-main.js +0 -9
  62. package/dist/service.js +0 -33
  63. package/dist/stream.js +0 -74
  64. package/dist/translate.js +0 -51
  65. package/how-we-work.md +0 -23
  66. package/skills/ask-matt/LICENSE +0 -21
  67. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  68. package/skills/ask-matt/SKILL.md +0 -91
  69. package/skills/ask-matt/agents/openai.yaml +0 -4
  70. package/skills/code-review/LICENSE +0 -21
  71. package/skills/code-review/SKILL.md +0 -89
  72. package/skills/code-review/agents/openai.yaml +0 -3
  73. package/skills/codebase-design/DEEPENING.md +0 -37
  74. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  75. package/skills/codebase-design/LICENSE +0 -21
  76. package/skills/codebase-design/SKILL.md +0 -116
  77. package/skills/codebase-design/agents/openai.yaml +0 -3
  78. package/skills/diagnosing-bugs/LICENSE +0 -21
  79. package/skills/diagnosing-bugs/SKILL.md +0 -140
  80. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  81. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  82. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  83. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  84. package/skills/domain-modeling/LICENSE +0 -21
  85. package/skills/domain-modeling/SKILL.md +0 -76
  86. package/skills/domain-modeling/agents/openai.yaml +0 -3
  87. package/skills/grill-me/LICENSE +0 -21
  88. package/skills/grill-me/SKILL.md +0 -8
  89. package/skills/grill-me/agents/openai.yaml +0 -4
  90. package/skills/grill-with-docs/LICENSE +0 -21
  91. package/skills/grill-with-docs/SKILL.md +0 -8
  92. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  93. package/skills/grilling/LICENSE +0 -21
  94. package/skills/grilling/SKILL.md +0 -30
  95. package/skills/grilling/agents/openai.yaml +0 -3
  96. package/skills/handoff/LICENSE +0 -21
  97. package/skills/handoff/SKILL.md +0 -17
  98. package/skills/handoff/agents/openai.yaml +0 -4
  99. package/skills/implement/LICENSE +0 -21
  100. package/skills/implement/SKILL.md +0 -16
  101. package/skills/implement/agents/openai.yaml +0 -4
  102. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  103. package/skills/improve-codebase-architecture/LICENSE +0 -21
  104. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  105. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  106. package/skills/prototype/LICENSE +0 -21
  107. package/skills/prototype/LOGIC.md +0 -67
  108. package/skills/prototype/SKILL.md +0 -28
  109. package/skills/prototype/UI.md +0 -112
  110. package/skills/prototype/agents/openai.yaml +0 -3
  111. package/skills/research/LICENSE +0 -21
  112. package/skills/research/SKILL.md +0 -14
  113. package/skills/research/agents/openai.yaml +0 -3
  114. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  115. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  116. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  117. package/skills/tdd/LICENSE +0 -21
  118. package/skills/tdd/SKILL.md +0 -40
  119. package/skills/tdd/agents/openai.yaml +0 -3
  120. package/skills/tdd/mocking.md +0 -59
  121. package/skills/tdd/tests.md +0 -77
  122. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  123. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  124. package/skills/teach/LICENSE +0 -21
  125. package/skills/teach/MISSION-FORMAT.md +0 -31
  126. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  127. package/skills/teach/SKILL.md +0 -141
  128. package/skills/teach/agents/openai.yaml +0 -4
  129. package/skills/to-questionnaire/LICENSE +0 -21
  130. package/skills/to-questionnaire/SKILL.md +0 -55
  131. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  132. package/skills/to-spec/LICENSE +0 -21
  133. package/skills/to-spec/SKILL.md +0 -76
  134. package/skills/to-spec/agents/openai.yaml +0 -4
  135. package/skills/to-tickets/LICENSE +0 -21
  136. package/skills/to-tickets/SKILL.md +0 -106
  137. package/skills/to-tickets/agents/openai.yaml +0 -4
  138. package/skills/wait-what/LICENSE +0 -21
  139. package/skills/wait-what/SKILL.md +0 -8
  140. package/skills/wait-what/agents/openai.yaml +0 -4
  141. package/skills/wayfinder/LICENSE +0 -21
  142. package/skills/wayfinder/SKILL.md +0 -129
  143. package/skills/wayfinder/agents/openai.yaml +0 -4
  144. package/skills/writing-for-agents/LICENSE +0 -21
  145. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  146. package/skills/writing-for-agents/SKILL.md +0 -83
  147. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/clis.js CHANGED
@@ -1,9 +1,12 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { constants, readFileSync } from 'node:fs';
3
4
  import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
4
- import { homedir, userInfo } from 'node:os';
5
- import { delimiter, isAbsolute, join } from 'node:path';
6
- import { kitHome } from './home.js';
5
+ import { userInfo } from 'node:os';
6
+ import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
+ import { CLAUDE_KEY, CODEX_KEY, GROK_KEY, codexHome } from './keys.js';
8
+ import { releaseDirectory } from './placement.js';
9
+ import { childEnvironment } from './relay.js';
7
10
  const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
8
11
  function houseRule(houses) {
9
12
  return `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`;
@@ -13,10 +16,12 @@ const RAW_SUBTYPES = [
13
16
  'task_started',
14
17
  'task_updated',
15
18
  'task_notification',
19
+ 'task_progress',
16
20
  'session_state_changed',
17
21
  'hook_started',
18
22
  'hook_response',
19
23
  ];
24
+ const RAW_TYPES = ['result', 'user', 'assistant', 'rate_limit_event', 'prompt_suggestion'];
20
25
  async function executable(path) {
21
26
  try {
22
27
  await access(path, constants.X_OK);
@@ -46,7 +51,7 @@ async function listedHouses(file) {
46
51
  }
47
52
  export async function allowHouseInCodex(path) {
48
53
  const candidates = [...new Set(path.split(delimiter).filter((directory) => isAbsolute(directory)))].map((directory) => join(directory, 'house'));
49
- const rules = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'rules');
54
+ const rules = join(codexHome(), 'rules');
50
55
  const file = join(rules, 'house.rules');
51
56
  const houses = [];
52
57
  for (const house of [...(await listedHouses(file)), ...candidates]) {
@@ -54,19 +59,32 @@ export async function allowHouseInCodex(path) {
54
59
  houses.push(house);
55
60
  }
56
61
  await mkdir(rules, { recursive: true });
57
- const temporary = `${file}.${process.pid}`;
62
+ const temporary = `${file}.${randomUUID()}`;
58
63
  await writeFile(temporary, houseRule(houses));
59
64
  await rename(temporary, file);
60
65
  }
61
66
  async function nothing() { }
67
+ function claudeQuestionFields(request) {
68
+ const properties = request.requestedSchema?.properties ?? {};
69
+ return Object.keys(properties).filter((name) => properties[name]._meta?.jetbrains?.air?.customAnswer !== undefined);
70
+ }
71
+ function codexQuestionFields(request) {
72
+ const { _meta, requestedSchema } = request;
73
+ return _meta?.codex === undefined ? [] : (requestedSchema?.required ?? []);
74
+ }
75
+ function answered(error) {
76
+ return typeof error === 'object' && error !== null ? error : {};
77
+ }
62
78
  function bridgeInClaudeSandbox(bridge) {
63
79
  return process.platform === 'darwin' ? { allowUnixSockets: [bridge] } : { allowAllUnixSockets: true };
64
80
  }
65
81
  export const CLIS = {
66
82
  'codex-acp': {
83
+ name: 'Codex',
67
84
  bin: 'codex',
68
- minimum: '0.159.1',
85
+ minimum: '0.165.0',
69
86
  install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
87
+ update: 'codex update',
70
88
  adapter: {
71
89
  package: '@agentclientprotocol/codex-acp',
72
90
  bin: 'codex-acp',
@@ -76,16 +94,23 @@ export const CLIS = {
76
94
  args: [],
77
95
  fullAccess: 'agent-full-access',
78
96
  sessionMeta: () => ({}),
79
- renames: true,
97
+ unknownSession: (error) => {
98
+ const { code, data } = answered(error);
99
+ return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
100
+ },
80
101
  allowHouse: allowHouseInCodex,
102
+ questionFields: codexQuestionFields,
81
103
  signedIn: { command: ['login', 'status'] },
82
104
  login: { args: ['login', '--device-auth'], code: 'show' },
105
+ key: CODEX_KEY,
83
106
  air: ['asyncTasks', 'nativeSubagentSessions'],
84
107
  },
85
108
  'claude-agent-acp': {
109
+ name: 'Claude Code',
86
110
  bin: 'claude',
87
- minimum: '2.1.286',
111
+ minimum: '2.1.316',
88
112
  install: 'curl -fsSL https://claude.ai/install.sh | bash',
113
+ update: 'claude update',
89
114
  adapter: {
90
115
  package: '@agentclientprotocol/claude-agent-acp',
91
116
  bin: 'claude-agent-acp',
@@ -94,71 +119,63 @@ export const CLIS = {
94
119
  },
95
120
  args: [],
96
121
  fullAccess: 'bypassPermissions',
97
- sessionMeta: (bridge, title) => ({
122
+ sessionMeta: (bridge) => ({
98
123
  claudeCode: {
99
124
  options: {
100
125
  allowedTools: ['Bash(house:*)'],
101
126
  includeHookEvents: true,
102
- title,
103
127
  settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
104
128
  },
105
- emitRawSDKMessages: RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })),
129
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), ...RAW_TYPES.map((type) => ({ type }))],
106
130
  },
107
131
  }),
108
- renames: false,
132
+ unknownSession: (error) => answered(error).code === -32002,
109
133
  allowHouse: nothing,
134
+ questionFields: claudeQuestionFields,
110
135
  signedIn: { command: ['auth', 'status'] },
111
136
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
137
+ key: CLAUDE_KEY,
112
138
  air: ['asyncTasks', 'sessionFailure'],
113
139
  },
114
140
  'grok-build': {
141
+ name: 'Grok Build',
115
142
  bin: 'grok',
116
143
  minimum: '1.0.46',
117
144
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
145
+ update: 'grok update',
118
146
  adapter: null,
119
147
  args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
120
148
  fullAccess: null,
121
149
  sessionMeta: () => ({}),
122
- renames: false,
150
+ unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
123
151
  allowHouse: nothing,
124
- signedIn: { initializeMeta: 'defaultAuthMethodId' },
152
+ questionFields: () => [],
153
+ signedIn: { initializeMeta: 'defaultAuthMethodId', apiKey: 'xai.api_key' },
125
154
  login: { args: ['login', '--device-auth'], code: 'show' },
155
+ key: GROK_KEY,
126
156
  air: ['asyncTasks'],
127
157
  },
128
158
  };
129
159
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
130
- export const KIT_VERSION = KIT_PACKAGE.version;
131
- const PROXY = /^https?_proxy$/i;
160
+ export const KIT_RELEASE = KIT_PACKAGE.version;
132
161
  const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
133
- // An install still running after fifteen minutes is ended and reported as failed, so a hung download cannot hold its CLI's report.
162
+ // An install or update still running after fifteen minutes is ended as failed, so a hung download can neither hold its CLI's report nor keep the Kit busy.
134
163
  const INSTALL_MS = 15 * 60_000;
135
164
  // A login shell or a version read is ended after half a minute, so a profile that waits for input cannot stall the report.
136
165
  const READ_MS = 30_000;
137
166
  const CAUSE_CHARACTERS = 4000;
138
- function prefix(kind) {
139
- return join(kitHome(), 'agents', kind);
140
- }
141
167
  export function adapterCommand(kind) {
142
- return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].adapter.bin);
168
+ return join(releaseDirectory(KIT_RELEASE), 'adapters', kind, 'node_modules', '.bin', CLIS[kind].adapter.bin);
143
169
  }
144
- async function installedAdapter(kind) {
145
- try {
146
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].adapter.package, 'package.json');
147
- return JSON.parse(await readFile(manifest, 'utf8')).version;
148
- }
149
- catch {
150
- return null;
151
- }
152
- }
153
- export function withoutProxy() {
154
- return Object.fromEntries(Object.entries(process.env).filter(([name]) => !PROXY.test(name)));
170
+ export async function cliEnvironment(kind) {
171
+ return { ...childEnvironment(), ...(await CLIS[kind].key.environment?.()) };
155
172
  }
156
- export function run(command, args, timeoutMs, detached = false, signal) {
173
+ export function run(command, args, timeoutMs, detached = false, signal, env = childEnvironment()) {
157
174
  return new Promise((resolve) => {
158
175
  const child = spawn(command, args, {
159
176
  stdio: ['ignore', 'pipe', 'pipe'],
160
177
  timeout: timeoutMs,
161
- env: withoutProxy(),
178
+ env,
162
179
  detached,
163
180
  signal: detached ? undefined : signal,
164
181
  });
@@ -192,19 +209,18 @@ export function run(command, args, timeoutMs, detached = false, signal) {
192
209
  export function failureOf(ran, program) {
193
210
  return ran.output.trim().slice(-CAUSE_CHARACTERS) || `${program} exited with ${ran.status ?? 'a signal'}`;
194
211
  }
195
- export async function installAdapter(kind, signal) {
196
- const adapter = CLIS[kind].adapter;
197
- if (adapter === null)
198
- return null;
199
- const release = KIT_PACKAGE.peerDependencies[adapter.package];
200
- if ((await installedAdapter(kind)) === release)
201
- return null;
202
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--no-save', '--no-audit', '--no-fund', '--omit=optional', `${adapter.package}@${release}`], INSTALL_MS, true, signal);
203
- return ran.status === 0 ? null : failureOf(ran, 'npm');
212
+ export function adapterArchive(kind) {
213
+ return `${kind}-${KIT_PACKAGE.peerDependencies[CLIS[kind].adapter.package]}.tar.gz`;
204
214
  }
205
- export async function installCli(kind, signal) {
206
- const ran = await run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, signal);
207
- return ran.status === 0 ? null : failureOf(ran, 'the install');
215
+ async function bounded(program, work, signal) {
216
+ const deadline = AbortSignal.timeout(INSTALL_MS);
217
+ const ran = await work(signal === undefined ? deadline : AbortSignal.any([signal, deadline]));
218
+ if (deadline.aborted && signal?.aborted !== true)
219
+ return `${program} did not end within ${INSTALL_MS / 1000} seconds`;
220
+ return ran.status === 0 ? null : failureOf(ran, program);
221
+ }
222
+ export function installCli(kind, signal) {
223
+ return bounded('the install', (within) => run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, within), signal);
208
224
  }
209
225
  function loginShell() {
210
226
  return process.env.SHELL || userInfo().shell;
@@ -212,20 +228,32 @@ function loginShell() {
212
228
  const FOUND = 'house-kit-cli ';
213
229
  const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
214
230
  const USER_BIN = 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$PATH:$HOME/.local/bin" ;; esac; export PATH';
215
- function inLoginShell(script, argument = '', signal) {
216
- return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], READ_MS, true, signal);
231
+ function inLoginShell(script, argument = '', signal, timeoutMs = READ_MS) {
232
+ return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], timeoutMs, true, signal);
217
233
  }
218
- export async function locate(kind, signal) {
219
- const ran = await inLoginShell(LOOKUP, CLIS[kind].bin, signal);
234
+ export async function onLoginPath(program, signal) {
235
+ const ran = await inLoginShell(LOOKUP, program, signal);
220
236
  return ran.stdout.split('\n').findLast((line) => line.startsWith(FOUND))?.slice(FOUND.length) ?? null;
221
237
  }
238
+ export function locate(kind, signal) {
239
+ return onLoginPath(CLIS[kind].bin, signal);
240
+ }
241
+ export function updateCli(kind) {
242
+ return bounded('the update', (within) => inLoginShell(CLIS[kind].update, '', within, INSTALL_MS));
243
+ }
222
244
  export async function loginPath() {
223
245
  const marker = 'house-kit-path ';
224
246
  const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
225
247
  return ran.stdout.split('\n').findLast((line) => line.startsWith(marker)).slice(marker.length);
226
248
  }
227
- export async function versionOf(path, signal) {
228
- return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal)).stdout)?.[0] ?? null;
249
+ export async function writeCodexRule() {
250
+ const shell = await loginPath().catch(() => '');
251
+ await allowHouseInCodex([dirname(process.execPath), process.env.PATH ?? '', shell].join(delimiter)).catch((error) => {
252
+ throw new Error(`Codex's rule for house could not be written: ${error.message}`);
253
+ });
254
+ }
255
+ export async function versionOf(kind, path, signal) {
256
+ return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal, await cliEnvironment(kind))).stdout)?.[0] ?? null;
229
257
  }
230
258
  function numbers(version) {
231
259
  return version.split(/[.-]/, 3).map(Number);
@@ -0,0 +1,121 @@
1
+ import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs';
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { HouseRefusal, kitAct } from './api.js';
6
+ import { KIT_RELEASE } from './clis.js';
7
+ import { otherAccountKit, takeOverEarlier } from './earlier.js';
8
+ import { kitHome, readDisconnected, readEnrolment, storedConfiguration, writeConfiguration } from './home.js';
9
+ import { DEFAULT_HOUSE, enrol, placeConnection } from './login.js';
10
+ import { runningRelease } from './owner.js';
11
+ import { HOUSE_NOT_KITS, houseRoot } from './settings.js';
12
+ import { quoted } from './shell.js';
13
+ import { defineSupervisor, launcher, supervise, systemd } from './supervisor.js';
14
+ const USAGE = `usage: kit connect [--house <origin>] [--code <code>]
15
+ --house <origin> the Building this account's Kit serves, ${DEFAULT_HOUSE} unless one is stored
16
+ --code <code> connect this computer with a login code when Kit holds no credential House accepts
17
+ `;
18
+ const HELD = 'held-enrolment';
19
+ const RECORDS = ['credential.json', 'disconnected.json'];
20
+ const ENDS = ['SIGHUP', 'SIGINT', 'SIGTERM'];
21
+ function unanswered(error) {
22
+ return error instanceof HouseRefusal ? error.status >= 500 : error instanceof TypeError && error.message === 'fetch failed';
23
+ }
24
+ async function standing(house, credential) {
25
+ try {
26
+ await kitAct(house, 'agents/desired/list', {}, credential);
27
+ return true;
28
+ }
29
+ catch (error) {
30
+ if (error instanceof HouseRefusal && error.status === 401)
31
+ return false;
32
+ if (!unanswered(error))
33
+ throw error;
34
+ process.stderr.write(`kit: House did not answer, so the stored credential stands: ${error.message}\n`);
35
+ return true;
36
+ }
37
+ }
38
+ function settleHeld() {
39
+ const held = join(kitHome(), HELD);
40
+ if (!existsSync(held))
41
+ return;
42
+ if (!existsSync(join(kitHome(), RECORDS[0]))) {
43
+ for (const record of RECORDS)
44
+ if (existsSync(join(held, record)))
45
+ renameSync(join(held, record), join(kitHome(), record));
46
+ }
47
+ rmSync(held, { recursive: true, force: true });
48
+ }
49
+ async function heldWhile(work) {
50
+ const held = join(kitHome(), HELD);
51
+ mkdirSync(held, { mode: 0o700 });
52
+ const ended = () => {
53
+ settleHeld();
54
+ process.exit(130);
55
+ };
56
+ for (const signal of ENDS)
57
+ process.once(signal, ended);
58
+ try {
59
+ for (const record of RECORDS)
60
+ if (existsSync(join(kitHome(), record)))
61
+ renameSync(join(kitHome(), record), join(held, record));
62
+ await work();
63
+ }
64
+ finally {
65
+ for (const signal of ENDS)
66
+ process.off(signal, ended);
67
+ settleHeld();
68
+ }
69
+ }
70
+ export async function connect(argv) {
71
+ const { values } = parseArgs({
72
+ args: argv,
73
+ options: { house: { type: 'string' }, code: { type: 'string' }, help: { type: 'boolean', default: false } },
74
+ });
75
+ if (values.help) {
76
+ process.stdout.write(USAGE);
77
+ return;
78
+ }
79
+ await takeOverEarlier();
80
+ settleHeld();
81
+ const held = await storedConfiguration();
82
+ const workspace = held.workspace ?? (await houseRoot());
83
+ if (workspace === null)
84
+ throw new Error(HOUSE_NOT_KITS);
85
+ const stored = await readEnrolment();
86
+ const other = stored === null && (await readDisconnected()) === null ? otherAccountKit() : null;
87
+ if (other !== null)
88
+ throw new Error(`this computer's Kit runs as ${other}; run this command as ${other} to update it`);
89
+ const house = values.house ?? stored?.house ?? DEFAULT_HOUSE;
90
+ if (stored !== null && stored.house !== house) {
91
+ throw new Error(`this account's Kit serves ${stored.house}; kit logout disconnects it from there, then this command connects it to ${house}`);
92
+ }
93
+ if (stored === null || !(await standing(stored.house, stored.credential))) {
94
+ if (values.code === undefined)
95
+ await enrol({ house, 'no-private': false });
96
+ else
97
+ await heldWhile(() => enrol({ house, code: values.code, 'no-private': false }));
98
+ if ((await readEnrolment()) === null)
99
+ throw new Error('kit login connected no Environment');
100
+ }
101
+ else if (values.code !== undefined) {
102
+ process.stdout.write(`This computer is already connected as Environment ${stored.environment}; the login code was not used.\n`);
103
+ }
104
+ const install = process.env.HOUSE_KIT_INSTALL_COMMAND;
105
+ if (install !== undefined && install !== '')
106
+ await writeFile(join(kitHome(), 'install-command'), `${install}\n`, { mode: 0o600 });
107
+ const settings = await storedConfiguration();
108
+ if (settings.skills === undefined || settings.workspace === undefined) {
109
+ await writeConfiguration({ skills: true, workspace, ...settings });
110
+ }
111
+ await placeConnection(house);
112
+ const { environment } = (await readEnrolment());
113
+ if (process.platform !== 'darwin' && !systemd()) {
114
+ process.stdout.write(`Kit ${KIT_RELEASE} is installed for Environment ${environment}, but no systemd runs on this host to start it; run ${quoted(launcher())} resident under your own service manager, restarting it whenever it ends with a failure.\n`);
115
+ return;
116
+ }
117
+ const changed = await defineSupervisor();
118
+ const running = await runningRelease();
119
+ await supervise(changed, running !== null && running !== KIT_RELEASE);
120
+ process.stdout.write(`Kit connected for Environment ${environment}.\n`);
121
+ }
@@ -0,0 +1,120 @@
1
+ import { KIT_CONNECTION_PATH, KIT_CONNECTION_PROTOCOL_PREFIX, KIT_WIRE, } from '@agentshouse/kit-wire';
2
+ import { subscribe } from 'node:diagnostics_channel';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { HouseRefusal, retryDelay } from './api.js';
5
+ import { end, REPLACED, signInAgain } from './end.js';
6
+ import { readEnrolment } from './home.js';
7
+ import { relayed } from './relay.js';
8
+ import { Silence } from './silence.js';
9
+ import { endUnserved, unserved } from './wire.js';
10
+ const SUBPROTOCOL = `${KIT_CONNECTION_PROTOCOL_PREFIX}${KIT_WIRE}`;
11
+ const REFUSAL_HEADER = 'x-house-refusal';
12
+ // House beats each Kit connection every thirty seconds, so two silent beats mean this Kit process cannot hear House.
13
+ export const CONNECTION_SILENCE_MS = 60_000;
14
+ // A stopping Kit waits up to two seconds for House to answer its close, so what it sent last reaches House and a House that does not answer holds no stop.
15
+ const CLOSE_ANSWER_MS = 2_000;
16
+ function connectionUrl(house) {
17
+ const url = new URL(KIT_CONNECTION_PATH, house);
18
+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
19
+ return url;
20
+ }
21
+ function header(headers, name) {
22
+ for (let index = 0; index < headers.length; index += 2) {
23
+ if (headers[index].toString('latin1').toLowerCase() === name)
24
+ return headers[index + 1].toString('latin1');
25
+ }
26
+ return '';
27
+ }
28
+ let refused = null;
29
+ subscribe('undici:request:headers', (message) => {
30
+ const { request, response } = message;
31
+ if (!request.path.endsWith(KIT_CONNECTION_PATH))
32
+ return;
33
+ refused = new HouseRefusal(KIT_CONNECTION_PATH, response.statusCode, header(response.headers, REFUSAL_HEADER) || response.statusText);
34
+ });
35
+ export function holdConnection(handlers) {
36
+ let connection = null;
37
+ let socket = null;
38
+ let failures = 0;
39
+ let stopping = false;
40
+ const connect = async () => {
41
+ const { house, credential } = (await readEnrolment());
42
+ if (socket !== null || unserved() || stopping)
43
+ return;
44
+ refused = null;
45
+ const opening = new WebSocket(relayed(connectionUrl(house)), {
46
+ protocols: [SUBPROTOCOL],
47
+ headers: { authorization: `Bearer ${credential}` },
48
+ });
49
+ socket = opening;
50
+ let opened = false;
51
+ let silence = null;
52
+ const closed = (event) => {
53
+ silence?.stop();
54
+ silence = null;
55
+ if (socket === opening)
56
+ socket = null;
57
+ if (connection === opening)
58
+ connection = null;
59
+ handlers.closed();
60
+ process.stderr.write(`kit: connection closed ${event.code} ${event.reason}\n`);
61
+ if (stopping)
62
+ return;
63
+ if (event.reason === 'replaced')
64
+ end(REPLACED);
65
+ if (event.reason === 'credential_rejected' || refused?.status === 401) {
66
+ void signInAgain(credential);
67
+ return;
68
+ }
69
+ if (refused !== null)
70
+ endUnserved(refused.text);
71
+ if (!opened && refused !== null)
72
+ process.stderr.write(`kit: ${refused.message}\n`);
73
+ // A closed connection reopens in one to three seconds, spread so Kit processes 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.
74
+ setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
75
+ };
76
+ opening.onopen = () => {
77
+ opened = true;
78
+ failures = 0;
79
+ connection = opening;
80
+ silence = new Silence(CONNECTION_SILENCE_MS, () => {
81
+ if (connection !== opening)
82
+ return;
83
+ connection = null;
84
+ opening.onclose = null;
85
+ opening.close();
86
+ closed(new CloseEvent('close', { code: 1006, reason: 'heartbeat_missed' }));
87
+ });
88
+ silence.heard();
89
+ handlers.opened();
90
+ };
91
+ opening.onmessage = (event) => {
92
+ silence?.heard();
93
+ const arrived = JSON.parse(String(event.data));
94
+ if (arrived.type === 'input')
95
+ handlers.call(arrived);
96
+ else if (arrived.type !== 'beat')
97
+ handlers.oneWayCall(arrived);
98
+ };
99
+ opening.onerror = () => undefined;
100
+ opening.onclose = closed;
101
+ };
102
+ void connect();
103
+ return {
104
+ send(oneWayCall) {
105
+ if (connection === null || connection.readyState !== WebSocket.OPEN)
106
+ return false;
107
+ connection.send(JSON.stringify(oneWayCall));
108
+ return true;
109
+ },
110
+ close() {
111
+ stopping = true;
112
+ const open = socket;
113
+ if (open === null)
114
+ return Promise.resolve();
115
+ const answered = new Promise((resolve) => open.addEventListener('close', () => resolve(), { once: true }));
116
+ open.close();
117
+ return Promise.race([answered, delay(CLOSE_ANSWER_MS)]);
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,106 @@
1
+ import { applied } from '@agentshouse/session-content';
2
+ function filesOf(files) {
3
+ const held = new Map();
4
+ for (const { path, added, removed } of files) {
5
+ const before = held.get(path);
6
+ held.set(path, { added: (before?.added ?? 0) + added, removed: (before?.removed ?? 0) + removed });
7
+ }
8
+ return held;
9
+ }
10
+ function none() {
11
+ return { type: 'counts', commands: 0, edited: 0, other: 0, added: 0, removed: 0, failed: 0 };
12
+ }
13
+ export class Content {
14
+ parts = [];
15
+ emit;
16
+ calls = new Map();
17
+ writing = null;
18
+ stretch = null;
19
+ constructor(emit) {
20
+ this.emit = emit;
21
+ }
22
+ holds(key) {
23
+ return this.calls.has(key);
24
+ }
25
+ write(id, text) {
26
+ if (text === '')
27
+ return;
28
+ if (this.writing !== null && this.writing.id === id) {
29
+ this.apply({ op: 'append', index: this.writing.index, text });
30
+ return;
31
+ }
32
+ this.stretch = null;
33
+ this.writing = { id, index: this.started({ type: 'text', text }) };
34
+ }
35
+ add(part) {
36
+ this.writing = null;
37
+ this.started(part);
38
+ }
39
+ arrived(part) {
40
+ this.started(part);
41
+ }
42
+ call(key, parent, called) {
43
+ const held = this.calls.get(key);
44
+ if (held !== undefined) {
45
+ held.files = filesOf(called.files);
46
+ held.failed = called.failed;
47
+ this.settle(this.tally());
48
+ return;
49
+ }
50
+ if (parent !== null && !this.calls.has(parent))
51
+ return;
52
+ if (parent === null)
53
+ this.writing = null;
54
+ const stretch = parent === null ? this.stretch : this.calls.get(parent).stretch;
55
+ const at = stretch ?? this.parts.length;
56
+ this.calls.set(key, { stretch: at, kind: called.kind, files: filesOf(called.files), failed: called.failed });
57
+ const tallied = this.tally();
58
+ if (stretch === null)
59
+ this.stretch = this.started(tallied.get(at));
60
+ this.settle(tallied);
61
+ }
62
+ operations() {
63
+ return this.parts.map((part, index) => ({ op: 'start', index, part }));
64
+ }
65
+ tally() {
66
+ const stretches = new Map();
67
+ const first = new Set();
68
+ for (const call of this.calls.values()) {
69
+ const counts = stretches.get(call.stretch) ?? none();
70
+ stretches.set(call.stretch, counts);
71
+ if (call.kind === 'command')
72
+ counts.commands += 1;
73
+ if (call.kind === 'other')
74
+ counts.other += 1;
75
+ if (call.failed)
76
+ counts.failed += 1;
77
+ if (call.kind !== 'edit')
78
+ continue;
79
+ if (call.files.size === 0)
80
+ counts.edited += 1;
81
+ for (const [path, lines] of call.files) {
82
+ if (!first.has(path))
83
+ counts.edited += 1;
84
+ first.add(path);
85
+ counts.added += lines.added;
86
+ counts.removed += lines.removed;
87
+ }
88
+ }
89
+ return stretches;
90
+ }
91
+ settle(tallied) {
92
+ for (const [index, counts] of tallied) {
93
+ if (JSON.stringify(counts) !== JSON.stringify(this.parts[index]))
94
+ this.apply({ op: 'set', index, part: counts });
95
+ }
96
+ }
97
+ started(part) {
98
+ const index = this.parts.length;
99
+ this.apply({ op: 'start', index, part });
100
+ return index;
101
+ }
102
+ apply(operation) {
103
+ this.parts = applied(this.parts, operation);
104
+ this.emit(operation);
105
+ }
106
+ }