@agentshouse/kit 0.2.1-ce145e9aadbf6 → 0.2.1-cfe80fd914176

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,10 +37,11 @@ them out; running it again without the flag brings them back.
37
37
  Environment's credential in `~/.house-kit`, or in `$HOUSE_KIT_HOME` when it is
38
38
  set. Pass `--manual` to paste the code by hand on a machine without a browser,
39
39
  and `--environment <id>` to reconnect an Environment you already have. It also
40
- connects your own agent: `house <tool>` run outside an Agent conversation calls
41
- House as you, until you revoke that connection on Connections. `house help`
42
- lists the Tools. `kit logout` disconnects this computer and stops House Kit; a
43
- later `kit login` reconnects the same Environment.
40
+ connects your own agent: outside an Agent conversation, `house <tool>` calls
41
+ House as you and `git` clones and pushes your Apps at `<house>/app/` as you,
42
+ until you revoke that connection on Connections. `house help` lists the Tools.
43
+ `kit logout` disconnects this computer, stops House Kit and ends that Git
44
+ access; a later `kit login` reconnects the same Environment.
44
45
 
45
46
  `kit resident` keeps the Environment connected, and keeps the Rooms you chose
46
47
  for this Environment as Git repositories under `local-copies` in the
@@ -49,11 +50,9 @@ commit to House; in the container, run it through the install command from the
49
50
  copy's directory. Inside an Agent conversation the Agent runs `house push`.
50
51
 
51
52
  House Kit turns each audio file of your message to an Agent into text on this
52
- computer before the Agent reads the message. The first audio file downloads the
53
- speech engine and model, about 425 MB, into `~/.house-kit`.
53
+ computer before the Agent reads it. While transcription is on, the speech
54
+ engine and model use about 425 MB in `~/.house-kit`; turning it off deletes them.
54
55
 
55
56
  ## License
56
57
 
