@agentshouse/kit 0.2.1-ccf188e02985d → 0.2.1-cd423aab3dbcc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +35 -42
  2. package/dist/acp.js +66 -12
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +122 -53
  5. package/dist/api.js +15 -10
  6. package/dist/binaries.js +60 -0
  7. package/dist/bridge.js +100 -45
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +54 -0
  11. package/dist/clis.js +62 -50
  12. package/dist/connect.js +121 -0
  13. package/dist/connection.js +120 -0
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +617 -240
  16. package/dist/copies.js +1277 -623
  17. package/dist/earlier.js +273 -0
  18. package/dist/end.js +12 -5
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +206 -38
  21. package/dist/git.js +2 -72
  22. package/dist/grok.js +39 -0
  23. package/dist/home.js +86 -29
  24. package/dist/house-cli.js +180 -189
  25. package/dist/house-main.js +3 -3
  26. package/dist/instructions.js +29 -11
  27. package/dist/keys.js +238 -0
  28. package/dist/kit-cli.js +18 -8
  29. package/dist/kit-main.js +3 -3
  30. package/dist/login.js +36 -22
  31. package/dist/logout.js +2 -2
  32. package/dist/manifest.js +75 -0
  33. package/dist/mcp.js +47 -7
  34. package/dist/owner.js +46 -0
  35. package/dist/placement.js +15 -20
  36. package/dist/refusals.js +50 -23
  37. package/dist/relay.js +21 -0
  38. package/dist/resident.js +141 -90
  39. package/dist/scope.js +15 -4
  40. package/dist/scripts.js +319 -0
  41. package/dist/secret-input.js +1 -1
  42. package/dist/settings.js +247 -0
  43. package/dist/sign-in.js +67 -21
  44. package/dist/silence.js +28 -0
  45. package/dist/skills.js +42 -97
  46. package/dist/supervisor.js +163 -0
  47. package/dist/transcription.js +88 -45
  48. package/dist/update.js +118 -120
  49. package/dist/wire.js +30 -4
  50. package/dist/work.js +27 -2
  51. package/dist/workspace.js +113 -0
  52. package/package.json +25 -22
  53. package/dist/authority-main.js +0 -22
  54. package/dist/bootstrap.json +0 -24
  55. package/dist/chatgpt.js +0 -32
  56. package/dist/clis-main.js +0 -23
  57. package/dist/configure-main.js +0 -6
  58. package/dist/enrol-main.js +0 -10
  59. package/dist/git-main.js +0 -153
  60. package/dist/inputs.js +0 -37
  61. package/dist/parts.js +0 -82
  62. package/dist/service-main.js +0 -9
  63. package/dist/service.js +0 -55
  64. package/dist/stream.js +0 -123
  65. package/dist/translate.js +0 -51
  66. package/how-we-work.md +0 -33
  67. package/skills/ask-matt/LICENSE +0 -21
  68. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  69. package/skills/ask-matt/SKILL.md +0 -97
  70. package/skills/ask-matt/agents/openai.yaml +0 -5
  71. package/skills/code-review/LICENSE +0 -21
  72. package/skills/code-review/SKILL.md +0 -89
  73. package/skills/code-review/agents/openai.yaml +0 -3
  74. package/skills/codebase-design/DEEPENING.md +0 -37
  75. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  76. package/skills/codebase-design/LICENSE +0 -21
  77. package/skills/codebase-design/SKILL.md +0 -114
  78. package/skills/codebase-design/agents/openai.yaml +0 -3
  79. package/skills/diagnosing-bugs/LICENSE +0 -21
  80. package/skills/diagnosing-bugs/SKILL.md +0 -138
  81. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  82. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  83. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  84. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  85. package/skills/domain-modeling/LICENSE +0 -21
  86. package/skills/domain-modeling/SKILL.md +0 -74
  87. package/skills/domain-modeling/agents/openai.yaml +0 -3
  88. package/skills/grill-me/LICENSE +0 -21
  89. package/skills/grill-me/SKILL.md +0 -7
  90. package/skills/grill-me/agents/openai.yaml +0 -5
  91. package/skills/grill-with-docs/LICENSE +0 -21
  92. package/skills/grill-with-docs/SKILL.md +0 -7
  93. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  94. package/skills/grilling/LICENSE +0 -21
  95. package/skills/grilling/SKILL.md +0 -30
  96. package/skills/grilling/agents/openai.yaml +0 -3
  97. package/skills/handoff/LICENSE +0 -21
  98. package/skills/handoff/SKILL.md +0 -16
  99. package/skills/handoff/agents/openai.yaml +0 -5
  100. package/skills/implement/LICENSE +0 -21
  101. package/skills/implement/SKILL.md +0 -17
  102. package/skills/implement/agents/openai.yaml +0 -5
  103. package/skills/implement-spec/LICENSE +0 -21
  104. package/skills/implement-spec/SKILL.md +0 -40
  105. package/skills/implement-spec/agents/openai.yaml +0 -5
  106. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  107. package/skills/improve-codebase-architecture/LICENSE +0 -21
  108. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  109. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  110. package/skills/pr/CREDITS.md +0 -3
  111. package/skills/pr/LICENSE +0 -21
  112. package/skills/pr/SKILL.md +0 -170
  113. package/skills/pr/agents/openai.yaml +0 -3
  114. package/skills/prototype/LICENSE +0 -21
  115. package/skills/prototype/LOGIC.md +0 -67
  116. package/skills/prototype/SKILL.md +0 -26
  117. package/skills/prototype/UI.md +0 -112
  118. package/skills/prototype/agents/openai.yaml +0 -3
  119. package/skills/research/LICENSE +0 -21
  120. package/skills/research/SKILL.md +0 -12
  121. package/skills/research/agents/openai.yaml +0 -3
  122. package/skills/retro/LICENSE +0 -21
  123. package/skills/retro/SKILL.md +0 -44
  124. package/skills/retro/agents/openai.yaml +0 -5
  125. package/skills/tdd/LICENSE +0 -21
  126. package/skills/tdd/SKILL.md +0 -38
  127. package/skills/tdd/agents/openai.yaml +0 -3
  128. package/skills/tdd/mocking.md +0 -59
  129. package/skills/tdd/tests.md +0 -77
  130. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  131. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  132. package/skills/teach/LICENSE +0 -21
  133. package/skills/teach/MISSION-FORMAT.md +0 -31
  134. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  135. package/skills/teach/SKILL.md +0 -140
  136. package/skills/teach/agents/openai.yaml +0 -5
  137. package/skills/to-questionnaire/LICENSE +0 -21
  138. package/skills/to-questionnaire/SKILL.md +0 -54
  139. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  140. package/skills/to-spec/LICENSE +0 -21
  141. package/skills/to-spec/SKILL.md +0 -75
  142. package/skills/to-spec/agents/openai.yaml +0 -5
  143. package/skills/to-tickets/LICENSE +0 -21
  144. package/skills/to-tickets/SKILL.md +0 -105
  145. package/skills/to-tickets/agents/openai.yaml +0 -5
  146. package/skills/triage/AGENT-BRIEF.md +0 -207
  147. package/skills/triage/LICENSE +0 -21
  148. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  149. package/skills/triage/SKILL.md +0 -112
  150. package/skills/triage/agents/openai.yaml +0 -5
  151. package/skills/wait-what/LICENSE +0 -21
  152. package/skills/wait-what/SKILL.md +0 -7
  153. package/skills/wait-what/agents/openai.yaml +0 -5
  154. package/skills/wayfinder/LICENSE +0 -21
  155. package/skills/wayfinder/SKILL.md +0 -128
  156. package/skills/wayfinder/agents/openai.yaml +0 -5
  157. package/skills/wizard/LICENSE +0 -21
  158. package/skills/wizard/SKILL.md +0 -44
  159. package/skills/wizard/agents/openai.yaml +0 -3
  160. package/skills/wizard/template.sh +0 -223
  161. package/skills/writing-for-agents/LICENSE +0 -21
  162. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  163. package/skills/writing-for-agents/SKILL.md +0 -81
  164. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/clis.js CHANGED
