@agentshouse/kit 0.2.1-cd9cbd8b6428c → 0.2.1-ce0af1aee9a57

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 (138) hide show
  1. package/README.md +46 -46
  2. package/dist/acp.js +102 -108
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +218 -63
  5. package/dist/api.js +34 -2
  6. package/dist/app-git.js +48 -0
  7. package/dist/authority-main.js +3 -3
  8. package/dist/bridge.js +42 -62
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +71 -0
  11. package/dist/chunks.js +49 -0
  12. package/dist/clis.js +169 -95
  13. package/dist/codex-main.js +58 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +63 -0
  16. package/dist/conversations.js +853 -333
  17. package/dist/copies.js +451 -251
  18. package/dist/end.js +33 -0
  19. package/dist/enrol-main.js +7 -1
  20. package/dist/events.js +1057 -0
  21. package/dist/files.js +139 -17
  22. package/dist/git.js +57 -21
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +89 -7
  25. package/dist/house-cli.js +299 -0
  26. package/dist/house-main.js +7 -159
  27. package/dist/instructions.js +7 -11
  28. package/dist/kit-cli.js +65 -0
  29. package/dist/kit-main.js +8 -19
  30. package/dist/login.js +117 -102
  31. package/dist/logout.js +14 -13
  32. package/dist/mcp.js +6 -2
  33. package/dist/placement.js +31 -0
  34. package/dist/refusals.js +12 -0
  35. package/dist/relay.js +33 -2
  36. package/dist/resident.js +138 -61
  37. package/dist/scope.js +214 -0
  38. package/dist/scripts.js +255 -0
  39. package/dist/secret-input.js +5 -2
  40. package/dist/service-main.js +9 -0
  41. package/dist/service.js +55 -0
  42. package/dist/shell.js +3 -0
  43. package/dist/sign-in.js +40 -32
  44. package/dist/silence.js +28 -0
  45. package/dist/skills.js +49 -35
  46. package/dist/transcription.js +131 -40
  47. package/dist/translate.js +19 -16
  48. package/dist/update.js +113 -103
  49. package/dist/wire.js +40 -0
  50. package/dist/work.js +353 -0
  51. package/package.json +22 -20
  52. package/dist/blocks.js +0 -51
  53. package/dist/bootstrap.json +0 -24
  54. package/dist/clis-main.js +0 -23
  55. package/dist/stream.js +0 -47
  56. package/how-we-work.md +0 -23
  57. package/skills/ask-matt/LICENSE +0 -21
  58. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  59. package/skills/ask-matt/SKILL.md +0 -91
  60. package/skills/ask-matt/agents/openai.yaml +0 -4
  61. package/skills/code-review/LICENSE +0 -21
  62. package/skills/code-review/SKILL.md +0 -89
  63. package/skills/code-review/agents/openai.yaml +0 -3
  64. package/skills/codebase-design/DEEPENING.md +0 -37
  65. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  66. package/skills/codebase-design/LICENSE +0 -21
  67. package/skills/codebase-design/SKILL.md +0 -116
  68. package/skills/codebase-design/agents/openai.yaml +0 -3
  69. package/skills/diagnosing-bugs/LICENSE +0 -21
  70. package/skills/diagnosing-bugs/SKILL.md +0 -140
  71. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  72. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  73. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  74. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  75. package/skills/domain-modeling/LICENSE +0 -21
  76. package/skills/domain-modeling/SKILL.md +0 -76
  77. package/skills/domain-modeling/agents/openai.yaml +0 -3
  78. package/skills/grill-me/LICENSE +0 -21
  79. package/skills/grill-me/SKILL.md +0 -8
  80. package/skills/grill-me/agents/openai.yaml +0 -4
  81. package/skills/grill-with-docs/LICENSE +0 -21
  82. package/skills/grill-with-docs/SKILL.md +0 -8
  83. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  84. package/skills/grilling/LICENSE +0 -21
  85. package/skills/grilling/SKILL.md +0 -30
  86. package/skills/grilling/agents/openai.yaml +0 -3
  87. package/skills/handoff/LICENSE +0 -21
  88. package/skills/handoff/SKILL.md +0 -17
  89. package/skills/handoff/agents/openai.yaml +0 -4
  90. package/skills/implement/LICENSE +0 -21
  91. package/skills/implement/SKILL.md +0 -16
  92. package/skills/implement/agents/openai.yaml +0 -4
  93. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  94. package/skills/improve-codebase-architecture/LICENSE +0 -21
  95. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  96. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  97. package/skills/prototype/LICENSE +0 -21
  98. package/skills/prototype/LOGIC.md +0 -67
  99. package/skills/prototype/SKILL.md +0 -28
  100. package/skills/prototype/UI.md +0 -112
  101. package/skills/prototype/agents/openai.yaml +0 -3
  102. package/skills/research/LICENSE +0 -21
  103. package/skills/research/SKILL.md +0 -14
  104. package/skills/research/agents/openai.yaml +0 -3
  105. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  106. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  107. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  108. package/skills/tdd/LICENSE +0 -21
  109. package/skills/tdd/SKILL.md +0 -40
  110. package/skills/tdd/agents/openai.yaml +0 -3
  111. package/skills/tdd/mocking.md +0 -59
  112. package/skills/tdd/tests.md +0 -77
  113. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  114. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  115. package/skills/teach/LICENSE +0 -21
  116. package/skills/teach/MISSION-FORMAT.md +0 -31
  117. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  118. package/skills/teach/SKILL.md +0 -141
  119. package/skills/teach/agents/openai.yaml +0 -4
  120. package/skills/to-questionnaire/LICENSE +0 -21
  121. package/skills/to-questionnaire/SKILL.md +0 -55
  122. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  123. package/skills/to-spec/LICENSE +0 -21
  124. package/skills/to-spec/SKILL.md +0 -76
  125. package/skills/to-spec/agents/openai.yaml +0 -4
  126. package/skills/to-tickets/LICENSE +0 -21
  127. package/skills/to-tickets/SKILL.md +0 -106
  128. package/skills/to-tickets/agents/openai.yaml +0 -4
  129. package/skills/wait-what/LICENSE +0 -21
  130. package/skills/wait-what/SKILL.md +0 -8
  131. package/skills/wait-what/agents/openai.yaml +0 -4
  132. package/skills/wayfinder/LICENSE +0 -21
  133. package/skills/wayfinder/SKILL.md +0 -129
  134. package/skills/wayfinder/agents/openai.yaml +0 -4
  135. package/skills/writing-for-agents/LICENSE +0 -21
  136. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  137. package/skills/writing-for-agents/SKILL.md +0 -83
  138. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/clis.js CHANGED
