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

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,31 @@
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 GIT_USAGE = 'usage: house git push [commit] [--owner]';
11
+ const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
12
+ const CLOSED = "this conversation's House connection is closed; nothing to do from here";
13
+ const REVOKED = 'this conversation no longer has House access; nothing to do from here';
14
+ const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
15
+ const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
10
16
  const socketPath = process.env.HOUSE_BRIDGE;
17
+ function refused(path, status, text) {
18
+ const refusal = refusalOf(text);
19
+ if (refusal !== null)
20
+ return refusal.text;
21
+ if (status === 401)
22
+ return REVOKED;
23
+ if (URL.canParse(path))
24
+ return `the upload answered ${status}; upload the file again`;
25
+ if (status === 502 && /^[A-Za-z]/.test(text))
26
+ return text;
27
+ return `${path} answered ${status}`;
28
+ }
11
29
  function bridged(path, body, headers = { 'content-type': 'application/json' }, to = socketPath) {
12
30
  return new Promise((resolve, reject) => {
13
31
  const sent = request({ socketPath: to, path, method: 'POST', headers }, (answer) => {
@@ -20,15 +38,28 @@ function bridged(path, body, headers = { 'content-type': 'application/json' }, t
20
38
  if (answer.statusCode === 200)
21
39
  resolve(text);
22
40
  else
23
- reject(new Error(`${path} answered ${answer.statusCode}: ${text}`));
41
+ reject(new Error(refused(path, answer.statusCode, text)));
24
42
  });
25
43
  });
26
- sent.on('error', reject);
44
+ sent.on('error', () => reject(new Error(CLOSED)));
27
45
  sent.end(body instanceof Buffer ? body : JSON.stringify(body));
28
46
  });
29
47
  }
48
+ async function direct(message) {
49
+ const ownAgent = await readOwnAgent();
50
+ if (ownAgent === null)
51
+ throw new Error(UNCONNECTED);
52
+ setGlobalProxyFromEnv();
53
+ const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
54
+ throw new Error(UNREACHABLE);
55
+ });
56
+ if (answer.status === 200)
57
+ return answer.text;
58
+ throw new Error(answer.status === 401 ? DISCONNECTED : (refusalOf(answer.text)?.text ?? `House answered ${answer.status}`));
59
+ }
30
60
  async function mcp(method, params) {
31
- const answer = JSON.parse(await bridged('/', { jsonrpc: '2.0', id: 1, method, params }));
61
+ const message = rpc(method, params);
62
+ const answer = JSON.parse(socketPath === undefined ? await direct(message) : await bridged('/', message));
32
63
  if (answer.error !== undefined)
33
64
  throw new Error(answer.error.message);
34
65
  return answer.result;
@@ -36,29 +67,45 @@ async function mcp(method, params) {
36
67
  async function tools() {
37
68
  return (await mcp('tools/list', {})).tools;
38
69
  }
39
- async function upload(path, roomRef) {
40
- const bytes = await readFile(path);
70
+ async function localFile(path) {
71
+ try {
72
+ return await readFile(path);
73
+ }
74
+ catch (error) {
75
+ throw new Error(error.code === 'EISDIR'
76
+ ? `${path} is a folder; upload one file at a time`
77
+ : `${path} is not a readable file`);
78
+ }
79
+ }
80
+ async function upload(path, roomRef, missing) {
81
+ if (typeof path !== 'string' || path === '')
82
+ throw new Error(missing);
83
+ const bytes = await localFile(path);
41
84
  const declared = JSON.parse(await bridged('/kit/attachments/upload', {
42
85
  ...(roomRef === undefined ? {} : { room_ref: roomRef }),
43
- version: randomUUID(),
44
86
  name: basename(path),
45
87
  bytes: bytes.length,
46
88
  sha256: createHash('sha256').update(bytes).digest('hex'),
47
89
  }));
48
- return bridged(declared.upload.url, bytes, {
90
+ if (declared.upload === undefined)
91
+ return declared.attachment;
92
+ const saved = JSON.parse(await bridged(declared.upload.url, bytes, {
49
93
  'content-type': 'application/octet-stream',
50
94
  'x-house-byte-operation': declared.upload.operation,
51
- });
95
+ }));
96
+ if (saved.upload_failure !== undefined)
97
+ throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
98
+ return saved.attachment;
52
99
  }
53
100
  async function gitPush(args) {
54
101
  if (args.includes('--help'))
55
102
  return GIT_USAGE;
56
103
  if (args[0] !== 'push')
57
- throw new Error(GIT_USAGE);
104
+ throw new Error('only house git push [commit] exists; use plain git for the rest');
58
105
  const owner = args.includes('--owner');
59
106
  const commit = args.slice(1).find((arg) => arg !== '--owner') ?? 'HEAD';
60
107
  if (owner && socketPath !== undefined)
61
- throw new Error('house git push --owner runs outside an Agent conversation');
108
+ throw new Error('--owner is not for Agent conversations; run house git push without it');
62
109
  if (!owner && socketPath === undefined)
63
110
  throw new Error('outside an Agent conversation, house git push needs --owner');
64
111
  const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
@@ -66,42 +113,51 @@ async function gitPush(args) {
66
113
  throw new Error(pushed.text);
67
114
  return pushed.text;
68
115
  }
116
+ function argumentsOf(argument) {
117
+ if (argument === undefined)
118
+ return {};
119
+ let parsed;
120
+ try {
121
+ parsed = JSON.parse(argument);
122
+ }
123
+ catch {
124
+ throw new Error(ARGUMENTS);
125
+ }
126
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
127
+ throw new Error(ARGUMENTS);
128
+ return parsed;
129
+ }
69
130
  async function house([verb, argument]) {
70
131
  if (verb === undefined || verb === '--help') {
71
- return [USAGE, `git push [commit]: ${GIT_HELP}`, ...(await tools()).map((tool) => `${tool.name}: ${tool.description}`)].join('\n');
132
+ return [USAGE, 'git push [commit]', ...(await tools()).map((tool) => `${tool.name}: ${tool.description}`)].join('\n');
72
133
  }
73
134
  if (argument === '--help') {
74
135
  const tool = (await tools()).find((listed) => listed.name === verb);
75
136
  if (tool === undefined)
76
- throw new Error(`House has no tool ${verb}`);
77
- return `${tool.description}\n${JSON.stringify(tool.inputSchema, null, 2)}`;
137
+ throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
138
+ return `${tool.description}\n${JSON.stringify(tool.inputSchema)}`;
139
+ }
140
+ const args = argumentsOf(argument);
141
+ if (socketPath !== undefined && verb === 'upload_attachment') {
142
+ return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload_attachment needs "path", a local file') });
78
143
  }
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)) {
144
+ if (socketPath !== undefined && verb === 'append_record' && Array.isArray(args.attachments)) {
83
145
  const attachments = [];
84
146
  for (const path of args.attachments) {
85
- attachments.push(JSON.parse(await upload(String(path), args.room_ref)).attachment);
147
+ attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
86
148
  }
87
149
  args.attachments = attachments;
88
150
  }
89
151
  const result = await mcp('tools/call', { name: verb, arguments: args });
90
152
  const text = result.content.map((content) => content.text).join('\n');
91
153
  if (result.isError === true)
92
- throw new Error(text);
154
+ throw new Error(text.replace(/\n+$/, ''));
93
155
  return text;
94
156
  }
95
157
  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');
158
+ (argv[0] === 'git' ? gitPush(argv.slice(1)) : house(argv)).then((text) => {
159
+ process.stdout.write(`${text}\n`);
160
+ }, (error) => {
161
+ process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
98
162
  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
- }
163
+ });
@@ -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 git 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/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, 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) => {
@@ -71,18 +80,29 @@ export async function login(argv) {
71
80
  });
72
81
  const enrolled = await readEnrolment();
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/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
@@ -8,11 +8,12 @@ import { Agents } from './agents.js';
8
8
  import { house } from './api.js';
9
9
  import { received } from './bridge.js';
10
10
  import { Conversations } from './conversations.js';
11
- import { WorkingCopies } from './copies.js';
12
- import { kitHome, readEnrolment } from './home.js';
11
+ import { LocalCopies } from './copies.js';
12
+ import { agentBase, kitHome, readEnrolment } from './home.js';
13
13
  import { SignIns } from './sign-in.js';
14
14
  import { placeSkillSet } from './skills.js';
15
15
  import { holdStream } from './stream.js';
16
+ import { Updates } from './update.js';
16
17
  function report(error) {
17
18
  process.stderr.write(`kit: ${error instanceof Error ? error.message : String(error)}\n`);
18
19
  }
@@ -56,9 +57,10 @@ export async function resident() {
56
57
  return;
57
58
  }
58
59
  await placeSkillSet();
60
+ await mkdir(agentBase(), { recursive: true });
59
61
  process.env.HOUSE_KIT_RESIDENT = String(process.pid);
60
62
  const agents = new Agents(house);
61
- const copies = new WorkingCopies(house);
63
+ const copies = new LocalCopies(house);
62
64
  await copies.load();
63
65
  await installShim();
64
66
  await serveOwner(copies);
@@ -82,6 +84,7 @@ export async function resident() {
82
84
  changed,
83
85
  });
