@agentshouse/kit 0.2.1-c3e4a20bb3183 → 0.2.1-c46722ad48058

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.
@@ -3,13 +3,20 @@ import { createHash } from 'node:crypto';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { request, setGlobalProxyFromEnv } from 'node:http';
5
5
  import { basename, join } from 'node:path';
6
- import { kitHome, readOwnAgent } from './home.js';
6
+ import { HOUSE_REF } from './git.js';
7
+ import { kitHome, readEnrolment, readOwnAgent } from './home.js';
7
8
  import { callHouse, rpc, UNREACHABLE } from './mcp.js';
8
9
  import { refusalOf } from './refusals.js';
10
+ import { relayed } from './relay.js';
11
+ import { parse } from 'yaml';
9
12
  const USAGE = "usage: house <tool> ['<arguments as JSON>']";
10
- const GIT_USAGE = 'usage: house git push [commit] [--owner]';
13
+ const PUSH_USAGE = 'usage: house push [commit] [--owner]';
14
+ const PUSH = "push [commit]: sends the Local copy's committed changes to House";
15
+ const FETCH_USAGE = 'usage: house fetch';
16
+ const FETCH = `fetch: records House's changes on each Local copy's ${HOUSE_REF}`;
11
17
  const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
12
18
  const CLOSED = "this conversation's House connection is closed; nothing to do from here";
19
+ const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
13
20
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
14
21
  const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
15
22
  const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
@@ -41,7 +48,7 @@ function bridged(path, body, headers = { 'content-type': 'application/json' }, t
41
48
  reject(new Error(refused(path, answer.statusCode, text)));
42
49
  });
43
50
  });
44
- sent.on('error', () => reject(new Error(CLOSED)));
51
+ sent.on('error', (error) => reject(new Error(error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
45
52
  sent.end(body instanceof Buffer ? body : JSON.stringify(body));
46
53
  });
47
54
  }
@@ -49,6 +56,7 @@ async function direct(message) {
49
56
  const ownAgent = await readOwnAgent();
50
57
  if (ownAgent === null)
51
58
  throw new Error(UNCONNECTED);
59
+ await readEnrolment();
52
60
  setGlobalProxyFromEnv();
53
61
  const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
54
62
  throw new Error(UNREACHABLE);
@@ -77,11 +85,24 @@ async function localFile(path) {
77
85
  : `${path} is not a readable file`);
78
86
  }
79
87
  }