@@ -1,125 +1,188 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { readFileSync } from 'node:fs';
3
- import { readFile } from 'node:fs/promises';
4
- import { userInfo } from 'node:os';
5
- import { join } from 'node:path';
6
- import { kitHome } from './home.js';
7
- const RUNNING_JOB = new Set(['running', 'paused']);
8
- function threadStatus({ method, params }) {
9
- if (method !== 'session/update' || params?.update?.sessionUpdate !== 'session_info_update')
10
- return undefined;
11
- return params.update._meta?.codex?.threadStatus?.type;
12
- }
13
- function asyncTask({ method, params }) {
14
- const update = params?.update;
15
- if (method !== 'session/update' || update?.asyncTaskId === undefined)
16
- return null;
17
- if (update.sessionUpdate === 'async_task_spawned')
18
- return { id: update.asyncTaskId, running: true };
19
- if (update.sessionUpdate === 'async_task_state_update' && !RUNNING_JOB.has(update.state ?? '')) {
20
- return { id: update.asyncTaskId, running: false };
2
+ import { randomUUID } from 'node:crypto';
3
+ import { constants, readFileSync } from 'node:fs';
4
+ import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
+ import { homedir, userInfo } from 'node:os';
6
+ import { delimiter, dirname, isAbsolute, join } from 'node:path';
7
+ import { releaseDirectory } from './placement.js';
8
+ import { childEnvironment } from './relay.js';
9
+ const HOUSE_EXECUTABLES = /^host_executable\(name = "house", paths = (\[.*\])\)$/m;
10
+ function houseRule(houses) {
11
+ return `prefix_rule(pattern = ["house"], decision = "allow")\nhost_executable(name = "house", paths = ${JSON.stringify(houses)})\n`;
12
+ }
13
+ const RAW_SUBTYPES = [
14
+ 'background_tasks_changed',
15
+ 'task_started',
16
+ 'task_updated',
17
+ 'task_notification',
18
+ 'task_progress',
19
+ 'session_state_changed',
20
+ 'hook_started',
21
+ 'hook_response',
22
+ ];
23
+ const RAW_TYPES = ['result', 'user', 'assistant', 'rate_limit_event', 'prompt_suggestion'];
24
+ async function executable(path) {
25
+ try {
26
+ await access(path, constants.X_OK);
27
+ return true;
21
28
  }
22
- return null;
29
+ catch {
30
+ return false;
31
+ }
32
+ }
33
+ async function listedHouses(file) {
34
+ let text;
35
+ try {
36
+ text = await readFile(file, 'utf8');
37
+ }
38
+ catch (error) {
39
+ if (error.code === 'ENOENT')
40
+ return [];
41
+ throw error;
42
+ }
43
+ try {
44
+ const listed = JSON.parse(HOUSE_EXECUTABLES.exec(text)?.[1] ?? '[]');
45
+ return Array.isArray(listed) ? listed.filter((house) => typeof house === 'string') : [];
46
+ }
47
+ catch {
48
+ return [];
49
+ }
50
+ }
51
+ export async function allowHouseInCodex(path) {
52
+ const candidates = [...new Set(path.split(delimiter).filter((directory) => isAbsolute(directory)))].map((directory) => join(directory, 'house'));
53
+ const rules = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'rules');
54
+ const file = join(rules, 'house.rules');
55
+ const houses = [];
56
+ for (const house of [...(await listedHouses(file)), ...candidates]) {
57
+ if (!houses.includes(house) && (await executable(house)))
58
+ houses.push(house);
59
+ }
60
+ await mkdir(rules, { recursive: true });
61
+ const temporary = `${file}.${randomUUID()}`;
62
+ await writeFile(temporary, houseRule(houses));
63
+ await rename(temporary, file);
64
+ }
65
+ async function nothing() { }
66
+ function claudeQuestionFields(request) {
67
+ const properties = request.requestedSchema?.properties ?? {};
68
+ return Object.keys(properties).filter((name) => properties[name]._meta?.jetbrains?.air?.customAnswer !== undefined);
69
+ }
70
+ function codexQuestionFields(request) {
71
+ const { _meta, requestedSchema } = request;
72
+ return _meta?.codex === undefined ? [] : (requestedSchema?.required ?? []);
73
+ }
74
+ function answered(error) {
75
+ return typeof error === 'object' && error !== null ? error : {};
23
76
  }
24
- function airPhase({ _meta }) {
25
- const phase = _meta?.jetbrains?.air?.phase;
26
- if (phase === 'commentary')
27
- return 'note';
28
- if (phase === 'final_answer')
29
- return 'answer';
30
- return null;
77
+ function bridgeInClaudeSandbox(bridge) {
78
+ return process.platform === 'darwin' ? { allowUnixSockets: [bridge] } : { allowAllUnixSockets: true };
31
79
  }
32
80
  export const CLIS = {
33
81
  'codex-acp': {
34
82
  bin: 'codex',
35
- minimum: '0.159.1',
83
+ minimum: '0.165.0',
36
84
  install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
37
- adapter: { package: '@agentclientprotocol/codex-acp', bin: 'codex-acp', executable: 'CODEX_PATH', env: {} },
85
+ update: 'codex update',
86
+ adapter: {
87
+ package: '@agentclientprotocol/codex-acp',
88
+ bin: 'codex-acp',
89
+ executable: 'CODEX_PATH',
90
+ env: { CODEX_CONFIG: JSON.stringify({ features: { shell_zsh_fork: true } }) },
91
+ },
38
92
  args: [],
93
+ fullAccess: 'agent-full-access',
94
+ sessionMeta: () => ({}),
95
+ unknownSession: (error) => {
96
+ const { code, data } = answered(error);
97
+ return code === -32603 && typeof data?.details === 'string' && data.details.startsWith('no rollout found');
98
+ },
99
+ allowHouse: allowHouseInCodex,
100
+ questionFields: codexQuestionFields,
39
101
  signedIn: { command: ['login', 'status'] },
40
102
  login: { args: ['login', '--device-auth'], code: 'show' },
41
- queues: false,
42
- turnStarted: (notice) => threadStatus(notice) === 'active',
43
- turnEnded: (notice) => threadStatus(notice) === 'idle',
44
- job: asyncTask,
45
- phase: airPhase,
103
+ air: ['asyncTasks', 'nativeSubagentSessions'],
46
104
  },
47
105
  'claude-agent-acp': {
48
106
  bin: 'claude',
49
- minimum: '2.1.286',
107
+ minimum: '2.1.316',
50
108
  install: 'curl -fsSL https://claude.ai/install.sh | bash',
109
+ update: 'claude update',
51
110
  adapter: {
52
111
  package: '@agentclientprotocol/claude-agent-acp',
53
112
  bin: 'claude-agent-acp',
54
113
  executable: 'CLAUDE_CODE_EXECUTABLE',
55
- env: { CLAUDE_CODE_ENTRYPOINT: 'claude-agent-acp' },
114
+ env: { CLAUDE_CODE_ENTRYPOINT: 'claude-agent-acp', IS_SANDBOX: '1' },
56
115
  },
57
116
  args: [],
117
+ fullAccess: 'bypassPermissions',
118
+ sessionMeta: (bridge) => ({
119
+ claudeCode: {
120
+ options: {
121
+ allowedTools: ['Bash(house:*)'],
122
+ includeHookEvents: true,
123
+ settings: { sandbox: { network: bridgeInClaudeSandbox(bridge) } },
124
+ },
125
+ emitRawSDKMessages: [...RAW_SUBTYPES.map((subtype) => ({ type: 'system', subtype })), ...RAW_TYPES.map((type) => ({ type }))],
126
+ },
127
+ }),
128
+ unknownSession: (error) => answered(error).code === -32002,
129
+ allowHouse: nothing,
130
+ questionFields: claudeQuestionFields,
58
131
  signedIn: { command: ['auth', 'status'] },
59
132
  login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
60
- queues: false,
61
- turnStarted: () => false,
62
- turnEnded: ({ method, params }) => method === 'session/update' &&
63
- params?.update?.sessionUpdate === 'usage_update' &&
64
- params.update._meta?.['_claude/origin'] !== undefined,
65
- job: asyncTask,
66
- phase: () => null,
133
+ air: ['asyncTasks', 'sessionFailure'],
67
134
  },
68
135
  'grok-build': {
69
136
  bin: 'grok',
70
137
  minimum: '1.0.46',
71
138
  install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
139
+ update: 'grok update',
72
140
  adapter: null,
73
- args: ['agent', '--no-leader', 'stdio'],
141
+ args: ['--sandbox', 'off', 'agent', '--always-approve', '--no-leader', 'stdio'],
142
+ fullAccess: null,
143
+ sessionMeta: () => ({}),
144
+ unknownSession: (error) => answered(error).data?.code === 'FS_NOT_FOUND',
145
+ allowHouse: nothing,
146
+ questionFields: () => [],
74
147
  signedIn: { initializeMeta: 'defaultAuthMethodId' },
75
148
  login: { args: ['login', '--device-auth'], code: 'show' },
76
- queues: true,
77
- turnStarted: ({ method, params }) => method === '_x.ai/queue/changed' && params?.runningPromptId !== undefined,
78
- turnEnded: ({ method, params }) => method === '_x.ai/session_notification' && params?.update?.sessionUpdate === 'turn_completed',
79
- job: ({ method, params }) => {
80
- if (method === '_x.ai/task_backgrounded')
81
- return { id: params.update.task_id, running: true };
82
- if (method === '_x.ai/task_completed')
83
- return { id: params.update.task_snapshot.task_id, running: false };
84
- return null;
85
- },
86
- phase: () => null,
149
+ air: ['asyncTasks'],
87
150
  },
88
151
  };
89
152
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
90
- export const KIT_VERSION = KIT_PACKAGE.version;
91
- const PROXY = /^https?_proxy$/i;
153
+ export const KIT_RELEASE = KIT_PACKAGE.version;
92
154
  const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
155
+ // 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.
93
156
  const INSTALL_MS = 15 * 60_000;
157
+ // A login shell or a version read is ended after half a minute, so a profile that waits for input cannot stall the report.
94
158
  const READ_MS = 30_000;
95
159
  const CAUSE_CHARACTERS = 4000;
96
- function prefix(kind) {
97
- return join(kitHome(), 'agents', kind);
98
- }
99
160
  export function adapterCommand(kind) {
100
- return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].adapter.bin);
101
- }
102
- async function installedAdapter(kind) {
103
- try {
104
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].adapter.package, 'package.json');
105
- return JSON.parse(await readFile(manifest, 'utf8')).version;
106
- }
107
- catch {
108
- return null;
109
- }
110
- }
111
- export function withoutProxy() {
112
- return Object.fromEntries(Object.entries(process.env).filter(([name]) => !PROXY.test(name)));
161
+ return join(releaseDirectory(KIT_RELEASE), 'adapters', kind, 'node_modules', '.bin', CLIS[kind].adapter.bin);
113
162
  }
