@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.
@@ -1,13 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { createHash, randomUUID } from 'node:crypto';
2
+ import { createHash } from 'node:crypto';
3
3
  import { readFile } from 'node:fs/promises';
4
- import { request } from 'node:http';
4
+ import { request, setGlobalProxyFromEnv } from 'node:http';
5
5
  import { basename, join } from 'node:path';
6
- import { kitHome } from './home.js';
6
+ import { kitHome, readOwnAgent } from './home.js';
7
+ import { callHouse, rpc, UNREACHABLE } from './mcp.js';
8
+ import { refusalOf } from './refusals.js';
7
9
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
8
- const GIT_HELP = 'Submit a Room commit to House; default HEAD. Use --owner only outside an Agent conversation. Native git push is not a House remote.';
9
- const GIT_USAGE = `usage: house git push [commit] [--owner]\n${GIT_HELP}`;
10
+ const PUSH_USAGE = 'usage: house push [commit] [--owner]';
11
+ const PUSH = "push [commit]: sends the Local copy's committed changes to House";
12
+ const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
13
+ const CLOSED = "this conversation's House connection is closed; nothing to do from here";
14
+ const REVOKED = 'this conversation no longer has House access; nothing to do from here';
15
+ const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
16
+ const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
10
17
  const socketPath = process.env.HOUSE_BRIDGE;
18
+ function refused(path, status, text) {
19
+ const refusal = refusalOf(text);
20
+ if (refusal !== null)
21
+ return refusal.text;
22
+ if (status === 401)
23
+ return REVOKED;
24
+ if (URL.canParse(path))
25
+ return `the upload answered ${status}; upload the file again`;
26
+ if (status === 502 && /^[A-Za-z]/.test(text))
27
+ return text;
28
+ return `${path} answered ${status}`;
29
+ }
11
30
  function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
12
31
  return new Promise((resolve, reject) => {
13
32
  const sent = request({ socketPath: to, path, method: 'POST', headers }, (answer) => {
@@ -20,15 +39,28 @@ function bridged(path, body, headers = { 'content-type': 'application/json' }, t
20
39
  if (answer.statusCode === 200)
21
40
  resolve(text);
22
41
  else
23
- reject(new Error(`${path} answered ${answer.statusCode}: ${text}`));
42
+ reject(new Error(refused(path, answer.statusCode, text)));
24
43
  });
25
44
  });
26
- sent.on('error', reject);
45
+ sent.on('error', () => reject(new Error(CLOSED)));
27
46
  sent.end(body instanceof Buffer ? body : JSON.stringify(body));
28
47
  });
29
48
  }
