@agentshouse/kit 0.2.1-ce145e9aadbf6 → 0.2.1-cf669c6d1ecbb

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,14 +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
13
  const PUSH_USAGE = 'usage: house push [commit] [--owner]';
11
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}`;
12
17
  const ARGUMENTS = `the arguments are one JSON object in single quotes, like house search '{"query":"invoice"}'`;
13
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";
14
20
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
15
21
  const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
16
22
  const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
@@ -42,7 +48,7 @@ function bridged(path, body, headers = { 'content-type': 'application/json' }, t
42
48
  reject(new Error(refused(path, answer.statusCode, text)));
43
49
  });
44
50
  });
45
- sent.on('error', () => reject(new Error(CLOSED)));
51
+ sent.on('error', (error) => reject(new Error(error.code === 'EPERM' || error.code === 'EACCES' ? SANDBOXED : CLOSED)));
46
52
  sent.end(body instanceof Buffer ? body : JSON.stringify(body));
47
53
  });
48
54
  }
@@ -50,6 +56,7 @@ async function direct(message) {
50
56
  const ownAgent = await readOwnAgent();
51
57
  if (ownAgent === null)
52
58
  throw new Error(UNCONNECTED);
59
+ await readEnrolment();
53
60
  setGlobalProxyFromEnv();
54
61
  const answer = await callHouse(ownAgent.house, ownAgent.credential, message).catch(() => {
55
62
  throw new Error(UNREACHABLE);
@@ -78,11 +85,24 @@ async function localFile(path) {
78
85
  : `${path} is not a readable file`);
79
86
  }
80
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
+ }
81
101
  async function upload(path, roomRef, missing) {
82
102
  if (typeof path !== 'string' || path === '')
83
103
  throw new Error(missing);
84
104
  const bytes = await localFile(path);
85
- const declared = JSON.parse(await bridged('/kit/attachments/upload', {
105
+ const declared = parse(await called('upload', {
86
106
  ...(roomRef === undefined ? {} : { room_ref: roomRef }),
87
107
  name: basename(path),
88
108
  bytes: bytes.length,
@@ -90,10 +110,7 @@ async function upload(path, roomRef, missing) {
90
110
  }));
91
111
  if (declared.upload === undefined)
92
112
  return declared.attachment;
93
- const saved = JSON.parse(await bridged(declared.upload.url, bytes, {
94
- 'content-type': 'application/octet-stream',
95
- 'x-house-byte-operation': declared.upload.operation,
96
- }));
113
+ const saved = JSON.parse(await sent(declared.upload.url, bytes, declared.upload.operation));
97
114
  if (saved.upload_failure !== undefined)
98
115
  throw new Error(`${path} was not saved: ${saved.upload_failure}; call again later`);
99
116
  return saved.attachment;
@@ -112,6 +129,14 @@ async function push(args) {
112
129
  throw new Error(pushed.text);
113
130
  return pushed.text;
114
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
+ }
115
140
  function argumentsOf(argument) {
116
141
  if (argument === undefined)
117
142
  return {};
@@ -128,7 +153,7 @@ function argumentsOf(argument) {
128
153
  }
129
154
  async function house([verb, argument]) {
130
155
  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');
156
+ return [USAGE, 'help', PUSH, FETCH, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
132
157
  }
133
158
  if (argument === '--help') {
134
159
  const tool = (await tools()).find((listed) => listed.name === verb);
@@ -137,25 +162,30 @@ async function house([verb, argument]) {
137
162
  return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
138
163
  }
139
164
  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') });
165
+ if (verb === 'upload') {
166
+ return JSON.stringify({ attachment: await upload(args.path, args.room_ref, 'upload needs "path", a local file') });
142
167
  }
143
- if (socketPath !== undefined && verb === 'append_record' && Array.isArray(args.attachments)) {
168
+ if (verb === 'append_record' && Array.isArray(args.attachments)) {
144
169
  const attachments = [];
145
170
  for (const path of args.attachments) {
146
171
  attachments.push(await upload(path, args.room_ref, 'each attachments entry is the path of a local file'));
147
172
  }
148
173
  args.attachments = attachments;
149
174
  }
150
- 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 });
151
179
  const text = result.content.map((content) => content.text).join('\n');
152
180
  if (result.isError === true)
153
181
  throw new Error(text.replace(/\n+$/, ''));
154
182
  return text;
155
183
  }
156
184
  const argv = process.argv.slice(2);
157
- (argv[0] === 'push' ? push(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) => {
158
186
  process.stdout.write(`${text}\n`);
187
+ if (argv[0] === 'shell')
188
+ process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
159
189
  }, (error) => {
160
190
  process.stderr.write(`house: ${error instanceof Error ? error.message : String(error)}\n`);
161
191
  process.exitCode = 1;
@@ -1,8 +1,10 @@
1
+ import { HOUSE_REF } from './git.js';
1
2
  import { HOW_WE_WORK } from './skills.js';
2
- 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 `/rooms/private/rooms/<handle>/AGENTS.md`.';
5
- const COPIES_LINE = 'House Local copies; commit, then `house push`:';
3
+ const SOURCE_LINE = "From House:";
4
+ const HOUSE_LINE = "Work with House through the `house` CLI: run `house --help`, and `house find_command` for House's guides and formats.";
5
+ const FILE_LINE = 'To give the User a file, upload it with `house upload` and link it; for an App, a Site or a website, follow `house find_command \'{"query":"app"}\'`. Never start a server.';
6
+ const READ_LINE = "Optional per-Room instructions: `/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,5 +1,6 @@
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';
4
5
  import { logout } from './logout.js';
