@agentshouse/kit 0.2.1-alpha.9 → 0.2.1-c5262a8cc063d

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.
package/dist/bridge.js CHANGED
@@ -1,17 +1,20 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { once } from 'node:events';
3
+ import { setTimeout as delay } from 'node:timers/promises';
3
4
  import { mkdir } from 'node:fs/promises';
4
5
  import { createServer, request as httpRequest } from 'node:http';
5
6
  import { request as httpsRequest } from 'node:https';
6
- import { delimiter, join } from 'node:path';
7
+ import { delimiter, dirname, join } from 'node:path';
7
8
  import { parse } from 'yaml';
8
- import { KIT_VERSION } from './clis.js';
9
- import { changedPaths, refusalCode, } from './copies.js';
9
+ import { HouseRefusal, retryDelay } from './api.js';
10
+ import { loginPath } from './clis.js';
11
+ import { changedPaths, } from './copies.js';
10
12
  import { kitHome, readEnrolment } from './home.js';
11
- import { operationId } from './operation.js';
12
- const MCP_PROTOCOL_VERSION = '2026-07-28';
13
+ import { callHouse, mcpBody, rpc, UNREACHABLE } from './mcp.js';
14
+ import { operationId, uuidOf } from './operation.js';
15
+ import { refusalOf } from './refusals.js';
13
16
  const MCP_REQUEST_BYTES = 4 * 1024 * 1024;