49
+ async function direct(message) {
50
+ const ownAgent = await readOwnAgent();
51
+ if (ownAgent === null)
52
+ throw new Error(UNCONNECTED);
53
+ setGlobalProxyFromEnv();
54
+ const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
55
+ throw new Error(UNREACHABLE);
56
+ });
57
+ if (answer.status === 200)
58
+ return answer.text;
59
+ throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? `House answered ${answer.status}`));
60
+ }
30
61
  async function mcp(method, params) {
31
- const answer = JSON.parse(await bridged('/', { jsonrpc: '2.0', id: 1, method, params }));
62
+ const message = rpc(method, params);
63
+ const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
32
64
  if (answer.error !== undefined)
33
65
  throw new Error(answer.error.message);
34
66
  return answer.result;
@@ -36,72 +68,95 @@ async function mcp(method, params) {
36
68
  async function tools() {
37
69
  return (await mcp('tools/list', {})).tools;
38
70
  }
39
- async function upload(path, roomRef) {
40
- const bytes = await readFile(path);
71
+ async function localFile(path) {
72
+ try {
73
+ return await readFile(path);
74
+ }
75
+ catch (error) {
76
+ throw new Error(error.code === 'EISDIR'
77
+ ? `${path} is a folder; upload one file at a time`
78
+ : `${path} is not a readable file`);
79
+ }
80
+ }
81
+ async function upload(path, roomRef, missing) {
82
+ if (typeof path !== 'string' || path === '')
83
+ throw new Error(missing);
84
+ const bytes = await localFile(path);
41
85
  const declared = JSON.parse(await bridged('/kit/attachments/upload', {
42
86
  ...(roomRef === undefined ? {} : { room_ref: roomRef }),
43
- version: randomUUID(),
44
87
  name: basename(path),
45
88
  bytes: bytes.length,
46
89
  sha256: createHash('sha256').update(bytes).digest('hex'),
47
90
  }));
48
- return bridged(declared.upload.url, bytes, {
91
+ if (declared.upload === undefined)
92
+ return declared.attachment;
93
+ const saved = JSON.parse(await bridged(declared.upload.url, bytes, {
49
94
  'content-type': 'application/octet-stream',
50
95
  'x-house-byte-operation': declared.upload.operation,
51
- });
96
+ }));
97
+ if (saved.upload_failure !== undefined)
98
+ throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
99
+ return saved.attachment;
52
100
  }
53
- async function gitPush(args) {
101
+ async function push(args) {
54
102
  if (args.includes('--help'))
55
- return GIT_USAGE;
56
- if (args[0] !== 'push')
57
- throw new Error(GIT_USAGE);
103
+ return PUSH_USAGE;
58
104
  const owner = args.includes('--owner');
59
- const commit = args.slice(1).find((arg) => arg !== '--owner') ?? 'HEAD';
105
+ const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
60
106
  if (owner && socketPath !== undefined)
61
- throw new Error('house git push --owner runs outside an Agent conversation');
107
+ throw new Error('--owner is not for Agent conversations; run house push without it');
62
108
  if (!owner && socketPath === undefined)
63
- throw new Error('outside an Agent conversation, house git push needs --owner');
109
+ throw new Error('outside an Agent conversation, house push needs --owner');
64
110
  const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
65
111
  if (pushed.refused)
66
112
  throw new Error(pushed.text);
67
113
  return pushed.text;
68
114
  }
115
+ function argumentsOf(argument) {
116
+ if (argument === undefined)
117
+ return {};
118
+ let parsed;
119
+ try {
120
+ parsed = JSON.parse(argument);
121
+ }
122
+ catch {
123
+ throw new Error(ARGUMENTS);
124
+ }
125
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
126
+ throw new Error(ARGUMENTS);
127
+ return parsed;
128
+ }
69
129
  async function house([verb, argument]) {
70
- if (verb === undefined || verb === '--help') {
71
- return [USAGE, `git push [commit]: ${GIT_HELP}`, ...(await tools()).map((tool) => `${tool.name}: ${tool.description}`)].join('\n');
130
+ if (verb === undefined || verb === '--help' || verb === 'help') {
131
+ return [USAGE, 'help', PUSH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
72
132
  }
73
133
  if (argument === '--help') {
74
134
  const tool = (await tools()).find((listed) => listed.name === verb);
75
135
  if (tool === undefined)
76
- throw new Error(`House has no tool ${verb}`);
77
- return `${tool.description}\n${JSON.stringify(tool.inputSchema, null, 2)}`;
136
+ throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
137
+ return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
138
+ }
139
+ const args = argumentsOf(argument);
140
+ if (socketPath !== undefined && verb === 'upload_attachment') {
141
+ return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload_attachment needs "path", a local file') });
78
142
  }
79
- const args = (argument === undefined ? {} : JSON.parse(argument));
80
- if (verb === 'upload_attachment')
81
- return upload(String(args.path), args.room_ref);
82
- if (verb === 'append_record' && Array.isArray(args.attachments)) {
143
+ if (socketPath !== undefined && verb === 'append_record' && Array.isArray(args.attachments)) {
83
144
  const attachments = [];
84
145
  for (const path of args.attachments) {
85
- attachments.push(JSON.parse(await upload(String(path), args.room_ref)).attachment);
146
+ attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
86
147
  }
87
148
  args.attachments = attachments;
88
149
  }
89
150
  const result = await mcp('tools/call', { name: verb, arguments: args });
90
151
  const text = result.content.map((content) => content.text).join('\n');
91
152
  if (result.isError === true)
92
- throw new Error(text);
153
+ throw new Error(text.replace(/\n+$/, ''));
93
154
  return text;
94
155
  }
95
156
  const argv = process.argv.slice(2);
96
- if (argv[0] !== 'git' && socketPath === undefined) {
97
- process.stderr.write('house: house runs inside an Agent conversation\n');
157
+ (argv[0] === 'push' ? push(argv.slice(1)) : house(argv)).then((text) => {
158
+ process.stdout.write(`${text}\n`);
159
+ }, (error) => {
160
+ process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
98
161
  process.exitCode = 1;
99
- }
100
- else {
101
- (argv[0] === 'git' ? gitPush(argv.slice(1)) : house(argv)).then((text) => {
102
- process.stdout.write(`${text}\n`);
103
- }, (error) => {
104
- process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
105
- process.exitCode = 1;
106
- });
107
- }
162
+ });
@@ -1,33 +1,34 @@
1
- import { readEnrolment } from './home.js';
2
1
  import { HOW_WE_WORK } from './skills.js';
3
2
  const HOUSE_LINE = 'Work with House through the `house` CLI: run `house --help`.';
4
- const FILE_LINE = 'To give the User a file, upload it with `house upload_attachment` and link it in your answer.';
5
- const COPIES_LINE = 'These House paths are Git working copies here; commit in one and run `house git push` to send the commit to House:';
3
+ const FILE_LINE = 'To give the User a file or a page, upload it with `house upload_attachment` and link it; never start a server.';
4
+ const READ_LINE = 'Before working in a Room, read `/private/rooms/<handle>/AGENTS.md`.';
5
+ const COPIES_LINE = 'House Local copies; commit, then `house push`:';
6
6
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
7
+ const FAILED = /^exit: [1-9]\d*$/;
7
8
  const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
9
+ function cutOf(lines) {
10
+ const cut = CUT.exec(lines[0] ?? '');
11
+ return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
12
+ }
8
13
  async function howWeWork(bridge) {
9
14
  let document = '';
10
15
  for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
11
16
  const read = await bridge.tool('shell', { command });
12
17
  const text = read.content.map((content) => content.text).join('\n');
13
18
  const lines = text.split('\n');
14
- let at = lines[5]?.startsWith('authority: ') ? 6 : 5;
15
- if (read.isError === true || lines[2] !== 'exit: 0') {
16
- const refusal = read.isError === true ? text : lines.slice(at).join('\n').replace(/^stderr: /gm, '');
19
+ if (read.isError === true || (FAILED.test(lines[0] ?? '') && lines[1]?.startsWith('stderr: '))) {
20
+ const refusal = read.isError === true ? text : lines.slice(1).join('\n').replace(/^stderr: /gm, '');
17
21
  if (UNREADABLE.test(refusal))
18
22
  return '';
19
23
  throw new Error(refusal);
20
24
  }
21
- const cut = lines[3] === 'truncation: egress' ? CUT.exec(lines[at++] ?? '') : null;
22
- const shown = Buffer.from(`${lines.slice(at).join('\n')}\n`);
23
- document += (cut === null ? shown : shown.subarray(0, Number(cut[1]))).toString();
25
+ const cut = cutOf(lines);
26
+ document += lines.slice(cut === null ? 0 : 1).join('\n');
24
27
  command = cut?.[2];
25
28
  }
26
29
  return document.replace(/\n$/, '');
27
30
  }
28
31
  export async function instructions(bridge, base, copies) {
29
- const app = new URL('/app/new.git', (await readEnrolment()).house).href;
30
- const appLine = `To show the User a page, upload it or push it to an App instead of starting a server; \`git clone ${app}\` starts a new App.`;
31
- const lines = [HOUSE_LINE, FILE_LINE, appLine, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
32
+ const lines = [HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
32
33
  return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
33
34
  }
package/dist/kit-main.js CHANGED
@@ -1,15 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { setGlobalProxyFromEnv } from 'node:http';
3
3
  import { login } from './login.js';
4
+ import { logout } from './logout.js';
4
5
  import { resident } from './resident.js';
5
6
  const [command, ...argv] = process.argv.slice(2);
6
7
  setGlobalProxyFromEnv();
7
8
  async function run() {
8
9
  if (command === 'login')
9
10
  return login(argv);
11
+ if (command === 'logout')
12
+ return logout();
10
13
  if (command === 'resident')
11
14
  return resident();
12
- process.stderr.write('usage: kit <login|resident>\n');
15
+ process.stderr.write('usage: kit <login|logout|resident>\n');
13
16
  process.exitCode = 2;
14
17
  }
15
18
  run().catch((error) => {
package/dist/login.js CHANGED
@@ -4,7 +4,8 @@ import { hostname } from 'node:os';
4
4
  import { createInterface } from 'node:readline/promises';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { post } from './api.js';
7
- import { readEnrolment, writeEnrolment } from './home.js';
7
+ import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
8
+ import { callHouse, rpc } from './mcp.js';
8
9
  const DEFAULT_HOUSE = 'https://agents.house';
9
10
  function listen() {
10
11
  return new Promise((resolve, reject) => {
@@ -48,6 +49,14 @@ function listen() {
48
49
  });
49
50
  });
50
51
  }
52
+ async function accepted(house, credential) {
53
+ const checked = await callHouse(house, credential, rpc('tools/list', {}));
54
+ if (checked.status === 200)
55
+ return true;
56
+ if (checked.status === 401)
57
+ return false;
58
+ throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
59
+ }
51
60
  async function typed(question) {
52
61
  const reader = createInterface({ input: process.stdin, output: process.stdout });
53
62
  const closed = new Promise((_, reject) => {
@@ -69,20 +78,31 @@ export async function login(argv) {
69
78
  manual: { type: 'boolean', default: false },
70
79
  },
71
80
  });
72
- const enrolled = await readEnrolment();
81
+ const enrolled = (await readEnrolment()) ?? (await readDisconnected());
73
82
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
74
- const environment = values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined);
83
+ const replaces = process.env.HOUSE_KIT_REPLACES;
84
+ const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
85
+ const ownAgent = await readOwnAgent();
86
+ const held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
75
87
  const verifier = randomBytes(32).toString('base64url');
76
88
  const started = {
77
89
  ...(environment === undefined
78
- ? { act: 'new_environment', label: hostname() }
90
+ ? { act: 'new_environment', label: hostname(), ...(replaces === undefined ? {} : { replaces }) }
79
91
  : { act: 'existing_environment', environment_id: environment }),
80
92
  code_challenge: createHash('sha256').update(verifier).digest('base64url'),
93
+ ...(held ? {} : { headless: true }),
81
94
  };
82
95
  const exchange = async (code) => {
83
96
  const exchanged = await post(house, '/kit/token', { code, code_verifier: verifier });
84
97
  await writeEnrolment({ house, environment: exchanged.environment, credential: exchanged.credential });
85
98
  process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
99
+ if (exchanged.headless_credential !== undefined) {
100
+ await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
101
+ }
102
+ else if (held && ownAgent.user !== exchanged.user) {
103
+ await forgetOwnAgent();
104
+ process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
105
+ }
86
106
  };
87
107
  if (values.manual) {
88
108
  const { start_url } = await post(house, '/kit', {
package/dist/logout.js ADDED
@@ -0,0 +1,18 @@
1
+ import { HouseRefusal, post } from './api.js';
2
+ import { forgetEnrolment, readEnrolment } from './home.js';
3
+ export async function logout() {
4
+ const enrolled = await readEnrolment();
5
+ if (enrolled === null) {
6
+ process.stdout.write('This computer is not connected to House.\n');
7
+ return;
8
+ }
9
+ try {
10
+ await post(enrolled.house, '/kit/logout', {}, enrolled.credential);
11
+ }
12
+ catch (error) {
13
+ if (!(error instanceof HouseRefusal && error.status === 401))
14
+ throw error;
15
+ }
16
+ await forgetEnrolment(enrolled);
17
+ process.stdout.write(`Environment ${enrolled.environment} is disconnected; kit login reconnects it.\n`);
18
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,38 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { KIT_VERSION } from './clis.js';
3
+ const MCP_PROTOCOL_VERSION = '2026-07-28';
4
+ export const UNREACHABLE = 'House is unreachable; call again in a minute';
5
+ export function rpc(method, params) {
6
+ return { jsonrpc: '2.0', id: randomUUID(), method, params };
7
+ }
8
+ export function mcpBody(message, operation) {
9
+ return JSON.stringify({
10
+ ...message,
11
+ params: {
12
+ ...message.params,
13
+ _meta: {
14
+ 'io.modelcontextprotocol/protocolVersion': MCP_PROTOCOL_VERSION,
15
+ 'io.modelcontextprotocol/clientInfo': { name: '@agentshouse/kit', version: KIT_VERSION },
16
+ 'io.modelcontextprotocol/clientCapabilities': {},
17
+ ...(operation === null ? {} : { 'agents.house/agent-operation': operation }),
18
+ },
19
+ },
20
+ });
21
+ }
22
+ export async function callHouse(origin, credential, message, operation = null, signal) {
23
+ const tool = message.method === 'tools/call' ? String(message.params.name) : null;
24
+ const answer = await fetch(new URL('/', origin), {
25
+ method: 'POST',
26
+ headers: {
27
+ 'content-type': 'application/json',
28
+ authorization: `Bearer ${credential}`,
29
+ accept: 'application/json, text/event-stream',
30
+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,
31
+ 'mcp-method': message.method,
32
+ ...(tool === null ? {} : { 'mcp-name': tool }),
33
+ },
34
+ body: mcpBody(message, operation),
35
+ signal,
36
+ });
37
+ return { status: answer.status, text: await answer.text() };
38
+ }
package/dist/operation.js CHANGED
@@ -1,9 +1,12 @@
1
1
  import { randomBytes } from 'node:crypto';
2
+ export function uuidOf(bytes, version) {
3
+ bytes[6] = (version << 4) | (bytes[6] & 0x0f);
4
+ bytes[8] = 0x80 | (bytes[8] & 0x3f);
5
+ const hex = bytes.toString('hex', 0, 16);
6
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
7
+ }
2
8
  export function operationId() {
3
9
  const bytes = randomBytes(16);
4
10
  bytes.writeUIntBE(Date.now(), 0, 6);
5
- bytes[6] = 0x70 | (bytes[6] & 0x0f);
6
- bytes[8] = 0x80 | (bytes[8] & 0x3f);
7
- const hex = bytes.toString('hex');
8
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
11
+ return uuidOf(bytes, 7);
9
12
  }
@@ -0,0 +1,41 @@
1
+ import { parse } from 'yaml';
2
+ const HEAD = /^([a-z][a-z0-9_]*): \S/;
3
+ function conflictCodes(detail) {
4
+ let parsed;
5
+ try {
6
+ parsed = parse(detail);
7
+ }
8
+ catch {
9
+ return [];
10
+ }
11
+ const conflicts = parsed?.conflicts;
12
+ if (!Array.isArray(conflicts))
13
+ return [];
14
+ return conflicts.flatMap((conflict) => typeof conflict?.code === 'string' ? [conflict.code] : []);
15
+ }
16
+ function spoken(text) {
17
+ const head = HEAD.exec(text);
18
+ if (head === null)
19
+ return null;
20
+ const said = text.replace(/\n+$/, '');
21
+ const detail = said.indexOf('\n');
22
+ return { code: head[1], text: said, conflicts: detail === -1 ? [] : conflictCodes(said.slice(detail + 1)) };
23
+ }
24
+ export function refusalOf(text) {
25
+ let body;
26
+ try {
27
+ body = JSON.parse(text);
28
+ }
29
+ catch {
30
+ return spoken(text);
31
+ }
32
+ const error = body?.error;
33
+ if (typeof error !== 'object' || error === null)
34
+ return null;
35
+ const { code, message, data } = error;
36
+ const said = typeof message === 'string' ? spoken(message) : null;
37
+ if (said !== null)
38
+ return said;
39
+ const named = typeof code === 'string' ? code : typeof data?.code === 'string' ? data.code : null;
40
+ return named === null ? null : { code: named, text: named, conflicts: [] };
41
+ }
package/dist/resident.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { once } from 'node:events';
2
+ import { watch } from 'node:fs';
2
3
  import { mkdir, rm, writeFile } from 'node:fs/promises';
3
4
  import { createServer } from 'node:http';
4
5
  import { extname, join } from 'node:path';
@@ -8,11 +9,12 @@ import { Agents } from './agents.js';
8
9
  import { house } from './api.js';
9
10
  import { received } from './bridge.js';
10
11
  import { Conversations } from './conversations.js';
11
- import { WorkingCopies } from './copies.js';
12
- import { kitHome, readEnrolment } from './home.js';
12
+ import { LocalCopies } from './copies.js';
13
+ import { agentBase, enrolled, kitHome } from './home.js';
13
14
  import { SignIns } from './sign-in.js';
14
15
  import { placeSkillSet } from './skills.js';
15
16
  import { holdStream } from './stream.js';
17
+ import { Updates } from './update.js';
16
18
  function report(error) {
17
19
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
18
20
  }
@@ -49,16 +51,35 @@ async function serveOwner(copies) {
49
51
  server.listen(socketPath);
50
52
  await once(server, 'listening');
51
53
  }
54
+ function connected() {
55
+ return new Promise((resolve) => {
56
+ const watcher = watch(kitHome(), () => {
57
+ if (!enrolled())
58
+ return;
59
+ watcher.close();
60
+ resolve();
61
+ });
62
+ if (!enrolled()) {
63
+ process.stderr.write('kit: this Environment is not connected; run kit login\n');
64
+ return;
65
+ }
66
+ watcher.close();
67
+ resolve();
68
+ });
69
+ }
52
70
  export async function resident() {
53
- if ((await readEnrolment()) === null) {
54
- process.stderr.write('kit: this Environment is not enrolled; run kit login\n');
55
- process.exitCode = 1;
56
- return;
57
- }
71
+ await connected();
72
+ watch(kitHome(), () => {
73
+ if (enrolled())
74
+ return;
75
+ killDescendants();
76
+ process.exit(1);
77
+ });
58
78
  await placeSkillSet();
79
+ await mkdir(agentBase(), { recursive: true });
59
80
  process.env.HOUSE_KIT_RESIDENT = String(process.pid);
60
81
  const agents = new Agents(house);
61
- const copies = new WorkingCopies(house);
82
+ const copies = new LocalCopies(house);
62
83
  await copies.load();
63
84
  await installShim();
64
85
  await serveOwner(copies);
@@ -82,6 +103,7 @@ export async function resident() {
82
103
  changed,
83
104
  });
84
105
  const signIns = new SignIns(house, agents, changed);
106
+ const updates = new Updates(house);
85
107
  for (const signal of ['SIGTERM', 'SIGINT']) {
86
108
  process.once(signal, () => {
87
109
  killDescendants();
@@ -89,6 +111,7 @@ export async function resident() {
89
111
  });
90
112
  }
91
113
  await house.deliver('/kit/restarted', {}).catch(report);
114
+ await updates.resumed().catch(report);
92
115
  logged(agents.refresh());
93
116
  stream = holdStream({
94
117
  opened: () => {
@@ -99,7 +122,7 @@ export async function resident() {
99
122
  frame: (arrived) => {
100
123
  if (arrived.type === 'work_available' && arrived.subject === 'agents')
101
124
  logged(agents.refresh());
102
- if (arrived.type === 'work_available' && arrived.subject === 'working_copy')
125
+ if (arrived.type === 'work_available' && arrived.subject === 'local_copy')
103
126
  logged(copies.select());
104
127
  if (arrived.type === 'entries') {
105
128
  copies.entries(arrived);
@@ -108,6 +131,8 @@ export async function resident() {
108
131
  reported = false;
109
132
  if (arrived.kind === 'sign_in')
110
133
  signIns.start(arrived);
134
+ else if (arrived.kind === 'update')
135
+ updates.start(arrived);
111
136
  else
112
137
  conversations.input(arrived);
113
138
  }
@@ -1,15 +1,17 @@
1
+ import { retryDelay } from './api.js';
1
2
  export async function holdSecretInput(house, subject, steps, waiting) {
2
- while (waiting()) {
3
+ for (let failures = 0; waiting();) {
3
4
  try {
4
5
  const held = await house.post(`/kit/secret-input/${subject}`, { steps });
5
6
  if (held.outcome === 'collected')
6
7
  return held.content;
7
8
  if (held.release !== 'held')
8
9
  return null;
10
+ failures = 0;
9
11
  }
10
12
  catch (error) {
11
13
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
12
- await new Promise((resolve) => setTimeout(resolve, 1000));
14
+ await new Promise((resolve) => setTimeout(resolve, retryDelay(failures++)));
13
15
  }
14
16
  }
15
17
  return null;
package/dist/sign-in.js CHANGED
@@ -1,13 +1,16 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
3
  import { killTree } from './acp.js';
4
- import { CLIS, cliCommand, withoutProxy } from './clis.js';
4
+ import { CLIS, withoutProxy } from './clis.js';
5
5
  import { holdSecretInput } from './secret-input.js';
6
6
  const ESCAPE = /\u001b\[[\d;]*m/g;
7
7
  const LINK = /https:\/\/\S+/;
8
8
  const CODE = /^[A-Z0-9]+-[A-Z0-9]+$/;
9
+ function causeOf(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
9
12
  function logged(error) {
10
- process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
13
+ process.stderr.write(`kit: ${causeOf(error)}\n`);
11
14
  }
12
15
  export class SignIns {
13
16
  house;
@@ -28,7 +31,7 @@ export class SignIns {
28
31
  this.running.add(input.input_id);
29
32
  this.changed();
30
33
  this.login(input)
31
- .then(() => this.agents.report())
34
+ .then(() => this.agents.reread(input.cli))
32
35
  .then(() => this.house.deliver(`/kit/inputs/${input.input_id}/ack`, {}))
33
36
  .catch(logged)
34
37
  .finally(() => {
@@ -37,9 +40,16 @@ export class SignIns {
37
40
  });
38
41
  }
39
42
  async login(input) {
40
- await this.agents.installed();
43
+ let cli;
44
+ try {
45
+ cli = await this.agents.located(input.cli);
46
+ }
47
+ catch (error) {
48
+ process.stderr.write(`kit: the ${input.cli} sign-in failed: ${causeOf(error)}\n`);
49
+ return;
50
+ }
41
51
  const login = CLIS[input.cli].login;
42
- const child = spawn(cliCommand(input.cli), login.args, {
52
+ const child = spawn(cli, login.args, {
43
53
  stdio: ['pipe', 'pipe', 'pipe'],
44
54
  detached: true,
45
55
  env: withoutProxy(),
@@ -54,6 +64,8 @@ export class SignIns {
54
64
  if (plain === '')
55
65
  return;
56
66
  last = plain;
67
+ if (login.code === 'collect' && plain.includes(login.rejected))
68
+ killTree(child);
57
69
  link ??= LINK.exec(plain)?.[0];
58
70
  if (CODE.test(plain))
59
71
  code ??= plain;
package/dist/skills.js CHANGED
@@ -3,11 +3,10 @@ import { cp, lstat, mkdir, readdir, realpath, rm, symlink, writeFile } from 'nod
3
3
  import { homedir } from 'node:os';
4
4
  import { join, relative } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
- import { parse } from 'yaml';
7
6
  import { KIT_VERSION } from './clis.js';
8
- import { refusalCode } from './copies.js';
9
7
  import { kitHome, readConfiguration, readHome, writeHome } from './home.js';
10
- export const HOW_WE_WORK = '/private/library/how-we-work.md';
8
+ import { refusalOf } from './refusals.js';
9
+ export const HOW_WE_WORK = '/private/how-we-work.md';
11
10
  const SKILL_SET = fileURLToPath(new URL('../skills/', import.meta.url));
12
11
  const HOW_WE_WORK_TEXT = readFileSync(new URL('../how-we-work.md', import.meta.url), 'utf8');
13
12
  const RECORD = 'skill-set.json';
@@ -63,20 +62,16 @@ export async function placeSkillSet() {
63
62
  else
64
63
  await rm(join(kitHome(), RECORD), { force: true });
65
64
  }
66
- function documentPresent(refusal) {
67
- const { conflicts } = parse(refusal.slice(refusal.indexOf('\n') + 1));
68
- return conflicts.some((conflict) => conflict.code === 'path_exists');
69
- }
70
65
  export async function createHowWeWork(bridge) {
71
66
  if ((await readHome(RECORD)) === null || (await present(join(kitHome(), CREATED))))
72
67
  return;
73
68
  const created = await bridge.tool('edit', { changes: [{ op: 'create', path: HOW_WE_WORK, content: HOW_WE_WORK_TEXT }] });
74
69
  if (created.isError === true) {
75
70
  const text = created.content.map((content) => content.text).join('\n');
76
- const code = refusalCode(text);
77
- if (UNWRITABLE.has(code))
71
+ const refusal = refusalOf(text);
72
+ if (UNWRITABLE.has(refusal?.code ?? ''))
78
73
  return;
79
- if (code !== 'edit_conflict' || !documentPresent(text))
74
+ if (refusal?.code !== 'edit_conflict' || !refusal.conflicts.includes('path_exists'))
80
75
  throw new Error(text);
81
76
  }
82
77
  await writeFile(join(kitHome(), CREATED), '');