5
6
  import { resident } from './resident.js';
@@ -12,6 +13,8 @@ async function run() {
12
13
  return logout();
13
14
  if (command === 'resident')
14
15
  return resident();
16
+ if (command === 'git-credential')
17
+ return answerGitCredential(argv[0]);
15
18
  process.stderr.write('usage: kit <login|logout|resident>\n');
16
19
  process.exitCode = 2;
17
20
  }
package/dist/login.js CHANGED
@@ -1,53 +1,21 @@
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';
5
+ import { post, retrying } from './api.js';
6
+ import { placeAppGit } from './app-git.js';
7
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';
10
+ import { startService } from './service.js';
9
11
  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
- });
12
+ const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
13
+ // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
14
+ const POLL_INTERVAL_MS = 2000;
15
+ function open(link) {
16
+ spawn(OPENER, [link], { detached: true, stdio: 'ignore' })
17
+ .on('error', () => undefined)
18
+ .unref();
51
19
  }
52
20
  async function accepted(house, credential) {
53
21
  const checked = await callHouse(house, credential, rpc('tools/list', {}));
@@ -57,17 +25,19 @@ async function accepted(house, credential) {
57
25
  return false;
58
26
  throw new Error(`House answered ${checked.status} when Kit checked this computer's own agent's connection: ${checked.text}`);
59
27
  }
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
- }
28
+ const USAGE = `usage: kit login [--house <origin>] [--environment <id>] [--rooms <ref>[,<ref>...] | --no-private] [--code <code>]
29
+ --house <origin> the House to connect to, ${DEFAULT_HOUSE} unless one is stored
30
+ --environment <id> reconnect this Environment
31
+ --rooms <ref>[,<ref>...] give this Environment only these Rooms
32
+ --no-private give this Environment every Room but your Private Room
33
+ --code <code> connect this machine with a login code
34
+ `;
35
+ function chosenRooms(rooms, noPrivate) {
36
+ if (rooms !== undefined && noPrivate)
37
+ throw new Error('--rooms and --no-private are two choices of Rooms; pass one');
38
+ if (rooms !== undefined)
39
+ return { rooms: { reach: 'selected', refs: rooms.split(',') } };
40
+ return noPrivate ? { rooms: { reach: 'all_but_private' } } : {};
71
41
  }