@@ -2,9 +2,11 @@ import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { constants, readFileSync } from 'node:fs';
4
4
  import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
- import { homedir, userInfo } from 'node:os';
5
+ import { userInfo } from 'node:os';
6
6
  import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
- import { kitHome } from './home.js';
7
+ import { CLAUDE_KEY, CODEX_KEY, GROK_KEY, codexHome } from './keys.js';
8
+ import { releaseDirectory } from './placement.js';
9
+ import { childEnvironment } from './relay.js';
8
10
  const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
9
11
  function houseRule(houses) {
10
12
  return `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`;
@@ -14,10 +16,12 @@ const RAW_SUBTYPES = [
14
16
  'task_started',
15
17
  'task_updated',
16
18
  'task_notification',
19
+ 'task_progress',
17
20
  'session_state_changed',
18
21
  'hook_started',
19
22
  'hook_response',
20
23
  ];
24
+ const RAW_TYPES = ['result', 'user', 'assistant', 'rate_limit_event', 'prompt_suggestion'];
21
25
  async function executable(path) {
22
26
  try {
23
27
  await access(path, constants.X_OK);
@@ -47,7 +51,7 @@ async function listedHouses(file) {
47
51
  }
48
52
  export async function allowHouseInCodex(path) {
49
53
  const candidates = [...new Set(path.split(delimiter).filter((directory) => isAbsolute(directory)))].map((directory) => join(directory, 'house'));
50
- const rules = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'rules');
54
+ const rules = join(codexHome(), 'rules');
51
55
  const file = join(rules, 'house.rules');
52
56
  const houses = [];
53
57
  for (const house of [...(await listedHouses(file)), ...candidates]) {
@@ -60,6 +64,14 @@ export async function allowHouseInCodex(path) {
60
64
  await rename(temporary, file);
61
65
  }
62
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
+ }
63
75
  function answered(error) {
64
76
  return typeof error === 'object' && error !== null ? error : {};
65
77
  }
@@ -68,9 +80,11 @@ function bridgeInClaudeSandbox(bridge) {
68
80
  }
69
81
  export const CLIS = {
70
82
  'codex-acp': {
83
+ name: 'Codex',
71
84
  bin: 'codex',
72
- minimum: '0.159.1',
85
+ minimum: '0.165.0',
73
86
  install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
87
+ update: 'codex update',
74
88
  adapter: {
75
89
  package: '@agentclientprotocol/codex-acp',
76
90
  bin: 'codex-acp',
@@ -84,16 +98,19 @@ export const CLIS = {
84
98
  const { code, data } = answered(error);
85
99
  return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
86
100
  },
87
- renames: true,
88
101
  allowHouse: allowHouseInCodex,
102
+ questionFields: codexQuestionFields,
89
103
  signedIn: { command: ['login', 'status'] },
90
104
  login: { args: ['login', '--device-auth'], code: 'show' },
105
+ key: CODEX_KEY,
91
106
  air: ['asyncTasks', 'nativeSubagentSessions'],
92
107
  },
93
108
  'claude-agent-acp': {
109
+ name: 'Claude Code',
94
110
  bin: 'claude',
95
- minimum: '2.1.286',
111
+ minimum: '2.1.316',
96
112
  install: 'curl -fsSL https://claude.ai/install.sh | bash',
113
+ update: 'claude update',
97
114
  adapter: {
98
115
  package: '@agentclientprotocol/claude-agent-acp',
99
116
  bin: 'claude-agent-acp',
@@ -102,73 +119,63 @@ export const CLIS = {
102
119
  },
103
120
  args: [],
104
121
  fullAccess: 'bypassPermissions',
105
- sessionMeta: (bridge, title) => ({
122
+ sessionMeta: (bridge) => ({
106
123
  claudeCode: {
107
124
  options: {
108
125
  allowedTools: ['Bash(house:*)'],
109
126
  includeHookEvents: true,
110
- title,
111
127
  settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
112
128
  },
113
- emitRawSDKMessages: RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })),
129
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), ...RAW_TYPES.map((type) => ({ type }))],
114
130
  },
115
131
  }),
116
132
  unknownSession: (error) => answered(error).code === -32002,
117
- renames: false,
118
133
  allowHouse: nothing,
134
+ questionFields: claudeQuestionFields,
119
135
  signedIn: { command: ['auth', 'status'] },
120
136
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
137
+ key: CLAUDE_KEY,
121
138
  air: ['asyncTasks', 'sessionFailure'],
122
139
  },
123
140
  'grok-build': {
141
+ name: 'Grok Build',
124
142
  bin: 'grok',
125
143
  minimum: '1.0.46',
126
144
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
145
+ update: 'grok update',
127
146
  adapter: null,
128
147
  args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
129
148
  fullAccess: null,
130
149
  sessionMeta: () => ({}),
131
150
  unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
132
- renames: false,
133
151
  allowHouse: nothing,
134
- signedIn: { initializeMeta: 'defaultAuthMethodId' },
152
+ questionFields: () => [],
153
+ signedIn: { initializeMeta: 'defaultAuthMethodId', apiKey: 'xai.api_key' },
135
154
  login: { args: ['login', '--device-auth'], code: 'show' },
155
+ key: GROK_KEY,
136
156
  air: ['asyncTasks'],
137
157
  },
138
158
  };
139
159
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
140
- export const KIT_VERSION = KIT_PACKAGE.version;
141
- const PROXY = /^https?_proxy$/i;
160
+ export const KIT_RELEASE = KIT_PACKAGE.version;
142
161
  const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
143
- // 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.
144
163
  const INSTALL_MS = 15 * 60_000;
145
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.
146
165
  const READ_MS = 30_000;
147
166
  const CAUSE_CHARACTERS = 4000;
148
- function prefix(kind) {
149
- return join(kitHome(), 'agents', kind);
150
- }
151
167
  export function adapterCommand(kind) {
152
- 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);
153
169
  }
154
- async function installedAdapter(kind) {
155
- try {
156
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].adapter.package, 'package.json');
157
- return JSON.parse(await readFile(manifest, 'utf8')).version;
158
- }
159
- catch {
160
- return null;
161
- }
162
- }
163
- export function withoutProxy() {
164
- 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?.()) };
165
172
  }