88
+ async function sent(url, bytes, operation) {
89
+ const headers = { 'content-type': 'application/octet-stream', 'x-house-byte-operation': operation };
90
+ if (socketPath !== undefined)
91
+ return bridged(url, bytes, headers);
92
+ setGlobalProxyFromEnv();
93
+ const answer = await fetch(relayed(url), { method: 'POST', headers, body: bytes }).catch(() => {
94
+ throw new Error(UNREACHABLE);
95
+ });
96
+ const text = await answer.text();
97
+ if (answer.status === 200)
98
+ return text;
99
+ throw new Error(refused(url, answer.status, text));
100
+ }
80
101
  async function upload(path, roomRef, missing) {
81
102
  if (typeof path !== 'string' || path === '')
82
103
  throw new Error(missing);
83
104
  const bytes = await localFile(path);
84
- const declared = JSON.parse(await bridged('/kit/attachments/upload', {
105
+ const declared = parse(await called('upload', {
85
106
  ...(roomRef === undefined ? {} : { room_ref: roomRef }),
86
107
  name: basename(path),
87
108
  bytes: bytes.length,
@@ -89,30 +110,33 @@ async function upload(path, roomRef, missing) {
89
110
  }));
90
111
  if (declared.upload === undefined)
91
112
  return declared.attachment;
92
- const saved = JSON.parse(await bridged(declared.upload.url, bytes, {
93
- 'content-type': 'application/octet-stream',
94
- 'x-house-byte-operation': declared.upload.operation,
95
- }));
113
+ const saved = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
96
114
  if (saved.upload_failure !== undefined)
97
115
  throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
98
116
  return saved.attachment;
99
117
  }
100
- async function gitPush(args) {
118
+ async function push(args) {
101
119
  if (args.includes('--help'))
102
- return GIT_USAGE;
103
- if (args[0] !== 'push')
104
- throw new Error('only house git push [commit] exists; use plain git for the rest');
120
+ return PUSH_USAGE;
105
121
  const owner = args.includes('--owner');
106
- const commit = args.slice(1).find((arg) => arg !== '--owner') ?? 'HEAD';
122
+ const commit = args.find((arg) => arg !== '--owner') ?? 'HEAD';
107
123
  if (owner && socketPath !== undefined)
108
- throw new Error('--owner is not for Agent conversations; run house git push without it');
124
+ throw new Error('--owner is not for Agent conversations; run house push without it');
109
125
  if (!owner && socketPath === undefined)
110
- throw new Error('outside an Agent conversation, house git push needs --owner');
126
+ throw new Error('outside an Agent conversation, house push needs --owner');
111
127
  const pushed = JSON.parse(await bridged('/git/push', { cwd: process.cwd(), commit }, undefined, owner ? join(kitHome(), 'owner.sock') : socketPath));
112
128
  if (pushed.refused)
113
129
  throw new Error(pushed.text);
114
130
  return pushed.text;
115
131
  }
132
+ async function fetched(args) {
133
+ if (args.includes('--help'))
134
+ return FETCH_USAGE;
135
+ const answer = JSON.parse(await bridged('/git/fetch', {}, undefined, socketPath ?? join(kitHome(), 'owner.sock')));
136
+ if (answer.refused)
137
+ throw new Error(answer.text);
138
+ return answer.text;
139
+ }
116
140
  function argumentsOf(argument) {
117
141
  if (argument === undefined)
118
142
  return {};
@@ -128,35 +152,40 @@ function argumentsOf(argument) {
128
152
  return parsed;
129
153
  }
130
154
  async function house([verb, argument]) {
131
- if (verb === undefined || verb === '--help') {
132
- return [USAGE, 'git push [commit]', ...(await tools()).map((tool) => `${tool.name}: ${tool.description}`)].join('\n');
155
+ if (verb === undefined || verb === '--help' || verb === 'help') {
156
+ return [USAGE, 'help', PUSH, FETCH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
133
157
  }
134
158
  if (argument === '--help') {
135
159
  const tool = (await tools()).find((listed) => listed.name === verb);
136
160
  if (tool === undefined)
137
161
  throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
138
- return `${tool.description}\n${JSON.stringify(tool.inputSchema)}`;
162
+ return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
139
163
  }
140
164
  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') });
165
+ if (verb === 'upload') {
166
+ return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload needs "path", a local file') });
143
167
  }
144
- if (socketPath !== undefined && verb === 'append_record' && Array.isArray(args.attachments)) {
168
+ if (verb === 'append_record' && Array.isArray(args.attachments)) {
145
169
  const attachments = [];
146
170
  for (const path of args.attachments) {
147
171
  attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
148
172
  }
149
173
  args.attachments = attachments;
150
174
  }
151
- const result = await mcp('tools/call', { name: verb, arguments: args });
175
+ return called(verb, args);
176
+ }
177
+ async function called(name, args) {
178
+ const result = await mcp('tools/call', { name, arguments: args });
152
179
  const text = result.content.map((content) => content.text).join('\n');
153
180
  if (result.isError === true)
154
181
  throw new Error(text.replace(/\n+$/, ''));
155
182
  return text;
156
183
  }
157
184
  const argv = process.argv.slice(2);
158
- (argv[0] === 'git' ? gitPush(argv.slice(1)) : house(argv)).then((text) => {
185
+ (argv[0] === 'push' ? push(argv.slice(1)) : argv[0] === 'fetch' ? fetched(argv.slice(1)) : house(argv)).then((text) => {
159
186
  process.stdout.write(`${text}\n`);
187
+ if (argv[0] === 'shell')
188
+ process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
160
189
  }, (error) => {
161
190
  process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
162
191
  process.exitCode = 1;
@@ -1,8 +1,10 @@
1
+ import { HOUSE_REF } from './git.js';
1
2
  import { HOW_WE_WORK } from './skills.js';
3
+ const SOURCE_LINE = "From House, not the User's message:";
2
4
  const HOUSE_LINE = 'Work with House through the `house` CLI: run `house --help`.';
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`:';
5
+ const FILE_LINE = 'To give the User a file or a page, upload it with `house upload` and link it; never start a server.';
6
+ const READ_LINE = "Your User's instructions for a Room, if any: `/rooms/private/rooms/<handle>/AGENTS.md`.";
7
+ const COPIES_LINE = `House Local copies; before work run \`house fetch\` and rebase onto \`${HOUSE_REF}\`; after it commit, then \`house push\`:`;
6
8
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
7
9
  const FAILED = /^exit: [1-9]\d*$/;
8
10
  const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
@@ -29,6 +31,6 @@ async function howWeWork(bridge) {
29
31
  return document.replace(/\n$/, '');
30
32
  }
31
33
  export async function instructions(bridge, base, copies) {
32
- const lines = [HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
34
+ const lines = [SOURCE_LINE, HOUSE_LINE, FILE_LINE, READ_LINE, ...(copies.length === 0 ? [] : [COPIES_LINE, ...copies])];
33
35
  return [lines.join('\n'), base, await howWeWork(bridge)].filter((part) => part !== '').join('\n\n');
34
36
  }
package/dist/kit-main.js CHANGED
@@ -1,15 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  import { setGlobalProxyFromEnv } from 'node:http';
3
+ import { answerGitCredential } from './app-git.js';
3
4
  import { login } from './login.js';
5
+ import { logout } from './logout.js';
4
6
  import { resident } from './resident.js';
5
7
  const [command, ...argv] = process.argv.slice(2);
6
8
  setGlobalProxyFromEnv();
7
9
  async function run() {
8
10
  if (command === 'login')
9
11
  return login(argv);
12
+ if (command === 'logout')
13
+ return logout();
10
14
  if (command === 'resident')
11
15
  return resident();
12
- process.stderr.write('usage: kit <login|resident>\n');
16
+ if (command === 'git-credential')
17
+ return answerGitCredential(argv[0]);
18
+ process.stderr.write('usage: kit <login|logout|resident>\n');
13
19
  process.exitCode = 2;
14
20
  }
15
21
  run().catch((error) => {
package/dist/login.js CHANGED
@@ -1,53 +1,20 @@
1
+ import { spawn } from 'node:child_process';
1
2
  import { createHash, randomBytes } from 'node:crypto';
2
- import { createServer } from 'node:http';
3
3
  import { hostname } from 'node:os';
4
- import { createInterface } from 'node:readline/promises';
5
4
  import { parseArgs } from 'node:util';
6
- import { post } from './api.js';
7
- import { forgetOwnAgent, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
5
+ import { post, retrying } from './api.js';
6
+ import { placeAppGit } from './app-git.js';
7
+ import { forgetOwnAgent, readDisconnected, readEnrolment, readOwnAgent, writeEnrolment, writeOwnAgent } from './home.js';
8
8
  import { callHouse, rpc } from './mcp.js';
9
+ import { selectRelay } from './relay.js';
9
10
  const DEFAULT_HOUSE = 'https://agents.house';
10
- function listen() {
11
- return new Promise((resolve, reject) => {
12
- let deliver = () => undefined;
13
- let held = null;
14
- const code = new Promise((settle) => {
15
- deliver = settle;
16
- });
17
- const server = createServer((request, response) => {
18
- const received = new URL(request.url ?? '/', 'http://127.0.0.1').searchParams.get('code');
19
- if (received === null || held !== null) {
20
- response.writeHead(404).end();
21
- return;
22
- }
23
- held = response;
24
- deliver(received);
25
- });
26
- const close = () => {
27
- server.close();
28
- server.closeAllConnections();
29
- };
30
- const port = Number(process.env.HOUSE_KIT_LOGIN_PORT ?? 0);
31
- server.once('error', reject);
32
- server.listen(port, port === 0 ? '127.0.0.1' : '0.0.0.0', () => {
33
- const address = server.address();
34
- if (address === null || typeof address === 'string') {
35
- reject(new Error('the login callback has no port'));
36
- return;
37
- }
38
- resolve({
39
- uri: `http://127.0.0.1:${address.port}/callback`,
40
- code,
41
- answer: (text) => new Promise((written) => {
42
- if (held === null || held.destroyed || !held.socket || held.socket.destroyed)
43
- return written();
44
- held.once('close', () => written());
45
- held.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' }).end(`${text}\n`);
46
- }),
47
- close,
48
- });
49
- });
50
- });
11
+ const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
12
+ // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
13
+ const POLL_INTERVAL_MS = 2000;
14
+ function open(link) {
15
+ spawn(OPENER, [link], { detached: true, stdio: 'ignore' })
16
+ .on('error', () => undefined)
17
+ .unref();
51
18
  }
52
19
  async function accepted(house, credential) {
53
20
  const checked = await callHouse(house, credential, rpc('tools/list', {}));
@@ -57,17 +24,19 @@ async function accepted(house, credential) {
57
24
  return false;
58
25
  throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
59
26
  }
60
- async function typed(question) {
61
- const reader = createInterface({ input: process.stdin, output: process.stdout });
62
- const closed = new Promise((_, reject) => {
63
- reader.once('close', () => reject(new Error('no code was typed')));
64
- });
65
- try {
66
- return (await Promise.race([reader.question(question), closed])).trim();
67
- }
68
- finally {
69
- reader.close();
70
- }
27
+ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private] [--code <code>]
28
+ --house <origin> the House to connect to, ${DEFAULT_HOUSE} unless one is stored
29
+ --environment <id> reconnect this Environment
30
+ --rooms <ref>[,<ref>...] give this Environment only these Rooms
31
+ --no-private give this Environment every Room but your Private Room
32
+ --code <code> connect this machine with a login code
33
+ `;
34
+ function chosenRooms(rooms, noPrivate) {
35
+ if (rooms !== undefined && noPrivate)
36
+ throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
37
+ if (rooms !== undefined)
38
+ return { rooms: { reach: 'selected', refs: rooms.split(',') } };
39
+ return noPrivate ? { rooms: { reach: 'all_but_private' } } : {};
71
40
  }
72
41
  export async function login(argv) {
73
42
  const { values } = parseArgs({
@@ -75,62 +44,66 @@ export async function login(argv) {
75
44
  options: {
76
45
  house: { type: 'string' },
77
46
  environment: { type: 'string' },
78
- manual: { type: 'boolean', default: false },
47
+ rooms: { type: 'string' },
48
+ 'no-private': { type: 'boolean', default: false },
49
+ code: { type: 'string' },
50
+ help: { type: 'boolean', default: false },
79
51
  },
80
52
  });
81
- const enrolled = await readEnrolment();
53
+ if (values.help) {
54
+ process.stdout.write(USAGE);
55
+ return;
56
+ }
57
+ if (values.code !== undefined && values.rooms !== undefined)
58
+ throw new Error('--code cannot be used with --rooms');
59
+ if (values.code !== undefined && values['no-private'])
60
+ throw new Error('--code cannot be used with --no-private');
61
+ if (values.code !== undefined && values.environment !== undefined)
62
+ throw new Error('--code cannot be used with --environment');
63
+ const rooms = chosenRooms(values.rooms, values['no-private']);
64
+ const enrolled = (await readEnrolment()) ?? (await readDisconnected());
65
+ if (values.code !== undefined && enrolled !== null) {
66
+ throw new Error(`--code connects a new machine; this Kit home records Environment ${enrolled.environment}, so run kit login to reconnect it`);
67
+ }
68
+ const relay = process.env.HOUSE_KIT_RELAY || undefined;
69
+ selectRelay(relay);
82
70
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
83
71
  const replaces = process.env.HOUSE_KIT_REPLACES;
84
72
  const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
85
73
  const ownAgent = await readOwnAgent();
86
- const held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
87
- const verifier = randomBytes(32).toString('base64url');
88
- const started = {
89
- ...(environment === undefined
90
- ? { act: 'new_environment', label: hostname(), ...(replaces === undefined ? {} : { replaces }) }
91
- : { act: 'existing_environment', environment_id: environment }),
92
- code_challenge: createHash('sha256').update(verifier).digest('base64url'),
93
- ...(held ? {} : { headless: true }),
94
- };
95
- const exchange = async (code) => {
96
- const exchanged = await post(house, '/kit/token', { code, code_verifier: verifier });
97
- await writeEnrolment({ house, environment: exchanged.environment, credential: exchanged.credential });
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
- }
106
- };
107
- if (values.manual) {
108
- const { start_url } = await post(house, '/kit', {
109
- ...started,
110
- presentation: 'manual',
111
- });
112
- process.stdout.write(`Open this link and confirm: ${start_url}\n`);
113
- await exchange(await typed('Code: '));
114
- return;
74
+ let held = false;
75
+ let exchanged;
76
+ if (values.code !== undefined) {
77
+ exchanged = await post(house, '/kit/token', { code: values.code, label: hostname() });
115
78
  }
116
- const callback = await listen();
117
- try {
118
- const { start_url } = await post(house, '/kit', {
119
- ...started,
120
- presentation: 'loopback',
121
- loopback_uri: callback.uri,
122
- });
123
- process.stdout.write(`Open this link and confirm: ${start_url}\n`);
124
- try {
125
- await exchange(await callback.code);
126
- }
127
- catch (error) {
128
- await callback.answer(`This Environment was not connected: ${error.message}`);
129
- throw error;
130
- }
131
- await callback.answer('This Environment is connected. You can close this tab.');
79
+ else {
80
+ held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
81
+ const verifier = randomBytes(32).toString('base64url');
82
+ const started = await retrying(() => post(house, '/kit', {
83
+ ...(environment === undefined
84
+ ? { act: 'new_environment', label: hostname(), ...(replaces === undefined ? {} : { replaces }) }
85
+ : { act: 'existing_environment', environment_id: environment }),
86
+ ...rooms,
87
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
88
+ ...(held ? {} : { headless: true }),
89
+ }));
90
+ process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
91
+ open(started.start_url);
92
+ exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
93
+ }
94
+ await writeEnrolment({
95
+ house,
96
+ ...(relay === undefined ? {} : { relay }),
97
+ environment: exchanged.environment,
98
+ credential: exchanged.credential,
99
+ });
100
+ process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
101
+ if (exchanged.headless_credential !== undefined) {
102
+ await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
132
103
  }
133
- finally {
134
- callback.close();
104
+ else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
105
+ await forgetOwnAgent();
106
+ process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
135
107
  }
108
+ await placeAppGit(ownAgent, await readOwnAgent());
136
109
  }
package/dist/logout.js ADDED
@@ -0,0 +1,21 @@
1
+ import { HouseRefusal, post } from './api.js';
2
+ import { forgetAppGit } from './app-git.js';
3
+ import { forgetEnrolment, forgetOwnAgent, readEnrolment } from './home.js';
4
+ export async function logout() {
5
+ const enrolled = await readEnrolment();
6
+ if (enrolled !== null) {
7
+ try {
8
+ await post(enrolled.house, '/kit/logout', {}, enrolled.credential);
9
+ }
10
+ catch (error) {
11
+ if (!(error instanceof HouseRefusal && error.status === 401))
12
+ throw error;
13
+ }
14
+ await forgetEnrolment(enrolled);
15
+ }
16
+ await forgetAppGit();
17
+ await forgetOwnAgent();
18
+ process.stdout.write(enrolled === null
19
+ ? 'This computer is not connected to House.\n'
20
+ : `Environment ${enrolled.environment} is disconnected; kit login reconnects it.\n`);
21
+ }
package/dist/mcp.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { KIT_VERSION } from './clis.js';
3
+ import { relayed } from './relay.js';
3
4
  const MCP_PROTOCOL_VERSION = '2026-07-28';
4
5
  export const UNREACHABLE = 'House is unreachable; call again in a minute';
5
6
  export function rpc(method, params) {
@@ -21,7 +22,7 @@ export function mcpBody(message, operation) {
21
22
  }
22
23
  export async function callHouse(origin, credential, message, operation = null, signal) {
23
24
  const tool = message.method === 'tools/call' ? String(message.params.name) : null;
24
- const answer = await fetch(new URL('/', origin), {
25
+ const answer = await fetch(relayed(new URL('/', origin)), {
25
26
  method: 'POST',
26
27
  headers: {
27
28
  'content-type': 'application/json',
package/dist/parts.js ADDED
@@ -0,0 +1,64 @@
1
+ export class Parts {
2
+ parts = [];
3
+ context = null;
4
+ emit;
5
+ writing = null;
6
+ planned = null;
7
+ constructor(emit) {
8
+ this.emit = emit;
9
+ }
10
+ write(type, id, text) {
11
+ if (text === '')
12
+ return;
13
+ const last = this.parts.length - 1;
14
+ const part = this.parts[last];
15
+ if (this.writing?.type === type && this.writing.id === id && part?.type === type) {
16
+ part.text += text;
17
+ this.emit({ op: 'append', index: last, text });
18
+ return;
19
+ }
20
+ this.start({ type, text });
21
+ this.writing = { type, id };
22
+ }
23
+ command() {
24
+ const last = this.parts.length - 1;
25
+ const part = this.parts[last];
26
+ if (part?.type !== 'commands') {
27
+ this.start({ type: 'commands', count: 1 });
28
+ return;
29
+ }
30
+ part.count++;
31
+ this.emit({ op: 'count', index: last, count: part.count });
32
+ }
33
+ start(part) {
34
+ this.writing = null;
35
+ this.parts.push(part);
36
+ const index = this.parts.length - 1;
37
+ this.emit({ op: 'start', index, part });
38
+ return index;
39
+ }
40
+ done(index, result) {
41
+ const part = this.parts[index];
42
+ part.status = 'done';
43
+ part.result = result;
44
+ this.emit({ op: 'status', index, status: 'done', result });
45
+ }
46
+ plan(entries) {
47
+ if (this.planned === null) {
48
+ this.planned = this.start({ type: 'plan', entries });
49
+ return;
50
+ }
51
+ this.parts[this.planned].entries = entries;
52
+ this.emit({ op: 'plan', index: this.planned, entries });
53
+ }
54
+ measure(context) {
55
+ this.context = context;
56
+ this.emit({ op: 'context', ...context });
57
+ }
58
+ operations() {
59
+ return [
60
+ ...this.parts.map((part, index) => ({ op: 'start', index, part })),
61
+ ...(this.context === null ? [] : [{ op: 'context', ...this.context }]),
62
+ ];
63
+ }
64
+ }
package/dist/refusals.js CHANGED
@@ -21,6 +21,18 @@ function spoken(text) {
21
21
  const detail = said.indexOf('\n');
22
22
  return { code: head[1], text: said, conflicts: detail === -1 ? [] : conflictCodes(said.slice(detail + 1)) };
23
23
  }
24
+ export function retryable(text) {
25
+ let body;
26
+ try {
27
+ body = JSON.parse(text);
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ const error = body?.error;
33
+ const verdict = error?.retryable ?? error?.data?.retryable;
34
+ return typeof verdict === 'boolean' ? verdict : null;
35
+ }
24
36
  export function refusalOf(text) {
25
37
  let body;
26
38
  try {
package/dist/relay.js ADDED
@@ -0,0 +1,20 @@
1
+ let selected;
2
+ export function selectRelay(relay) {
3
+ selected = relay === undefined || relay === '' ? null : relay;
4
+ }
5
+ function relayOrigin() {
6
+ if (selected !== undefined)
7
+ return selected ?? undefined;
8
+ const ambient = process.env.HOUSE_KIT_RELAY;
9
+ return ambient === undefined || ambient === '' ? undefined : ambient;
10
+ }
11
+ export function relayed(target) {
12
+ const url = new URL(target);
13
+ const relay = relayOrigin();
14
+ if (relay === undefined)
15
+ return url;
16
+ const through = new URL(`${url.host}${url.pathname}${url.search}`, `${relay}/`);
17
+ if (url.protocol === 'wss:' || url.protocol === 'ws:')
18
+ through.protocol = 'wss:';
19
+ return through;
20
+ }