57
- MIT
58
-
59
- The skills come from [mattpocock/skills](https://github.com/mattpocock/skills); thank you, Matt Pocock.
58
+ MIT. The skills come from [mattpocock/skills](https://github.com/mattpocock/skills); thank you, Matt Pocock.
package/dist/acp.js CHANGED
@@ -3,9 +3,7 @@ import { execFileSync, spawn } from 'node:child_process';
3
3
  import { readdirSync, readFileSync } from 'node:fs';
4
4
  import { Readable, Writable } from 'node:stream';
5
5
  import { CLIS, KIT_VERSION, adapterCommand, withoutProxy } from './clis.js';
6
- export const TURN_STARTED = 'kit/turn_started';
7
- export const TURN_ENDED = 'kit/turn_ended';
8
- export async function startAdapter(kind, cli, cwd, app, jobs = () => undefined, added = {}) {
6
+ export async function startAdapter(kind, cli, cwd, app, events = () => undefined, added = {}, signal) {
9
7
  const adapter = CLIS[kind].adapter;
10
8
  const child = spawn(adapter === null ? cli : adapterCommand(kind), CLIS[kind].args, {
11
9
  cwd,
@@ -13,6 +11,9 @@ export async function startAdapter(kind, cli, cwd, app, jobs = () => undefined,
13
11
  stdio: ['pipe', 'pipe', 'pipe'],
14
12
  detached: true,
15
13
  });
14
+ const stop = () => killTree(child);
15
+ signal?.addEventListener('abort', stop, { once: true });
16
+ child.on('exit', () => signal?.removeEventListener('abort', stop));
16
17
  let stderr = '';
17
18
  child.stderr.on('data', (chunk) => {
18
19
  stderr = (stderr + chunk.toString('utf8')).slice(-4000);
@@ -29,16 +30,11 @@ export async function startAdapter(kind, cli, cwd, app, jobs = () => undefined,
29
30
  writable: stream.writable,
30
31
  readable: stream.readable.pipeThrough(new TransformStream({
31
32
  transform(message, controller) {
32
- const notice = message;
33
- const job = CLIS[kind].job(notice);
34
- if (job !== null)
35
- jobs(job);
36
- if (!notice.params?.update?.sessionUpdate?.startsWith('async_task_'))
33
+ const read = message;
34
+ events(read);
35
+ if (read.id !== undefined || (read.method !== 'session/update' && !read.method.startsWith('_'))) {
37
36
  controller.enqueue(message);
38
- if (CLIS[kind].turnStarted(notice))
39
- controller.enqueue({ jsonrpc: '2.0', method: TURN_STARTED });
40
- if (CLIS[kind].turnEnded(notice))
41
- controller.enqueue({ jsonrpc: '2.0', method: TURN_ENDED });
37
+ }
42
38
  },
43
39
  })),
44
40
  });
@@ -50,7 +46,8 @@ export async function startAdapter(kind, cli, cwd, app, jobs = () => undefined,
50
46
  fs: { readTextFile: false, writeTextFile: false },
51
47
  terminal: false,
52
48
  elicitation: { form: {} },
53
- _meta: { jetbrains: { air: { version: 1, capabilities: ['asyncTasks'] } } },
49
+ session: { compaction: {}, notices: {} },
50
+ _meta: { jetbrains: { air: { version: 1, capabilities: CLIS[kind].air } } },
54
51
  },
55
52
  clientInfo: { name: '@agentshouse/kit', version: KIT_VERSION },
56
53
  });
@@ -127,6 +124,22 @@ function marked(marker) {
127
124
  })
128
125
  .map(Number);
129
126
  }
127
+ function commandLine(pid) {
128
+ try {
129
+ return readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim();
130
+ }
131
+ catch {
132
+ return '';
133
+ }
134
+ }
135
+ export function processes(marker) {
136
+ const pids = marked(marker);
137
+ const tree = [...pids, ...descendants(pids)];
138
+ const commands = process.platform === 'darwin'
139
+ ? new Map(listed('-Aww').map(([pid, , command]) => [pid, command]))
140
+ : new Map(tree.map((pid) => [pid, commandLine(pid)]));
141
+ return new Set(tree.flatMap((pid) => (commands.get(pid) ? [`${pid} ${commands.get(pid)}`] : [])));
142
+ }
130
143
  export function killTree(child) {
131
144
  killAll([child.pid, ...descendants([child.pid])]);
132
145
  }
package/dist/agents.js CHANGED
@@ -3,6 +3,7 @@ import { readFile, realpath } from 'node:fs/promises';
3
3
  import { killTree, startAdapter } from './acp.js';
4
4
  import { CLIS, KIT_VERSION, below, installAdapter, installCli, locate, run, versionOf } from './clis.js';
5
5
  import { agentBase, kitHome } from './home.js';
6
+ import { holdTranscription, transcriptionReport } from './transcription.js';
6
7
  const SIGNED_OUT = { signed_in: false, models: [], modes: [] };
7
8
  function select(options, category) {
8
9
  const option = options.find((candidate) => candidate.category === category);
@@ -46,19 +47,29 @@ async function models(kind, adapter, known) {
46
47
  }
47
48
  return { models: offered, modes };
48
49
  }
49
- async function signedIn(kind, cli, known) {
50
+ async function signedIn(kind, cli, known, signal) {
50
51
  const probe = CLIS[kind].signedIn;
52
+ // A sign-in check that has not answered in half a minute counts as signed out rather than stalling the report.
51
53
  if ('command' in probe)
52
- return (await run(cli, probe.command, 30_000)).status === 0;
53
- return (await offer(kind, cli, known)).signed_in;
54
+ return (await run(cli, probe.command, 30_000, false, signal)).status === 0;
55
+ return (await offer(kind, cli, known, signal)).signed_in;
54
56
  }
55
- async function offer(kind, cli, known) {
57
+ function ended(signal) {
58
+ return new Promise((_, reject) => {
59
+ if (signal.aborted)
60
+ reject(signal.reason);
61
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
62
+ });
63
+ }
64
+ async function offer(kind, cli, known, signal) {
56
65
  const probe = CLIS[kind].signedIn;
57
- if ('command' in probe && (await run(cli, probe.command, 30_000)).status !== 0)
66
+ // A sign-in check that has not answered in half a minute counts as signed out rather than stalling the report.
67
+ if ('command' in probe && (await run(cli, probe.command, 30_000, false, signal)).status !== 0)
58
68
  return SIGNED_OUT;
59
69
  let adapter;
60
70
  try {
61
- adapter = await startAdapter(kind, cli, kitHome(), client({ name: '@agentshouse/kit' }));
71
+ adapter = await startAdapter(kind, cli, kitHome(), client({ name: '@agentshouse/kit' }), () => undefined, {}, signal);
72
+ signal?.throwIfAborted();
62
73
  if ('initializeMeta' in probe) {
63
74
  const method = adapter.initialized._meta?.[probe.initializeMeta];
64
75
  if (typeof method !== 'string' || method.length === 0)
@@ -67,7 +78,8 @@ async function offer(kind, cli, known) {
67
78
  return { signed_in: true, ...(await models(kind, adapter, known.models)) };
68
79
  }
69
80
  catch (error) {
70
- process.stderr.write(`kit: ${kind} did not offer its models: ${causeOf(error)}\n`);
81
+ if (!signal?.aborted)
82
+ process.stderr.write(`kit: ${kind} did not offer its models: ${causeOf(error)}\n`);
71
83
  return {
72
84
  signed_in: adapter === undefined && 'initializeMeta' in probe ? known.signed_in : true,
73
85
  models: known.models,
@@ -96,17 +108,19 @@ function tooOld(kind, release) {
96
108
  return `${cli.bin} ${release} is older than ${cli.minimum}, the oldest this Kit runs`;
97
109
  }
98
110
  async function sshHostKey() {
111
+ // Listing a local host key takes a moment, so ten seconds only bounds a stuck ssh-keygen.
99
112
  const listed = await run('ssh-keygen', ['-l', '-E', 'sha256', '-f', '/etc/ssh/ssh_host_ed25519_key.pub'], 10_000);
100
113
  return listed.status === 0 ? (/^\d+ (SHA256:\S+)/.exec(listed.output)?.[1] ?? null) : null;
101
114
  }
102
115
  async function operatingSystem() {
116
+ // sw_vers answers at once, so ten seconds only bounds a stuck call.
103
117
  if (process.platform === 'darwin')
104
118
  return `macOS ${(await run('sw_vers', ['-productVersion'], 10_000)).output.trim()}`;
105
119
  const release = await readFile('/etc/os-release', 'utf8');
106
120
  return /^PRETTY_NAME="?([^"\n]*)"?$/m.exec(release)?.[1] ?? release;
107
121
  }
108
122
  export class Agents {
109
- desired = { agents: [], routes: [] };
123
+ desired = { agents: [], routes: [], transcribe: false };
110
124
  house;
111
125
  reading = Promise.resolve();
112
126
  queues = new Map();
@@ -130,7 +144,10 @@ export class Agents {
130
144
  return this.desired;
131
145
  });
132
146
  this.reading = reading;
133
- return reading.then(({ agents }) => {
147
+ return reading.then(({ agents, transcribe }) => {
148
+ holdTranscription(transcribe)
149
+ .then((changed) => (changed ? this.report() : undefined))
150
+ .catch(logged);
134
151
  Promise.all(agents.map((kind) => this.load(kind)))
135
152
  .then(() => this.report())
136
153
  .catch(logged);
@@ -160,17 +177,18 @@ export class Agents {
160
177
  return cli;
161
178
  });
162
179
  }
163
- located(kind) {
164
- return this.queue(kind, () => this.ensure(kind));
180
+ located(kind, signal) {
181
+ return this.queue(kind, () => this.ensure(kind, signal), signal);
165
182
  }
166
183
  async reread(kind) {
167
184
  await this.examine(kind, this.readings.get(kind) ?? SIGNED_OUT, offer);
168
185
  await this.report();
169
186
  }
170
- async recheck(kind) {
187
+ async recheck(kind, signal) {
171
188
  const known = this.readings.get(kind) ?? SIGNED_OUT;
172
- await this.examine(kind, known, async (kind, cli) => (await signedIn(kind, cli, known)) ? { ...known, signed_in: true } : SIGNED_OUT);
173
- await this.report();
189
+ await this.examine(kind, known, async (kind, cli) => ((await signedIn(kind, cli, known, signal)) ? { ...known, signed_in: true } : SIGNED_OUT), signal);
190
+ if (!signal.aborted)
191
+ await this.report();
174
192
  }
175
193
  report() {
176
194
  const sending = this.sending.catch(() => undefined).then(() => this.send());
@@ -186,39 +204,42 @@ export class Agents {
186
204
  this.readings.set(kind, reading);
187
205
  this.report().catch(logged);
188
206
  }
189
- queue(kind, work) {
190
- const queued = (this.queues.get(kind) ?? Promise.resolve()).then(work);
207
+ queue(kind, work, signal) {
208
+ const queued = (this.queues.get(kind) ?? Promise.resolve()).then(() => {
209
+ signal?.throwIfAborted();
210
+ return work();
211
+ });
191
212
  this.queues.set(kind, queued.catch(() => undefined));
192
- return queued;
213
+ return signal === undefined ? queued : Promise.race([queued, ended(signal)]);
193
214
  }
194
- async ensure(kind) {
195
- const failed = await installAdapter(kind);
215
+ async ensure(kind, signal) {
216
+ const failed = await installAdapter(kind, signal);
196
217
  if (failed !== null)
197
218
  throw new Error(failed);
198
- const found = await locate(kind);
219
+ const found = await locate(kind, signal);
199
220
  if (found !== null)
200
221
  return found;
201
- const installing = this.installing.catch(() => undefined).then(() => installCli(kind));
222
+ const installing = this.installing.catch(() => undefined).then(() => installCli(kind, signal));
202
223
  this.installing = installing;
203
224
  const failure = await installing;
204
225
  if (failure !== null)
205
226
  throw new Error(failure);
206
- const installed = await locate(kind);
227
+ const installed = await locate(kind, signal);
207
228
  if (installed === null)
208
229
  throw new Error(`the login shell does not find ${CLIS[kind].bin} after its install`);
209
230
  return installed;
210
231
  }
211
- async resolve(kind) {
232
+ async resolve(kind, signal) {
212
233
  let cli;
213
234
  try {
214
- cli = await realpath(await this.ensure(kind));
235
+ cli = await realpath(await this.ensure(kind, signal));
215
236
  }
216
237
  catch (error) {
217
238
  const failure = causeOf(error);
218
239
  process.stderr.write(`kit: ${kind} did not install: ${failure}\n`);
219
240
  return { release: null, failure, ...SIGNED_OUT };
220
241
  }
221
- const release = await versionOf(cli);
242
+ const release = await versionOf(cli, signal);
222
243
  if (release === null)
223
244
  return { release: null, failure: `${cli} --version names no version`, ...SIGNED_OUT };
224
245
  const minimum = CLIS[kind].minimum;
@@ -226,11 +247,11 @@ export class Agents {
226
247
  return { release, minimum, failure: null, ...SIGNED_OUT };
227
248
  return { cli, release };
228
249
  }
229
- async examine(kind, known, read) {
250
+ async examine(kind, known, read, signal) {
230
251
  const current = this.nextRead(kind);
231
- const resolved = await this.queue(kind, () => this.resolve(kind));
252
+ const resolved = await this.queue(kind, () => this.resolve(kind, signal), signal);
232
253
  const reading = 'cli' in resolved ? { release: resolved.release, failure: null, ...(await read(kind, resolved.cli, known)) } : resolved;
233
- if (this.reads.get(kind) === current)
254
+ if (this.reads.get(kind) === current && !signal?.aborted)
234
255
  this.readings.set(kind, reading);
235
256
  }
236
257
  async load(kind) {
@@ -250,6 +271,7 @@ export class Agents {
250
271
  kit_version: KIT_VERSION,
251
272
  agent_base: agentBase(),
252
273
  agents,
274
+ transcription: transcriptionReport(),
253
275
  ...(hostKey === null ? {} : { ssh_host_key: hostKey }),
254
276
  };
255
277
  const state = JSON.stringify(body);
package/dist/api.js CHANGED
@@ -1,4 +1,7 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { end, SIGN_IN_AGAIN } from './end.js';
1
3
  import { readEnrolment } from './home.js';
4
+ import { retryable } from './refusals.js';
2
5
  import { relayed } from './relay.js';
3
6
  export class HouseRefusal extends Error {
4
7
  status;
@@ -9,9 +12,26 @@ export class HouseRefusal extends Error {
9
12
  this.text = text;
10
13
  }
11
14
  }
15
+ export function finalRefusal(error) {
16
+ return error instanceof HouseRefusal && retryable(error.text) === false;
17
+ }
12
18
  export function retryDelay(attempt) {
19
+ // Full jitter, doubling from one second to a 30-second cap, spreads the Kits one outage dropped and retries within half a minute of House's return.
13
20
  return Math.random() * Math.min(30_000, 1000 * 2 ** attempt);
14
21
  }
22
+ export async function retrying(sent, signal) {
23
+ for (let attempt = 0;; attempt++) {
24
+ try {
25
+ return await sent();
26
+ }
27
+ catch (error) {
28
+ if (!(error instanceof HouseRefusal) || retryable(error.text) !== true)
29
+ throw error;
30
+ }
31
+ // A request House refused as retryable is sent again on the jittered curve.
32
+ await delay(retryDelay(attempt), undefined, { signal });
33
+ }
34
+ }
15
35
  export async function post(house, path, body, credential, signal) {
16
36
  const answer = await fetch(relayed(new URL(path, house)), {
17
37
  method: 'POST',
@@ -29,7 +49,14 @@ export async function post(house, path, body, credential, signal) {
29
49
  }
30
50
  async function enrolledPost(path, body, signal) {
31
51
  const { house, credential } = (await readEnrolment());
32
- return post(house, path, body, credential, signal);
52
+ try {
53
+ return await post(house, path, body, credential, signal);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof HouseRefusal && error.status === 401)
57
+ end(SIGN_IN_AGAIN);
58
+ throw error;
59
+ }
33
60
  }
34
61
  export const house = {
35
62
  post: enrolledPost,
@@ -39,9 +66,10 @@ export const house = {
39
66
  return await enrolledPost(path, body);
40
67
  }
41
68
  catch (error) {
42
- if (error instanceof HouseRefusal && error.status < 500)
69
+ if (finalRefusal(error))
43
70
  throw error;
44
71
  process.stderr.write(`kit: ${path} did not reach House: ${error.message}\n`);
72
+ // A delivery House did not take is sent again on the jittered curve for as long as it is still current.
45
73
  await new Promise((resolve) => setTimeout(resolve, retryDelay(attempt)));
46
74
  if (!current())
47
75
  throw error;
@@ -0,0 +1,64 @@
1
+ import { extname, resolve } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { run } from './git.js';
4
+ import { kitHome, readOwnAgent } from './home.js';
5
+ import { quoted } from './shell.js';
6
+ function section(house) {
7
+ return `credential.${new URL('/app/', house).href}`;
8
+ }
9
+ function helper() {
10
+ const main = fileURLToPath(new URL(`./kit-main${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
11
+ return `!HOUSE_KIT_HOME=${quoted(resolve(kitHome()))} ${quoted(process.execPath)} ${quoted(main)} git-credential`;
12
+ }
13
+ async function configured(args) {
14
+ try {
15
+ return await run(kitHome(), ['config', '--global', ...args]);
16
+ }
17
+ catch (error) {
18
+ if (error.code === 'ENOENT')
19
+ return null;
20
+ throw error;
21
+ }
22
+ }
23
+ async function forget(house) {
24
+ await configured(['--remove-section', section(house)]);
25
+ }
26
+ async function register(house) {
27
+ await forget(house);
28
+ for (const value of ['', helper()]) {
29
+ const ran = await configured(['--add', `${section(house)}.helper`, value]);
30
+ if (ran === null)
31
+ return;
32
+ if (ran.status !== 0)
33
+ throw new Error(`git config failed: ${ran.stderr.trim()}`);
34
+ }
35
+ }
36
+ export async function placeAppGit(before, after) {
37
+ if (before !== null && before.house !== after?.house)
38
+ await forget(before.house);
39
+ if (after !== null)
40
+ await register(after.house);
41
+ }
42
+ export async function forgetAppGit() {
43
+ const ownAgent = await readOwnAgent();
44
+ if (ownAgent !== null)
45
+ await forget(ownAgent.house);
46
+ }
47
+ export async function answerGitCredential(operation) {
48
+ let asked = '';
49
+ for await (const chunk of process.stdin)
50
+ asked += String(chunk);
51
+ if (operation !== 'get')
52
+ return;
53
+ const attributes = new Map(asked
54
+ .split('\n')
55
+ .filter((line) => line.includes('='))
56
+ .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]));
57
+ const ownAgent = await readOwnAgent();
58
+ if (ownAgent === null)
59
+ return;
60
+ const house = new URL(ownAgent.house);
61
+ if (attributes.get('protocol') !== house.protocol.slice(0, -1) || attributes.get('host') !== house.host)
62
+ return;
63
+ process.stdout.write(`username=house\npassword=${ownAgent.credential}\n`);
64
+ }
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "schemaVersion": 2,
3
- "version": "0.2.1-ce145e9aadbf6",
3
+ "version": "0.2.1-cfe80fd914176",
4
4
  "hosts": {
5
5
  "macos": {
6
6
  "asset": {
7
7
  "name": "connect-linux.sh",
8
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-ce145e9aadbf6/connect-linux.sh"
8
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-cfe80fd914176/connect-linux.sh"
9
9
  }
10
10
  },
11
11
  "linux": {
12
12
  "asset": {
13
13
  "name": "connect-linux.sh",
14
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-ce145e9aadbf6/connect-linux.sh"
14
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-cfe80fd914176/connect-linux.sh"
15
15
  }
16
16
  },
17
17
  "windows": {
18
18
  "asset": {
19
19
  "name": "connect-windows.ps1",
20
- "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-ce145e9aadbf6/connect-windows.ps1"
20
+ "url": "https://github.com/agentshouse/kit/releases/download/v0.2.1-cfe80fd914176/connect-windows.ps1"
21
21
  }
22
22
  }
23
23
  }
package/dist/bridge.js CHANGED
@@ -6,16 +6,15 @@ import { createServer, request as httpRequest } from 'node:http';
6
6
  import { request as httpsRequest } from 'node:https';
7
7
  import { delimiter, dirname, join } from 'node:path';
8
8
  import { parse } from 'yaml';
9
- import { HouseRefusal, retryDelay } from './api.js';
9
+ import { finalRefusal, HouseRefusal, retryDelay, retrying } from './api.js';
10
10
  import { loginPath } from './clis.js';
11
11
  import { changedPaths, } from './copies.js';
12
12
  import { kitHome, readEnrolment } from './home.js';
13
13
  import { callHouse, mcpBody, rpc, UNREACHABLE } from './mcp.js';
14
- import { operationId, uuidOf } from './operation.js';
15
- import { refusalOf } from './refusals.js';
14
+ import { operationId } from './operation.js';
15
+ import { refusalOf, retryable } from './refusals.js';
16
16
  import { relayed } from './relay.js';
17
17
  const MCP_REQUEST_BYTES = 4 * 1024 * 1024;
18
- const ATTACHMENTS = '/kit/attachments/upload';
19
18
  export async function received(request) {
20
19
  let text = '';
21
20
  request.setEncoding('utf8');
@@ -40,8 +39,6 @@ function refusalIn(text, status) {
40
39
  return refusalOf(text) ?? { code: '', text: text === '' ? `House refused it with ${status}` : text, conflicts: [] };
41
40
  }
42
41
  function answered(forwarded) {
43
- if (forwarded.status >= 500)
44
- throw new HouseRefusal('/', forwarded.status, forwarded.text);
45
42
  if (forwarded.status !== 200)
46
43
  return { refused: refusalIn(forwarded.text, forwarded.status) };
47
44
  const answer = JSON.parse(forwarded.text);
@@ -65,16 +62,11 @@ function pendingSeconds(forwarded) {
65
62
  function resendAfter(forwarded, attempt) {
66
63
  if (forwarded === null)
67
64
  return retryDelay(attempt);
68
- if (forwarded.status >= 500)
69
- return refusalOf(forwarded.text) === null ? retryDelay(attempt) : null;
65
+ if (forwarded.status !== 200)
66
+ return retryable(forwarded.text) === false ? null : retryDelay(attempt);
70
67
  const seconds = pendingSeconds(forwarded);
71
68
  return seconds === null ? null : seconds * 1000;
72
69
  }
73
- function versioned(conversationId, text) {
74
- const file = JSON.parse(text);
75
- const identity = JSON.stringify([conversationId, file.room_ref ?? null, file.name, file.sha256]);
76
- return JSON.stringify({ ...file, version: uuidOf(createHash('sha256').update(identity).digest(), 8) });
77
- }
78
70
  function editAnswer(forwarded) {
79
71
  const answer = answered(forwarded);
80
72
  if ('refused' in answer)
@@ -105,6 +97,7 @@ export async function openBridge(house, copies, conversationId, signal) {
105
97
  const after = resendAfter(forwarded, attempt);
106
98
  if (after === null)
107
99
  return forwarded;
100
+ // A write House did not settle is sent again on the jittered curve, or after the wait House names for a pending one.
108
101
  await delay(after, undefined, { signal: closed.signal });
109
102
  }
110
103
  };
@@ -119,17 +112,26 @@ export async function openBridge(house, copies, conversationId, signal) {
119
112
  if ('refused' in prepared)
120
113
  return prepared;
121
114
  const { transfer } = parse(prepared.text);
122
- const posted = await fetch(relayed(transfer.url), {
123
- method: 'POST',
124
- headers: { 'content-type': 'text/plain; charset=utf-8' },
125
- body: Buffer.concat([Buffer.from(`${transfer.operation}\n`), bytes]),
126
- signal: closed.signal,
127
- });
128
- const text = await posted.text();
129
- if (posted.status >= 500)
130
- throw new HouseRefusal('/', posted.status, text);
131
- if (!posted.ok)
132
- return { refused: refusalIn(text, posted.status) };
115
+ let text;
116
+ try {
117
+ text = await retrying(async () => {
118
+ const posted = await fetch(relayed(transfer.url), {
119
+ method: 'POST',
120
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
121
+ body: Buffer.concat([Buffer.from(`${transfer.operation}\n`), bytes]),
122
+ signal: closed.signal,
123
+ });
124
+ const answer = await posted.text();
125
+ if (!posted.ok)
126
+ throw new HouseRefusal('/', posted.status, answer);
127
+ return answer;
128
+ }, closed.signal);
129
+ }
130
+ catch (error) {
131
+ if (!finalRefusal(error))
132
+ throw error;
133
+ return { refused: refusalIn(error.text, error.status) };
134
+ }
133
135
  const held = JSON.parse(text).transfer;
134
136
  return { url: held.url, operation: held.operation, bytes: bytes.length, sha256 };
135
137
  };
@@ -146,19 +148,10 @@ export async function openBridge(house, copies, conversationId, signal) {
146
148
  throw error;
147
149
  }
148
150
  };
149
- const forward = async (path, text) => {
150
- if (path === '/') {
151
- const message = JSON.parse(text);
152
- const tool = message.method === 'tools/call' ? String(message.params.name) : null;
153
- return send(message, tool !== null && (await writes(tool)) ? operationId() : null);
154
- }
155
- const answer = await fetch(relayed(new URL(path, origin)), {
156
- method: 'POST',
157
- headers: { 'content-type': 'application/json', authorization: `Bearer ${credential}` },
158
- body: versioned(conversationId, text),
159
- signal: closed.signal,
160
- });
161
- return { status: answer.status, text: await answer.text() };
151
+ const forward = async (text) => {
152
+ const message = JSON.parse(text);
153
+ const tool = message.method === 'tools/call' ? String(message.params.name) : null;
154
+ return send(message, tool !== null && (await writes(tool)) ? operationId() : null);
162
155
  };
163
156
  const caller = {
164
157
  key: `conversation:${conversationId}`,
@@ -184,7 +177,7 @@ export async function openBridge(house, copies, conversationId, signal) {
184
177
  await copies.observed(JSON.parse(text));
185
178
  return { status: 200, text: '{}' };
186
179
  }
187
- return path === '/' || path === ATTACHMENTS ? forward(path, text) : { status: 404, text: '' };
180
+ return path === '/' ? forward(text) : { status: 404, text: '' };
188
181
  };
189
182
  const sockets = join(kitHome(), 'bridges');
190
183
  await mkdir(sockets, { recursive: true, mode: 0o700 });
@@ -231,7 +224,7 @@ export async function openBridge(house, copies, conversationId, signal) {
231
224
  GIT_CONFIG_VALUE_0: app,
232
225
  },
233
226
  tool: async (name, args) => {
234
- const forwarded = await forward('/', JSON.stringify(call(name, args)));
227
+ const forwarded = await forward(JSON.stringify(call(name, args)));
235
228
  if (forwarded.status !== 200)
236
229
  throw new Error(`House refused ${name} with ${forwarded.status}: ${forwarded.text}`);
237
230
  const answer = JSON.parse(forwarded.text);