166
- export function run(command, args, timeoutMs, detached = false, signal) {
173
+ export function run(command, args, timeoutMs, detached = false, signal, env = childEnvironment()) {
167
174
  return new Promise((resolve) => {
168
175
  const child = spawn(command, args, {
169
176
  stdio: ['ignore', 'pipe', 'pipe'],
170
177
  timeout: timeoutMs,
171
- env: withoutProxy(),
178
+ env,
172
179
  detached,
173
180
  signal: detached ? undefined : signal,
174
181
  });
@@ -202,19 +209,18 @@ export function run(command, args, timeoutMs, detached = false, signal) {
202
209
  export function failureOf(ran, program) {
203
210
  return ran.output.trim().slice(-CAUSE_CHARACTERS) || `${program} exited with ${ran.status ?? 'a signal'}`;
204
211
  }
205
- export async function installAdapter(kind, signal) {
206
- const adapter = CLIS[kind].adapter;
207
- if (adapter === null)
208
- return null;
209
- const release = KIT_PACKAGE.peerDependencies[adapter.package];
210
- if ((await installedAdapter(kind)) === release)
211
- return null;
212
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--cache', join(kitHome(), 'npm-cache'), '--no-save', '--no-audit', '--no-fund', '--omit=optional', `${adapter.package}@${release}`], INSTALL_MS, true, signal);
213
- 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`;
214
+ }
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);
214
221
  }
215
- export async function installCli(kind, signal) {
216
- const ran = await run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, signal);
217
- return ran.status === 0 ? null : failureOf(ran, 'the install');
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);
218
224
  }
219
225
  function loginShell() {
220
226
  return process.env.SHELL || userInfo().shell;
@@ -222,13 +228,19 @@ function loginShell() {
222
228
  const FOUND = 'house-kit-cli ';
223
229
  const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
224
230
  const USER_BIN = 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$PATH:$HOME/.local/bin" ;; esac; export PATH';
225
- function inLoginShell(script, argument = '', signal) {
226
- 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);
227
233
  }
228
- export async function locate(kind, signal) {
229
- const ran = await inLoginShell(LOOKUP, CLIS[kind].bin, signal);
234
+ export async function onLoginPath(program, signal) {
235
+ const ran = await inLoginShell(LOOKUP, program, signal);
230
236
  return ran.stdout.split('\n').findLast((line) => line.startsWith(FOUND))?.slice(FOUND.length) ?? null;
231
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
+ }
232
244
  export async function loginPath() {
233
245
  const marker = 'house-kit-path ';
234
246
  const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
@@ -240,8 +252,8 @@ export async function writeCodexRule() {
240
252
  throw new Error(`Codex's rule for house could not be written: ${error.message}`);
241
253
  });
242
254
  }
243
- export async function versionOf(path, signal) {
244
- return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal)).stdout)?.[0] ?? null;
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;
245
257
  }
246
258
  function numbers(version) {
247
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
+ }