114
163
  export function run(command, args, timeoutMs, detached = false, signal) {
115
164
  return new Promise((resolve) => {
116
165
  const child = spawn(command, args, {
117
166
  stdio: ['ignore', 'pipe', 'pipe'],
118
167
  timeout: timeoutMs,
119
- env: withoutProxy(),
168
+ env: childEnvironment(),
120
169
  detached,
121
- signal,
170
+ signal: detached ? undefined : signal,
122
171
  });
172
+ const stop = () => {
173
+ try {
174
+ process.kill(-child.pid, 'SIGKILL');
175
+ }
176
+ catch { }
177
+ };
178
+ if (detached && signal?.aborted)
179
+ stop();
180
+ if (detached)
181
+ signal?.addEventListener('abort', stop, { once: true });
182
+ const ended = (ran) => {
183
+ signal?.removeEventListener('abort', stop);
184
+ resolve(ran);
185
+ };
123
186
  let stdout = '';
124
187
  let output = '';
125
188
  child.stdout.setEncoding('utf8').on('data', (chunk) => {
@@ -129,26 +192,25 @@ export function run(command, args, timeoutMs, detached = false, signal) {
129
192
  child.stderr.setEncoding('utf8').on('data', (chunk) => {
130
193
  output += chunk;
131
194
  });
132
- child.on('error', (error) => resolve({ status: null, stdout, output: error.message }));
133
- child.on('close', (status) => resolve({ status, stdout, output }));
195
+ child.on('error', (error) => ended({ status: null, stdout, output: error.message }));
196
+ child.on('close', (status) => ended({ status, stdout, output }));
134
197
  });
135
198
  }
136
199
  export function failureOf(ran, program) {
137
200
  return ran.output.trim().slice(-CAUSE_CHARACTERS) || `${program} exited with ${ran.status ?? 'a signal'}`;
138
201
  }
139
- export async function installAdapter(kind) {
140
- const adapter = CLIS[kind].adapter;
141
- if (adapter === null)
142
- return null;
143
- const release = KIT_PACKAGE.peerDependencies[adapter.package];
144
- if ((await installedAdapter(kind)) === release)
145
- return null;
146
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--no-save', '--no-audit', '--no-fund', '--omit=optional', `${adapter.package}@${release}`], INSTALL_MS);
147
- return ran.status === 0 ? null : failureOf(ran, 'npm');
202
+ export function adapterArchive(kind) {
203
+ return `${kind}-${KIT_PACKAGE.peerDependencies[CLIS[kind].adapter.package]}.tar.gz`;
204
+ }
205
+ async function bounded(program, work, signal) {
206
+ const deadline = AbortSignal.timeout(INSTALL_MS);
207
+ const ran = await work(signal === undefined ? deadline : AbortSignal.any([signal, deadline]));
208
+ if (deadline.aborted && signal?.aborted !== true)
209
+ return `${program} did not end within ${INSTALL_MS / 1000} seconds`;
210
+ return ran.status === 0 ? null : failureOf(ran, program);
148
211
  }
149
- export async function installCli(kind) {
150
- const ran = await run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true);
151
- return ran.status === 0 ? null : failureOf(ran, 'the install');
212
+ export function installCli(kind, signal) {
213
+ return bounded('the install', (within) => run('bash', ['-o', 'pipefail', '-c', CLIS[kind].install], INSTALL_MS, true, within), signal);
152
214
  }
153
215
  function loginShell() {
154
216
  return process.env.SHELL || userInfo().shell;
@@ -156,20 +218,32 @@ function loginShell() {
156
218
  const FOUND = 'house-kit-cli ';
157
219
  const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
158
220
  const USER_BIN = 'case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$PATH:$HOME/.local/bin" ;; esac; export PATH';
159
- function inLoginShell(script, argument = '') {
160
- return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], READ_MS, true);
221
+ function inLoginShell(script, argument = '', signal, timeoutMs = READ_MS) {
222
+ return run(loginShell(), ['-l', '-i', '-c', `exec /bin/sh -c '${USER_BIN}; ${script}' sh ${argument}`], timeoutMs, true, signal);
161
223
  }
162
- export async function locate(kind) {
163
- const ran = await inLoginShell(LOOKUP, CLIS[kind].bin);
224
+ export async function onLoginPath(program, signal) {
225
+ const ran = await inLoginShell(LOOKUP, program, signal);
164
226
  return ran.stdout.split('\n').findLast((line) => line.startsWith(FOUND))?.slice(FOUND.length) ?? null;
165
227
  }
228
+ export function locate(kind, signal) {
229
+ return onLoginPath(CLIS[kind].bin, signal);
230
+ }
231
+ export function updateCli(kind) {
232
+ return bounded('the update', (within) => inLoginShell(CLIS[kind].update, '', within, INSTALL_MS));
233
+ }
166
234
  export async function loginPath() {
167
235
  const marker = 'house-kit-path ';
168
236
  const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
169
237
  return ran.stdout.split('\n').findLast((line) => line.startsWith(marker)).slice(marker.length);
170
238
  }
171
- export async function versionOf(path) {
172
- return VERSION.exec((await run(path, ['--version'], READ_MS)).stdout)?.[0] ?? null;
239
+ export async function writeCodexRule() {
240
+ const shell = await loginPath().catch(() => '');
241
+ await allowHouseInCodex([dirname(process.execPath), process.env.PATH ?? '', shell].join(delimiter)).catch((error) => {
242
+ throw new Error(`Codex's rule for house could not be written: ${error.message}`);
243
+ });
244
+ }
245
+ export async function versionOf(path, signal) {
246
+ return VERSION.exec((await run(path, ['--version'], READ_MS, false, signal)).stdout)?.[0] ?? null;
173
247
  }
174
248
  function numbers(version) {
175
249
  return version.split(/[.-]/, 3).map(Number);
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { connect } from 'node:net';
4
+ const KIT_ANSWER = '"house-kit-';
5
+ const SYNC = 'house-kit/sync';
6
+ function lines(each) {
7
+ let buffer = '';
8
+ return (chunk) => {
9
+ buffer += chunk;
10
+ for (let index = buffer.indexOf('\n'); index >= 0; index = buffer.indexOf('\n')) {
11
+ each(buffer.slice(0, index + 1));
12
+ buffer = buffer.slice(index + 1);
13
+ }
14
+ };
15
+ }
16
+ function answersKit(line) {
17
+ if (!line.includes(KIT_ANSWER))
18
+ return false;
19
+ try {
20
+ const message = JSON.parse(line);
21
+ return message.method === undefined && typeof message.id === 'string' && message.id.startsWith(KIT_ANSWER.slice(1));
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ const args = process.argv.slice(2);
28
+ const serving = args[0] === 'app-server';
29
+ if (process.env.HOUSE_KIT_SANDBOX === '1' && serving)
30
+ args.push('--disable', 'memories');
31
+ const codex = spawn(process.env.HOUSE_KIT_CODEX, args, { stdio: ['pipe', 'pipe', 'inherit'] });
32
+ const stream = serving ? connect(process.env.HOUSE_KIT_CODEX_STREAM) : null;
33
+ stream?.on('error', () => undefined);
34
+ process.stdin.setEncoding('utf8').on('data', lines((line) => codex.stdin.write(line)));
35
+ process.stdin.on('end', () => codex.stdin.end());
36
+ stream?.setEncoding('utf8').on('data', lines((line) => {
37
+ const message = JSON.parse(line);
38
+ if (message.method === SYNC)
39
+ stream.write(`${JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} })}\n`);
40
+ else
41
+ codex.stdin.write(line);
42
+ }));
43
+ codex.stdout.setEncoding('utf8').on('data', lines((line) => {
44
+ stream?.write(line);
45
+ if (answersKit(line) || process.stdout.write(line))
46
+ return;
47
+ codex.stdout.pause();
48
+ process.stdout.once('drain', () => codex.stdout.resume());
49
+ }));
50
+ codex.stdin.on('error', () => undefined);
51
+ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'])
52
+ process.on(signal, () => codex.kill(signal));
53
+ codex.on('exit', (code, signal) => {
54
+ if (signal === null)
55
+ process.exit(code ?? 1);
56
+ process.removeAllListeners(signal);
57
+ process.kill(process.pid, signal);
58
+ });
@@ -0,0 +1,120 @@
1
+ import { subscribe } from 'node:diagnostics_channel';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { HouseRefusal, retryDelay } from './api.js';
4
+ import { end, REPLACED, signInAgain } from './end.js';
5
+ import { readEnrolment } from './home.js';
6
+ import { relayed } from './relay.js';
7
+ import { Silence } from './silence.js';
8
+ import { endUnserved, KIT_WIRE, unserved } from './wire.js';
9
+ const PATH = '/kit/stream';
10
+ const SUBPROTOCOL = `house.kit.stream.${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(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(PATH))
32
+ return;
33
+ refused = new HouseRefusal(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,63 @@
1
+ import { applied } from '@agentshouse/session-content';
2
+ function whole(part, parent) {
3
+ return { ...part, parent };
4
+ }
5
+ export class Content {
6
+ parts = [];
7
+ emit;
8
+ keys = new Map();
9
+ writing = new Map();
10
+ planned = null;
11
+ constructor(emit) {
12
+ this.emit = emit;
13
+ }
14
+ index(key) {
15
+ return this.keys.get(key);
16
+ }
17
+ write(type, id, parent, text) {
18
+ if (text === '')
19
+ return;
20
+ const writing = this.writing.get(parent);
21
+ if (writing?.type === type && writing.id === id) {
22
+ this.apply({ op: 'append', index: writing.index, text });
23
+ return;
24
+ }
25
+ const index = this.add(parent, { type, text });
26
+ this.writing.set(parent, { type, id, index });
27
+ }
28
+ put(key, parent, part) {
29
+ const index = this.keys.get(key);
30
+ if (index === undefined) {
31
+ const added = this.add(parent, part);
32
+ this.keys.set(key, added);
33
+ return added;
34
+ }
35
+ const changed = whole(part, this.parts[index].parent);
36
+ if (JSON.stringify(changed) !== JSON.stringify(this.parts[index]))
37
+ this.apply({ op: 'set', index, part: changed });
38
+ return index;
39
+ }
40
+ plan(entries) {
41
+ if (this.planned === null) {
42
+ this.planned = this.add(null, { type: 'plan', entries });
43
+ return;
44
+ }
45
+ this.apply({ op: 'set', index: this.planned, part: { type: 'plan', parent: null, entries } });
46
+ }
47
+ add(parent, part) {
48
+ this.writing.delete(parent);
49
+ return this.arrived(parent, part);
50
+ }
51
+ arrived(parent, part) {
52
+ const index = this.parts.length;
53
+ this.apply({ op: 'start', index, part: whole(part, parent) });
54
+ return index;
55
+ }
56
+ operations() {
57
+ return this.parts.map((part, index) => ({ op: 'start', index, part }));
58
+ }
59
+ apply(operation) {
60
+ this.parts = applied(this.parts, operation);
61
+ this.emit(operation);
62
+ }
63
+ }