72
42
  export async function login(argv) {
73
43
  const { values } = parseArgs({
@@ -75,62 +45,73 @@ export async function login(argv) {
75
45
  options: {
76
46
  house: { type: 'string' },
77
47
  environment: { type: 'string' },
78
- manual: { type: 'boolean', default: false },
48
+ rooms: { type: 'string' },
49
+ 'no-private': { type: 'boolean', default: false },
50
+ code: { type: 'string' },
51
+ help: { type: 'boolean', default: false },
79
52
  },
80
53
  });
54
+ if (values.help) {
55
+ process.stdout.write(USAGE);
56
+ return;
57
+ }
58
+ if (values.code !== undefined && values.rooms !== undefined)
59
+ throw new Error('--code cannot be used with --rooms');
60
+ if (values.code !== undefined && values['no-private'])
61
+ throw new Error('--code cannot be used with --no-private');
62
+ if (values.code !== undefined && values.environment !== undefined)
63
+ throw new Error('--code cannot be used with --environment');
64
+ const rooms = chosenRooms(values.rooms, values['no-private']);
81
65
  const enrolled = (await readEnrolment()) ?? (await readDisconnected());
66
+ if (values.code !== undefined && enrolled !== null) {
67
+ throw new Error(`--code connects a new machine; this Kit home records Environment ${enrolled.environment}, so run kit login to reconnect it`);
68
+ }
69
+ const relay = process.env.HOUSE_KIT_RELAY || undefined;
70
+ selectRelay(relay);
82
71
  const house = values.house ?? enrolled?.house ?? DEFAULT_HOUSE;
83
72
  const replaces = process.env.HOUSE_KIT_REPLACES;
84
73
  const environment = replaces === undefined ? (values.environment ?? (enrolled?.house === house ? enrolled.environment : undefined)) : undefined;
85
74
  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;
75
+ let held = false;
76
+ let exchanged;
77
+ if (values.code !== undefined) {
78
+ exchanged = await post(house, '/kit/token', { code: values.code, label: hostname() });
79
+ }
80
+ else {
81
+ held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
82
+ const verifier = randomBytes(32).toString('base64url');
83
+ const started = await retrying(() => post(house, '/kit', {
84
+ label: hostname(),
85
+ ...(environment === undefined
86
+ ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
87
+ : { act: 'existing_environment', environment_id: environment }),
88
+ ...rooms,
89
+ code_challenge: createHash('sha256').update(verifier).digest('base64url'),
90
+ ...(held ? {} : { headless: true }),
91
+ }));
92
+ process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
93
+ open(started.start_url);
94
+ exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
95
+ }
96
+ await writeEnrolment({
97
+ house,
98
+ ...(relay === undefined ? {} : { relay }),
99
+ environment: exchanged.environment,
100
+ credential: exchanged.credential,
101
+ });
102
+ process.stdout.write(`Environment ${exchanged.environment} is connected to ${house}.\n`);
103
+ if (exchanged.headless_credential !== undefined) {
104
+ await writeOwnAgent({ house, user: exchanged.user, credential: exchanged.headless_credential });
105
+ }
106
+ else if (held && ownAgent !== null && ownAgent.user !== exchanged.user) {
107
+ await forgetOwnAgent();
108
+ process.stdout.write("This computer's own agent was another User's; run kit login again to connect it to you.\n");
115
109
  }
116
- const callback = await listen();
110
+ await placeAppGit(ownAgent, await readOwnAgent());
117
111
  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.');
112
+ startService();
132
113
  }
133
- finally {
134
- callback.close();
114
+ catch (error) {
115
+ process.stderr.write(`kit: ${error.message}\n`);
135
116
  }
136
117
  }
package/dist/logout.js CHANGED
@@ -1,18 +1,21 @@
1
1
  import { HouseRefusal, post } from './api.js';
2
- import { forgetEnrolment, readEnrolment } from './home.js';
2
+ import { forgetAppGit } from './app-git.js';
3
+ import { forgetEnrolment, forgetOwnAgent, readEnrolment } from './home.js';
3
4
  export async function logout() {
4
5
  const enrolled = await readEnrolment();
5
- if (enrolled === null) {
6
- process.stdout.write('This computer is not connected to House.\n');
7
- return;
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);
8
15
  }
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`);
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`);
18
21
  }