14
- const FORWARDED = new Set(['/', '/kit/attachments/upload']);
17
+ const ATTACHMENTS = '/kit/attachments/upload';
15
18
  export async function received(request) {
16
19
  let text = '';
17
20
  request.setEncoding('utf8');
@@ -31,16 +34,44 @@ function relay(request, response, target, authorization) {
31
34
  forwarded.on('error', () => response.destroy());
32
35
  request.pipe(forwarded);
33
36
  }
37
+ function refusalIn(text, status) {
38
+ return refusalOf(text) ?? { code: '', text: text === '' ? `House refused it with ${status}` : text, conflicts: [] };
39
+ }
34
40
  function answered(forwarded) {
35
41
  if (forwarded.status >= 500)
36
- throw new Error(`House answered ${forwarded.status}`);
42
+ throw new HouseRefusal('/', forwarded.status, forwarded.text);
37
43
  if (forwarded.status !== 200)
38
- return { refused: { code: refusalCode(forwarded.text), text: forwarded.text } };
44
+ return { refused: refusalIn(forwarded.text, forwarded.status) };
39
45
  const answer = JSON.parse(forwarded.text);
40
46
  if (answer.error !== undefined)
41
- return { refused: { code: refusalCode(answer.error.message), text: answer.error.message } };
47
+ return { refused: refusalIn(answer.error.message, forwarded.status) };
42
48
  const text = answer.result.content.map((content) => content.text).join('\n');
43
- return answer.result.isError === true ? { refused: { code: refusalCode(text), text } } : { text };
49
+ return answer.result.isError === true ? { refused: refusalIn(text, forwarded.status) } : { text };
50
+ }
51
+ function pendingSeconds(forwarded) {
52
+ if (forwarded.status !== 200)
53
+ return null;
54
+ const { result } = JSON.parse(forwarded.text);
55
+ if (result === undefined || result.isError === true)
56
+ return null;
57
+ const text = result.content.map((content) => content.text).join('\n');
58
+ if (!text.startsWith('{"pending":'))
59
+ return null;
60
+ const seconds = JSON.parse(text).pending.retry_after;
61
+ return typeof seconds === 'number' ? seconds : null;
62
+ }
63
+ function resendAfter(forwarded, attempt) {
64
+ if (forwarded === null)
65
+ return retryDelay(attempt);
66
+ if (forwarded.status >= 500)
67
+ return refusalOf(forwarded.text) === null ? retryDelay(attempt) : null;
68
+ const seconds = pendingSeconds(forwarded);
69
+ return seconds === null ? null : seconds * 1000;
70
+ }
71
+ function versioned(conversationId, text) {
72
+ const file = JSON.parse(text);
73
+ const identity = JSON.stringify([conversationId, file.room_ref ?? null, file.name, file.sha256]);
74
+ return JSON.stringify({ ...file, version: uuidOf(createHash('sha256').update(identity).digest(), 8) });
44
75
  }
45
76
  function editAnswer(forwarded) {
46
77
  const answer = answered(forwarded);
@@ -50,44 +81,32 @@ function editAnswer(forwarded) {
50
81
  return {
51
82
  accepted: results.flatMap((result) => [
52
83
  ...(result.from === undefined ? [] : [{ path: result.from, revision: null, content: null }]),
53
- { path: result.path, revision: result.op === 'remove' ? null : result.revision },
84
+ { path: result.path, revision: result.revision ?? null },
54
85
  ]),
55
86
  };
56
87
  }
57
88
  export async function openBridge(house, copies, conversationId, signal) {
89
+ const path = [join(kitHome(), 'shim'), dirname(process.execPath), await loginPath()].join(delimiter);
58
90
  const origin = (await readEnrolment()).house;
59
91
  const { credential } = await house.post(`/kit/conversations/${conversationId}/credential`, {}, signal);
60
92
  const closed = new AbortController();
61
- const body = (message, operation) => JSON.stringify({
62
- ...message,
63
- params: {
64
- ...message.params,
65
- _meta: {
66
- 'io.modelcontextprotocol/protocolVersion': MCP_PROTOCOL_VERSION,
67
- 'io.modelcontextprotocol/clientInfo': { name: '@agentshouse/kit', version: KIT_VERSION },
68
- 'io.modelcontextprotocol/clientCapabilities': {},
69
- ...(operation === null ? {} : { 'agents.house/agent-operation': operation }),
70
- },
71
- },
72
- });
93
+ const sent = (message, operation) => callHouse(origin, credential, message, operation, closed.signal);
73
94
  const send = async (message, operation) => {
74
- const tool = message.method === 'tools/call' ? String(message.params?.name) : null;
75
- const answer = await fetch(new URL('/', origin), {
76
- method: 'POST',
77
- headers: {
78
- 'content-type': 'application/json',
79
- authorization: `Bearer ${credential}`,
80
- accept: 'application/json, text/event-stream',
81
- 'mcp-protocol-version': MCP_PROTOCOL_VERSION,
82
- 'mcp-method': message.method,
83
- ...(tool === null ? {} : { 'mcp-name': tool }),
84
- },
85
- body: body(message, operation),
86
- signal: closed.signal,
87
- });
88
- return { status: answer.status, text: await answer.text() };
95
+ if (operation === null)
96
+ return sent(message, null);
97
+ for (let attempt = 0;; attempt++) {
98
+ const forwarded = await sent(message, operation).catch((error) => {
99
+ if (closed.signal.aborted)
100
+ throw error;
101
+ return null;
102
+ });
103
+ const after = resendAfter(forwarded, attempt);
104
+ if (after === null)
105
+ return forwarded;
106
+ await delay(after, undefined, { signal: closed.signal });
107
+ }
89
108
  };
90
- const call = (name, args) => ({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } });
109
+ const call = (name, args) => rpc('tools/call', { name, arguments: args });
91
110
  const staged = async (operation, changes) => {
92
111
  const bytes = Buffer.from(JSON.stringify({ changes }));
93
112
  const sha256 = createHash('sha256').update(bytes).digest('hex');
@@ -106,24 +125,35 @@ export async function openBridge(house, copies, conversationId, signal) {
106
125
  });
107
126
  const text = await posted.text();
108
127
  if (posted.status >= 500)
109
- throw new Error(`House answered ${posted.status}`);
128
+ throw new HouseRefusal('/', posted.status, text);
110
129
  if (!posted.ok)
111
- return { refused: { code: refusalCode(text), text } };
130
+ return { refused: refusalIn(text, posted.status) };
112
131
  const held = JSON.parse(text).transfer;
113
132
  return { url: held.url, operation: held.operation, bytes: bytes.length, sha256 };
114
133
  };
134
+ let mutations = null;
135
+ const writes = async (tool) => {
136
+ mutations ??= house
137
+ .post('/kit/tools/mutations', {}, closed.signal)
138
+ .then(({ tools }) => new Set(tools.filter((listed) => listed.writes).map((listed) => listed.name)));
139
+ try {
140
+ return (await mutations).has(tool);
141
+ }
142
+ catch (error) {
143
+ mutations = null;
144
+ throw error;
145
+ }
146
+ };
115
147
  const forward = async (path, text) => {
116
148
  if (path === '/') {
117
149
  const message = JSON.parse(text);
118
- const tool = message.method === 'tools/call' ? String(message.params?.name) : null;
119
- const writes = tool !== null &&
120
- (await house.post('/kit/tools/mutations', {}, closed.signal)).tools.some((listed) => listed.name === tool && listed.writes);
121
- return send(message, writes ? operationId() : null);
150
+ const tool = message.method === 'tools/call' ? String(message.params.name) : null;
151
+ return send(message, tool !== null && (await writes(tool)) ? operationId() : null);
122
152
  }
123
153
  const answer = await fetch(new URL(path, origin), {
124
154
  method: 'POST',
125
155
  headers: { 'content-type': 'application/json', authorization: `Bearer ${credential}` },
126
- body: text,
156
+ body: versioned(conversationId, text),
127
157
  signal: closed.signal,
128
158
  });
129
159
  return { status: answer.status, text: await answer.text() };
@@ -133,7 +163,7 @@ export async function openBridge(house, copies, conversationId, signal) {
133
163
  submit: async (operation, changes, held, retain) => {
134
164
  const inline = call('edit', { changes });
135
165
  let upload = held;
136
- if (upload === undefined && Buffer.byteLength(body(inline, operation)) > MCP_REQUEST_BYTES) {
166
+ if (upload === undefined && Buffer.byteLength(mcpBody(inline, operation)) > MCP_REQUEST_BYTES) {
137
167
  const prepared = await staged(operation, changes);
138
168
  if ('refused' in prepared)
139
169
  return prepared;
@@ -152,7 +182,7 @@ export async function openBridge(house, copies, conversationId, signal) {
152
182
  await copies.observed(JSON.parse(text));
153
183
  return { status: 200, text: '{}' };
154
184
  }
155
- return FORWARDED.has(path) ? forward(path, text) : { status: 404, text: '' };
185
+ return path === '/' || path === ATTACHMENTS ? forward(path, text) : { status: 404, text: '' };
156
186
  };
157
187
  const sockets = join(kitHome(), 'bridges');
158
188
  await mkdir(sockets, { recursive: true, mode: 0o700 });
@@ -168,7 +198,11 @@ export async function openBridge(house, copies, conversationId, signal) {
168
198
  response.writeHead(answered.status, { 'content-type': 'application/json' }).end(answered.text);
169
199
  }
170
200
  catch (error) {
171
- response.writeHead(502).end(error instanceof Error ? error.message : String(error));
201
+ if (error instanceof HouseRefusal) {
202
+ response.writeHead(error.status, { 'content-type': 'application/json' }).end(error.text);
203
+ return;
204
+ }
205
+ response.writeHead(502).end(request.url === '/git/push' && error instanceof Error ? error.message : UNREACHABLE);
172
206
  }
173
207
  });
174
208
  bridge.listen(socketPath);
@@ -189,13 +223,13 @@ export async function openBridge(house, copies, conversationId, signal) {
189
223
  return {
190
224
  env: {
191
225
  HOUSE_BRIDGE: socketPath,
192
- PATH: `${join(kitHome(), 'shim')}${delimiter}${process.env.PATH ?? ''}`,
226
+ PATH: path,
193
227
  GIT_CONFIG_COUNT: '1',
194
228
  GIT_CONFIG_KEY_0: `url.${proxy}/app/.insteadOf`,
195
229
  GIT_CONFIG_VALUE_0: app,
196
230
  },
197
231
  tool: async (name, args) => {
198
- const forwarded = await forward('/', JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }));
232
+ const forwarded = await forward('/', JSON.stringify(call(name, args)));
199
233
  if (forwarded.status !== 200)
200
234
  throw new Error(`House refused ${name} with ${forwarded.status}: ${forwarded.text}`);
201
235
  const answer = JSON.parse(forwarded.text);
@@ -0,0 +1,23 @@
1
+ import { setGlobalProxyFromEnv } from 'node:http';
2
+ import { post } from './api.js';
3
+ import { CLIS, below, locate, versionOf } from './clis.js';
4
+ import { readEnrolment } from './home.js';
5
+ setGlobalProxyFromEnv();
6
+ try {
7
+ const { house, credential } = (await readEnrolment());
8
+ const { agents } = await post(house, '/kit/agents/desired', {}, credential);
9
+ for (const kind of agents) {
10
+ const cli = await locate(kind);
11
+ if (cli === null)
12
+ continue;
13
+ const release = await versionOf(cli);
14
+ if (release === null)
15
+ continue;
16
+ const { bin, minimum } = CLIS[kind];
17
+ process.stdout.write(`${[bin, cli, release, minimum, below(release, minimum) ? 'old' : 'current'].join('\t')}\n`);
18
+ }
19
+ }
20
+ catch (error) {
21
+ process.stderr.write(`kit: ${error.message}\n`);
22
+ process.exitCode = 1;
23
+ }
package/dist/clis.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { readFile } from 'node:fs/promises';
4
+ import { userInfo } from 'node:os';
4
5
  import { join } from 'node:path';
5
6
  import { kitHome } from './home.js';
6
7
  const RUNNING_JOB = new Set(['running', 'paused']);
@@ -20,34 +21,55 @@ function asyncTask({ method, params }) {
20
21
  }
21
22
  return null;
22
23
  }
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;
31
+ }
23
32
  export const CLIS = {
24
33
  'codex-acp': {
25
- package: '@agentclientprotocol/codex-acp',
26
- bin: 'codex-acp',
34
+ bin: 'codex',
35
+ minimum: '0.159.1',
36
+ install: 'curl -fsSL https://chatgpt.com/codex/install.sh | sh',
37
+ adapter: { package: '@agentclientprotocol/codex-acp', bin: 'codex-acp', executable: 'CODEX_PATH', env: {} },
27
38
  args: [],
28
- signedIn: { command: ['cli', 'login', 'status'] },
29
- login: { args: ['cli', 'login', '--device-auth'], code: 'show' },
39
+ signedIn: { command: ['login', 'status'] },
40
+ login: { args: ['login', '--device-auth'], code: 'show' },
30
41
  queues: false,
31
42
  turnStarted: (notice) => threadStatus(notice) === 'active',
32
43
  turnEnded: (notice) => threadStatus(notice) === 'idle',
33
44
  job: asyncTask,
45
+ phase: airPhase,
34
46
  },
35
47
  'claude-agent-acp': {
36
- package: '@agentclientprotocol/claude-agent-acp',
37
- bin: 'claude-agent-acp',
48
+ bin: 'claude',
49
+ minimum: '2.1.286',
50
+ install: 'curl -fsSL https://claude.ai/install.sh | bash',
51
+ adapter: {
52
+ package: '@agentclientprotocol/claude-agent-acp',
53
+ bin: 'claude-agent-acp',
54
+ executable: 'CLAUDE_CODE_EXECUTABLE',
55
+ env: { CLAUDE_CODE_ENTRYPOINT: 'claude-agent-acp' },
56
+ },
38
57
  args: [],
39
- signedIn: { command: ['--cli', 'auth', 'status'] },
40
- login: { args: ['--cli', 'auth', 'login', '--claudeai'], code: 'collect' },
58
+ signedIn: { command: ['auth', 'status'] },
59
+ login: { args: ['auth', 'login', '--claudeai'], code: 'collect', rejected: 'Invalid code' },
41
60
  queues: false,
42
61
  turnStarted: () => false,
43
62
  turnEnded: ({ method, params }) => method === 'session/update' &&
44
63
  params?.update?.sessionUpdate === 'usage_update' &&
45
64
  params.update._meta?.['_claude/origin'] !== undefined,
46
65
  job: asyncTask,
66
+ phase: () => null,
47
67
  },
48
68
  'grok-build': {
49
- package: '@xai-official/grok',
50
69
  bin: 'grok',
70
+ minimum: '1.0.46',
71
+ install: 'curl -fsSL https://x.ai/cli/install.sh | bash',
72
+ adapter: null,
51
73
  args: ['agent', '--no-leader', 'stdio'],
52
74
  signedIn: { initializeMeta: 'defaultAuthMethodId' },
53
75
  login: { args: ['login', '--device-auth'], code: 'show' },
@@ -61,23 +83,25 @@ export const CLIS = {
61
83
  return { id: params.update.task_snapshot.task_id, running: false };
62
84
  return null;
63
85
  },
86
+ phase: () => null,
64
87
  },
65
88
  };
66
89
  const KIT_PACKAGE = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
67
90
  export const KIT_VERSION = KIT_PACKAGE.version;
68
91
  const PROXY = /^https?_proxy$/i;
69
- export function pinned(kind) {
70
- return KIT_PACKAGE.peerDependencies[CLIS[kind].package];
71
- }
92
+ const VERSION = /\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?/;
93
+ const INSTALL_MS = 15 * 60_000;
94
+ const READ_MS = 30_000;
95
+ const CAUSE_CHARACTERS = 4000;
72
96
  function prefix(kind) {
73
97
  return join(kitHome(), 'agents', kind);
74
98
  }
75
- export function cliCommand(kind) {
76
- return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].bin);
99
+ export function adapterCommand(kind) {
100
+ return join(prefix(kind), 'node_modules', '.bin', CLIS[kind].adapter.bin);
77
101
  }
78
- export async function installedRelease(kind) {
102
+ async function installedAdapter(kind) {
79
103
  try {
80
- const manifest = join(prefix(kind), 'node_modules', CLIS[kind].package, 'package.json');
104
+ const manifest = join(prefix(kind), 'node_modules', CLIS[kind].adapter.package, 'package.json');
81
105
  return JSON.parse(await readFile(manifest, 'utf8')).version;
82
106
  }
83
107
  catch {
@@ -87,28 +111,74 @@ export async function installedRelease(kind) {
87
111
  export function withoutProxy() {
88
112
  return Object.fromEntries(Object.entries(process.env).filter(([name]) => !PROXY.test(name)));
89
113
  }
90
- export function run(command, args, timeoutMs) {
114
+ export function run(command, args, timeoutMs, detached = false, signal) {
91
115
  return new Promise((resolve) => {
92
- const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs, env: withoutProxy() });
116
+ const child = spawn(command, args, {
117
+ stdio: ['ignore', 'pipe', 'pipe'],
118
+ timeout: timeoutMs,
119
+ env: withoutProxy(),
120
+ detached,
121
+ signal,
122
+ });
123
+ let stdout = '';
93
124
  let output = '';
94
- child.stdout.on('data', (chunk) => {
95
- output += chunk.toString('utf8');
125
+ child.stdout.setEncoding('utf8').on('data', (chunk) => {
126
+ stdout += chunk;
127
+ output += chunk;
96
128
  });
97
- child.stderr.on('data', (chunk) => {
98
- output += chunk.toString('utf8');
129
+ child.stderr.setEncoding('utf8').on('data', (chunk) => {
130
+ output += chunk;
99
131
  });
100
- child.on('error', (error) => resolve({ status: null, output: error.message }));
101
- child.on('close', (status) => resolve({ status, output }));
132
+ child.on('error', (error) => resolve({ status: null, stdout, output: error.message }));
133
+ child.on('close', (status) => resolve({ status, stdout, output }));
102
134
  });
103
135
  }
104
- export async function install(kind) {
105
- const release = pinned(kind);
106
- if ((await installedRelease(kind)) === release)
107
- return release;
108
- const ran = await run('npm', ['install', '--prefix', prefix(kind), '--no-save', '--no-audit', '--no-fund', `${CLIS[kind].package}@${release}`], 15 * 60_000);
109
- if (ran.status !== 0) {
110
- process.stderr.write(`kit: ${kind} did not install: ${ran.output.trim()}\n`);
136
+ export function failureOf(ran, program) {
137
+ return ran.output.trim().slice(-CAUSE_CHARACTERS) || `${program} exited with ${ran.status ?? 'a signal'}`;
138
+ }
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)
111
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');
148
+ }
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');
152
+ }
153
+ function loginShell() {
154
+ return process.env.SHELL || userInfo().shell;
155
+ }
156
+ const FOUND = 'house-kit-cli ';
157
+ const LOOKUP = `found=$(command -v "$1") || exit 0; case $found in /*) ;; *) found=$(pwd -P)/$found ;; esac; printf "${FOUND}%s\\n" "$found"`;
158
+ 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);
161
+ }
162
+ export async function locate(kind) {
163
+ const ran = await inLoginShell(LOOKUP, CLIS[kind].bin);
164
+ return ran.stdout.split('\n').findLast((line) => line.startsWith(FOUND))?.slice(FOUND.length) ?? null;
165
+ }
166
+ export async function loginPath() {
167
+ const marker = 'house-kit-path ';
168
+ const ran = await inLoginShell(`printf "${marker}%s\\n" "$PATH"`);
169
+ return ran.stdout.split('\n').findLast((line) => line.startsWith(marker)).slice(marker.length);
170
+ }
171
+ export async function versionOf(path) {
172
+ return VERSION.exec((await run(path, ['--version'], READ_MS)).stdout)?.[0] ?? null;
173
+ }
174
+ function numbers(version) {
175
+ return version.split(/[.-]/, 3).map(Number);
176
+ }
177
+ export function below(found, minimum) {
178
+ const [have, need] = [numbers(found), numbers(minimum)];
179
+ for (let index = 0; index < 3; index++) {
180
+ if (have[index] !== need[index])
181
+ return have[index] < need[index];
112
182
  }
113
- return installedRelease(kind);
183
+ return found.includes('-') && !minimum.includes('-');
114
184
  }