84
86
  const signIns = new SignIns(house, agents, changed);
87
+ const updates = new Updates(house);
85
88
  for (const signal of ['SIGTERM', 'SIGINT']) {
86
89
  process.once(signal, () => {
87
90
  killDescendants();
@@ -89,6 +92,7 @@ export async function resident() {
89
92
  });
90
93
  }
91
94
  await house.deliver('/kit/restarted', {}).catch(report);
95
+ await updates.resumed().catch(report);
92
96
  logged(agents.refresh());
93
97
  stream = holdStream({
94
98
  opened: () => {
@@ -99,7 +103,7 @@ export async function resident() {
99
103
  frame: (arrived) => {
100
104
  if (arrived.type === 'work_available' && arrived.subject === 'agents')
101
105
  logged(agents.refresh());
102
- if (arrived.type === 'work_available' && arrived.subject === 'working_copy')
106
+ if (arrived.type === 'work_available' && arrived.subject === 'local_copy')
103
107
  logged(copies.select());
104
108
  if (arrived.type === 'entries') {
105
109
  copies.entries(arrived);
@@ -108,6 +112,8 @@ export async function resident() {
108
112
  reported = false;
109
113
  if (arrived.kind === 'sign_in')
110
114
  signIns.start(arrived);
115
+ else if (arrived.kind === 'update')
116
+ updates.start(arrived);
111
117
  else
112
118
  conversations.input(arrived);
113
119
  }
@@ -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), '');
package/dist/stream.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { retryDelay } from './api.js';
1
2
  import { readEnrolment } from './home.js';
2
3
  const SUBPROTOCOL = 'house.kit.stream.1';
3
4
  function streamUrl(house) {
@@ -29,9 +30,7 @@ export function holdStream(handlers) {
29
30
  if (socket === opening)
30
31
  socket = null;
31
32
  process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
32
- const delay = opened
33
- ? 1000 + Math.random() * 2000
34
- : Math.min(30_000, 1000 * 2 ** failures++);
33
+ const delay = opened ? 1000 + Math.random() * 2000 : retryDelay(failures++);
35
34
  setTimeout(() => void connect(), delay);
36
35
  };
37
36
  };