package/dist/parts.js ADDED
@@ -0,0 +1,82 @@
1
+ export class Parts {
2
+ parts = [];
3
+ context = null;
4
+ emit;
5
+ made = [];
6
+ events = 0;
7
+ writing = null;
8
+ counting = null;
9
+ planned = null;
10
+ constructor(emit) {
11
+ this.emit = emit;
12
+ }
13
+ write(type, id, text) {
14
+ if (text === '')
15
+ return;
16
+ if (this.writing?.type === type && this.writing.id === id) {
17
+ this.parts[this.writing.index].text += text;
18
+ this.emit({ op: 'append', index: this.writing.index, text });
19
+ return;
20
+ }
21
+ this.writing = { type, id, index: this.start({ type, text }) };
22
+ }
23
+ command() {
24
+ if (this.counting === null) {
25
+ this.counting = this.start({ type: 'commands', count: 1 });
26
+ return;
27
+ }
28
+ const part = this.parts[this.counting];
29
+ part.count++;
30
+ this.emit({ op: 'count', index: this.counting, count: part.count });
31
+ }
32
+ start(part) {
33
+ this.writing = null;
34
+ this.counting = null;
35
+ return this.add(part, ++this.events);
36
+ }
37
+ reserve() {
38
+ this.writing = null;
39
+ this.counting = null;
40
+ return ++this.events;
41
+ }
42
+ arrive(part, reserved) {
43
+ this.add(part, reserved);
44
+ }
45
+ done(index, result) {
46
+ const part = this.parts[index];
47
+ part.status = 'done';
48
+ part.result = result;
49
+ this.emit({ op: 'status', index, status: 'done', result });
50
+ }
51
+ plan(entries) {
52
+ if (this.planned === null) {
53
+ this.planned = this.start({ type: 'plan', entries });
54
+ return;
55
+ }
56
+ this.parts[this.planned].entries = entries;
57
+ this.emit({ op: 'plan', index: this.planned, entries });
58
+ }
59
+ measure(context) {
60
+ this.context = context;
61
+ this.emit({ op: 'context', ...context });
62
+ }
63
+ saved() {
64
+ return this.parts
65
+ .map((part, index) => ({ part, made: this.made[index] }))
66
+ .sort((a, b) => a.made - b.made)
67
+ .map(({ part }) => part);
68
+ }
69
+ operations() {
70
+ return [
71
+ ...this.parts.map((part, index) => ({ op: 'start', index, part })),
72
+ ...(this.context === null ? [] : [{ op: 'context', ...this.context }]),
73
+ ];
74
+ }
75
+ add(part, made) {
76
+ this.parts.push(part);
77
+ this.made.push(made);
78
+ const index = this.parts.length - 1;
79
+ this.emit({ op: 'start', index, part });
80
+ return index;
81
+ }
82
+ }
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 CHANGED
@@ -1,7 +1,17 @@
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
+ }
1
11
  export function relayed(target) {
2
12
  const url = new URL(target);
3
- const relay = process.env.HOUSE_KIT_RELAY;
4
- if (relay === undefined || relay === '')
13
+ const relay = relayOrigin();
14
+ if (relay === undefined)
5
15
  return url;
6
16
  const through = new URL(`${url.host}${url.pathname}${url.search}`, `${relay}/`);
7
17
  if (url.protocol === 'wss:' || url.protocol === 'ws:')