@agentshouse/kit 0.2.1-ce47f621f90e1 → 0.2.1-ce9401bb7d372

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/dist/files.js CHANGED
@@ -27,7 +27,7 @@ export function inspectedFile(answer) {
27
27
  media_type: typeof inspected.media_type === 'string' ? inspected.media_type : null,
28
28
  };
29
29
  }
30
- function paused(milliseconds) {
30
+ export function paused(milliseconds) {
31
31
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
32
32
  }
33
33
  export function storeRefusal(act, status) {
@@ -140,5 +140,5 @@ export async function downloaded(address, fetching, destination, name) {
140
140
  }
141
141
  export async function fetched(url, signal) {
142
142
  const answer = await fetch(relayed(url), { signal });
143
- return { status: answer.status, body: answer.body ?? Readable.from([]) };
143
+ return { status: answer.status, body: answer.body === null ? Readable.from([]) : Readable.fromWeb(answer.body) };
144
144
  }
package/dist/git.js CHANGED
@@ -70,18 +70,52 @@ function data(text) {
70
70
  const bytes = Buffer.from(text, 'utf8');
71
71
  return [Buffer.from(`data ${bytes.length}\n`), bytes, Buffer.from('\n')];
72
72
  }
73
- export async function importCommits(repository, commits) {
74
- const stream = [];
73
+ function written(stream, bytes) {
74
+ return new Promise((resolve, reject) => {
75
+ stream.write(bytes, (error) => (error ? reject(error) : resolve()));
76
+ });
77
+ }
78
+ async function imported(stream, commits) {
79
+ await written(stream, Buffer.from('feature done\n'));
75
80
  for (const [index, commit] of commits.entries()) {
76
- stream.push(Buffer.from(`commit ${HOUSE_REF}\nmark :${index + 1}\ncommitter ${COMMITTER} ${Math.floor(Date.now() / 1000)} +0000\n`), ...data(commit.message), ...(commit.from === null ? [] : [Buffer.from(`from ${commit.from}\n`)]), ...(commit.merge === undefined ? [] : [Buffer.from(`merge ${commit.merge}\n`)]), ...(commit.replaces === true ? [Buffer.from('deleteall\n')] : []));
77
- for (const [path, content] of commit.files) {
78
- if (content === null)
79
- stream.push(Buffer.from(`D ${quoted(path)}\n`));
80
- else
81
- stream.push(Buffer.from(`M 100644 inline ${quoted(path)}\n`), ...data(content));
81
+ await written(stream, Buffer.concat([
82
+ Buffer.from(`commit ${HOUSE_REF}\nmark :${index + 1}\ncommitter ${COMMITTER} ${Math.floor(Date.now() / 1000)} +0000\n`),
83
+ ...data(commit.message),
84
+ ...(commit.from === null ? [] : [Buffer.from(`from ${commit.from}\n`)]),
85
+ ...(commit.merge === undefined ? [] : [Buffer.from(`merge ${commit.merge}\n`)]),
86
+ ...(commit.replaces === true ? [Buffer.from('deleteall\n')] : []),
87
+ ]));
88
+ for await (const [path, content] of commit.files) {
89
+ await written(stream, content === null
90
+ ? Buffer.from(`D ${quoted(path)}\n`)
91
+ : Buffer.concat([Buffer.from(`M 100644 inline ${quoted(path)}\n`), ...data(content)]));
82
92
  }
83
- stream.push(Buffer.from('\n'));
93
+ await written(stream, Buffer.from('\n'));
94
+ }
95
+ await written(stream, Buffer.from('done\n'));
96
+ }
97
+ export async function importCommits(repository, commits) {
98
+ const child = spawn('git', ['fast-import', '--quiet', '--force'], { cwd: repository, env: childEnvironment() });
99
+ let stderr = '';
100
+ child.stdout.resume();
101
+ child.stderr.on('data', (chunk) => {
102
+ stderr += chunk.toString('utf8');
103
+ });
104
+ child.stdin.on('error', () => undefined);
105
+ const closed = new Promise((resolve, reject) => {
106
+ child.on('error', reject);
107
+ child.on('close', resolve);
108
+ });
109
+ try {
110
+ await imported(child.stdin, commits);
111
+ child.stdin.end();
112
+ }
113
+ catch (error) {
114
+ child.stdin.destroy();
115
+ await closed;
116
+ throw error.code === 'EPIPE' ? new Error(`git fast-import failed: ${stderr.trim()}`) : error;
84
117
  }
85
- await git(repository, ['fast-import', '--quiet', '--force'], Buffer.concat(stream));
118
+ if ((await closed) !== 0)
119
+ throw new Error(`git fast-import failed: ${stderr.trim()}`);
86
120
  return revision(repository, HOUSE_REF);
87
121
  }
package/dist/grok.js ADDED
@@ -0,0 +1,39 @@
1
+ const PLAN = 'plan';
2
+ const PLAN_ABANDONED = 'abandoned';
3
+ const PLAN_FIELD = {
4
+ type: 'string',
5
+ title: 'Approve this plan?',
6
+ oneOf: [
7
+ { const: 'approved', title: 'Approve' },
8
+ { const: PLAN_ABANDONED, title: 'Abandon' },
9
+ ],
10
+ };
11
+ function form(sessionId, message, properties) {
12
+ return { mode: 'form', sessionId, message, requestedSchema: { type: 'object', properties } };
13
+ }
14
+ function questionField({ options, multiSelect }, title) {
15
+ const choices = options.map(({ label, description }) => ({ const: label, title: label, description }));
16
+ return multiSelect === true ? { type: 'array', title, items: { anyOf: choices } } : { type: 'string', title, oneOf: choices };
17
+ }
18
+ export function grokQuestionForm({ sessionId, questions }) {
19
+ const lone = questions.length === 1;
20
+ return form(sessionId, questions.map(({ question }) => question).join('\n\n'), Object.fromEntries(questions.map((one) => [one.question, questionField(one, lone ? 'Answer' : one.question)])));
21
+ }
22
+ function answerText(value) {
23
+ return Array.isArray(value) ? value.join(', ') : String(value);
24
+ }
25
+ function contentOf(response) {
26
+ return response.action === 'accept' ? (response.content ?? {}) : {};
27
+ }
28
+ export function grokQuestionAnswer(response) {
29
+ if (response.action !== 'accept')
30
+ return { outcome: 'cancelled' };
31
+ const answers = Object.entries(contentOf(response)).map(([question, value]) => [question, answerText(value)]);
32
+ return { outcome: 'accepted', answers: Object.fromEntries(answers) };
33
+ }
34
+ export function grokPlanForm({ sessionId, planContent }) {
35
+ return form(sessionId, planContent, { [PLAN]: PLAN_FIELD });
36
+ }
37
+ export function grokPlanAnswer(response) {
38
+ return { outcome: contentOf(response)[PLAN] ?? PLAN_ABANDONED };
39
+ }
package/dist/house-cli.js CHANGED
@@ -12,7 +12,8 @@ import { callHouse, rpc, UNREACHABLE, Unsettled } from './mcp.js';
12
12
  import { refusalOf, retryable } from './refusals.js';
13
13
  import { proxyUnlessRelayed, relayed, selectRelay } from './relay.js';
14
14
  import { parse } from 'yaml';
15
- const USAGE = "usage: house <tool> ['<arguments as JSON>']";
15
+ const USAGE = "usage: house <tool> ['<arguments as JSON>']; house help <tool>: its arguments";
16
+ const HELP = 'help [tool]';
16
17
  const PUSH_USAGE = 'usage: house push [commit] [--owner]';
17
18
  const PUSH = "push [commit]: sends the Local copy's committed changes to House";
18
19
  const FETCH_USAGE = 'usage: house fetch';
@@ -23,8 +24,8 @@ const ARGUMENTS = `the arguments are one JSON object in single quotes, like hous
23
24
  const CLOSED = "this conversation's House connection is closed; nothing to do from here";
24
25
  const SANDBOXED = "your CLI's sandbox kept house from House; run house directly, not through another program";
25
26
  const REVOKED = 'this conversation no longer has House access; nothing to do from here';
26
- const UNCONNECTED = "this computer's own agent has no House connection; run kit login, or kit chatgpt --key <key> with a script key";
27
- const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login, or kit chatgpt --key <key> with a script key";
27
+ const UNCONNECTED = "this computer's own agent has no House connection; run kit login";
28
+ const DISCONNECTED = "House no longer accepts this computer's own agent; run kit login";
28
29
  const UNCONFIRMED = 'with no result; a write may or may not have taken effect, so read before you repeat it';
29
30
  const socketPath = process.env.HOUSE_BRIDGE;
30
31
  const MEDIA_TYPES = new Map([
@@ -255,21 +256,77 @@ function argumentsOf(argument) {
255
256
  throw new Error(ARGUMENTS);
256
257
  return parsed;
257
258
  }
259
+ // The schema a $ref points to inside the Tool's own inputSchema, or an empty one when it points elsewhere.
260
+ function resolved(schema, root) {
261
+ if (schema.$ref === undefined)
262
+ return schema;
263
+ if (!schema.$ref.startsWith('#'))
264
+ return {};
265
+ let found = root;
266
+ for (const key of schema.$ref.split('/').slice(1)) {
267
+ found = typeof found === 'object' && found !== null ? found[key.replaceAll('~1', '/').replaceAll('~0', '~')] : undefined;
268
+ }
269
+ return typeof found === 'object' && found !== null ? found : {};
270
+ }
271
+ // The schema a $ref resolves to, with that $ref added to the open ones, or null when it is open already,
272
+ // so a schema that holds itself is expanded once.
273
+ function expanded(schema, root, refs) {
274
+ if (schema.$ref === undefined)
275
+ return { schema, refs };
276
+ return refs.has(schema.$ref) ? null : { schema: resolved(schema, root), refs: new Set([...refs, schema.$ref]) };
277
+ }
278
+ // One line per argument: its name, its value when it has one or a few, whether it is required, and its
279
+ // description. When deep, the arguments its value holds follow it.
280
+ function argumentLines(schema, root, indent, deep, refs = new Set()) {
281
+ const required = new Set(schema.required ?? []);
282
+ return Object.entries(schema.properties ?? {}).flatMap(([name, property]) => {
283
+ const value = resolved(property, root);
284
+ const values = value.const !== undefined ? [value.const] : (value.enum ?? []);
285
+ const words = [name, ...(values.length === 0 ? [] : [values.map((one) => JSON.stringify(one)).join(' | ')]), ...(required.has(name) ? ['(required)'] : [])];
286
+ const description = property.description ?? value.description;
287
+ const line = `${indent}${words.join(' ')}${description === undefined ? '' : `: ${description}`}`;
288
+ return deep ? [line, ...held(property, root, `${indent} `, refs)] : [line];
289
+ });
290
+ }
291
+ // The arguments a value holds: its own, its items', and those of each alternative of a oneOf or anyOf,
292
+ // each alternative a "- " entry when more than one has arguments.
293
+ function held(schema, root, indent, refs) {
294
+ const value = expanded(schema, root, refs);
295
+ if (value === null)
296
+ return [];
297
+ const alternatives = (value.schema.oneOf ?? value.schema.anyOf ?? [])
298
+ .map((alternative) => held(alternative, root, indent, value.refs))
299
+ .filter((lines) => lines.length > 0);
300
+ return [
301
+ ...argumentLines(value.schema, root, indent, true, value.refs),
302
+ ...(value.schema.items === undefined ? [] : held(value.schema.items, root, indent, value.refs)),
303
+ ...(alternatives.length === 1
304
+ ? alternatives[0]
305
+ : alternatives.flatMap((lines) => lines.map((line, index) => (index === 0 ? `${indent}- ${line.slice(indent.length)}` : ` ${line}`)))),
306
+ ];
307
+ }
308
+ function listed(tool) {
309
+ return tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`;
310
+ }
311
+ async function toolHelp(name) {
312
+ const tool = (await tools()).find((one) => one.name === name);
313
+ if (tool === undefined)
314
+ throw new Error(`${name} is no Tool; house find_command '{"query":"${name}"}' finds Commands`);
315
+ return [listed(tool), ...argumentLines(tool.inputSchema, tool.inputSchema, ' ', true)].join('\n');
316
+ }
258
317
  async function house(args) {
259
318
  const { flags, positionals: [verb, argument] } = accepted(args, ['--help'], 2, USAGE);
260
- if (verb === 'help' && argument !== undefined)
261
- throw unexpected(argument, USAGE);
262
319
  if (flags.has('--help') && argument !== undefined)
263
320
  throw unexpected('--help', USAGE);
321
+ // house help <name> runs as house <name> --help, so both forms answer alike.
322
+ if (verb === 'help' && argument !== undefined)
323
+ return run([argument, '--help']);
264
324
  if (verb === undefined || verb === 'help') {
265
- return [USAGE, 'help', PUSH, FETCH, DOWNLOAD, ...(await tools()).map((tool) => (tool.description === undefined ? tool.name : `${tool.name}: ${tool.description}`))].join('\n');
266
- }
267
- if (flags.has('--help')) {
268
- const tool = (await tools()).find((listed) => listed.name === verb);
269
- if (tool === undefined)
270
- throw new Error(`${verb} is no Tool; house find_command '{"query":"${verb}"}' finds Commands`);
271
- return [...(tool.description === undefined ? [] : [tool.description]), JSON.stringify(tool.inputSchema)].join('\n');
325
+ const listing = (await tools()).flatMap((tool) => tool.description === undefined ? [tool.name, ...argumentLines(tool.inputSchema, tool.inputSchema, ' ', false)] : [listed(tool)]);
326
+ return [USAGE, HELP, PUSH, FETCH, DOWNLOAD, ...listing].join('\n');
272
327
  }
328
+ if (flags.has('--help'))
329
+ return toolHelp(verb);
273
330
  const parsed = argumentsOf(argument);
274
331
  return verb === 'upload' ? upload(parsed) : called(verb, parsed);
275
332
  }
@@ -280,16 +337,19 @@ async function called(name, args) {
280
337
  throw new Error(text.replace(/\n+$/, ''));
281
338
  return text;
282
339
  }
340
+ function run(argv) {
341
+ const named = argv.findIndex((arg) => !arg.startsWith('-'));
342
+ const rest = argv.filter((_arg, index) => index !== named);
343
+ if (argv[named] === 'push')
344
+ return push(rest);
345
+ if (argv[named] === 'fetch')
346
+ return fetched(rest);
347
+ if (argv[named] === 'download')
348
+ return download(rest);
349
+ return house(argv);
350
+ }
283
351
  const argv = process.argv.slice(2);
284
- const named = argv.findIndex((arg) => !arg.startsWith('-'));
285
- const rest = argv.filter((_arg, index) => index !== named);
286
- (argv[named] === 'push'
287
- ? push(rest)
288
- : argv[named] === 'fetch'
289
- ? fetched(rest)
290
- : argv[named] === 'download'
291
- ? download(rest)
292
- : house(argv)).then((text) => {
352
+ run(argv).then((text) => {
293
353
  process.stdout.write(`${text}\n`);
294
354
  if (argv[0] === 'shell')
295
355
  process.exitCode = Number(/^exit: (\d+)(?:\n|$)/.exec(text)?.[1] ?? 0);
@@ -1,5 +1,4 @@
1
1
  import { agentInstructions } from '@agentshouse/skills';
2
- import { HOUSE_REF } from './git.js';
3
2
  const OWNER_RULES = '/rooms/private/owner-rules.md';
4
3
  const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
5
4
  const FAILED = /^exit: [1-9]\d*$/;
@@ -26,7 +25,6 @@ async function readOwnerRules(bridge) {
26
25
  }
27
26
  return document;
28
27
  }
29
- export async function instructions(bridge, base, copies) {
30
- const lines = agentInstructions(HOUSE_REF, copies);
31
- return [lines.join('\n'), base, (await readOwnerRules(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
28
+ export async function instructions(bridge, base) {
29
+ return [agentInstructions().join('\n'), base, (await readOwnerRules(bridge)).replace(/\n$/, '')].filter((part) => part !== '').join('\n\n');
32
30
  }
package/dist/kit-cli.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import { answerGitCredential } from './app-git.js';
3
- import { chatgpt } from './chatgpt.js';
4
3
  import { login } from './login.js';
5
4
  import { logout } from './logout.js';
6
5
  import { proxyUnlessRelayed } from './relay.js';
7
6
  import { resident } from './resident.js';
8
- const USAGE = 'usage: kit <login|logout|resident|chatgpt>\n';
7
+ const USAGE = 'usage: kit <login|logout|resident>\n';
9
8
  const COMMANDS = new Map([
10
9
  [
11
10
  'logout',
@@ -40,8 +39,6 @@ proxyUnlessRelayed();
40
39
  async function run() {
41
40
  if (command === 'login')
42
41
  return login(argv);
43
- if (command === 'chatgpt')
44
- return chatgpt(argv);
45
42
  if (command === '--help') {
46
43
  parseArgs({ args: argv });
47
44
  process.stdout.write(USAGE);
package/dist/login.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { KIT_LOGIN_PATHS, } from '@agentshouse/kit-wire';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { createHash, randomBytes } from 'node:crypto';
3
4
  import { parseArgs } from 'node:util';
@@ -11,16 +12,22 @@ import { selectRelay } from './relay.js';
11
12
  import { startService } from './service.js';
12
13
  import { placeSkillSet } from './skills.js';
13
14
  import { endUnserved } from './wire.js';
14
- export const DEFAULT_HOUSE = 'https://agents.house';
15
+ const DEFAULT_HOUSE = 'https://agents.house';
15
16
  const OPENER = process.platform === 'darwin' ? 'open' : 'xdg-open';
16
17
  // Polling every two seconds brings the User's confirmation to the waiting Kit moments after they give it.
17
18
  const POLL_INTERVAL_MS = 2000;
19
+ function startLogin(house, request) {
20
+ return post(house, KIT_LOGIN_PATHS.start, request);
21
+ }
22
+ function pollLogin(house, request) {
23
+ return post(house, KIT_LOGIN_PATHS.poll, request);
24
+ }
18
25
  function open(link) {
19
26
  spawn(OPENER, [link], { detached: true, stdio: 'ignore' })
20
27
  .on('error', () => undefined)
21
28
  .unref();
22
29
  }
23
- export async function accepted(house, credential) {
30
+ async function accepted(house, credential) {
24
31
  const checked = await callHouse(house, credential, rpc('tools/list', {}));
25
32
  if (checked.status === 200)
26
33
  return true;
@@ -92,12 +99,12 @@ export async function login(argv) {
92
99
  let named = environment;
93
100
  let exchanged;
94
101
  if (values.code !== undefined) {
95
- exchanged = await post(house, '/kit/token', { code: values.code });
102
+ exchanged = await pollLogin(house, { code: values.code });
96
103
  }
97
104
  else {
98
105
  held = ownAgent !== null && ownAgent.house === house && (await accepted(house, ownAgent.credential));
99
106
  const verifier = randomBytes(32).toString('base64url');
100
- const start = () => retrying(() => post(house, '/kit', {
107
+ const start = () => retrying(() => startLogin(house, {
101
108
  ...(named === undefined
102
109
  ? { act: 'new_environment', ...(replaces === undefined ? {} : { replaces }) }
103
110
  : { act: 'existing_environment', environment_id: named }),
@@ -119,7 +126,7 @@ export async function login(argv) {
119
126
  }
120
127
  process.stdout.write(`Open this link and confirm: ${started.start_url}\n`);
121
128
  open(started.start_url);
122
- exchanged = await retrying(() => post(house, '/kit/token', { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
129
+ exchanged = await retrying(() => pollLogin(house, { login: started.login, code_verifier: verifier }), undefined, () => POLL_INTERVAL_MS);
123
130
  }
124
131
  await placeSkillSet(house);
125
132
  await writeCodexRule().catch((error) => process.stderr.write(`kit: ${error.message}\n`));
package/dist/logout.js CHANGED
@@ -1,10 +1,10 @@
1
- import { HouseRefusal, post } from './api.js';
1
+ import { HouseRefusal, kitAct } from './api.js';
2
2
  import { forgetEnrolment, forgetOwnAgent, readEnrolment } from './home.js';
3
3
  export async function logout() {
4
4
  const enrolled = await readEnrolment();
5
5
  if (enrolled !== null) {
6
6
  try {
7
- await post(enrolled.house, '/kit/logout', {}, enrolled.credential);
7
+ await kitAct(enrolled.house, 'kits/log-out', {}, enrolled.credential);
8
8
  }
9
9
  catch (error) {
10
10
  if (!(error instanceof HouseRefusal && error.status === 401))
package/dist/mcp.js CHANGED
@@ -1,7 +1,7 @@
1
+ import { KIT_WIRE, KIT_WIRE_HEADER } from '@agentshouse/kit-wire';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { KIT_RELEASE } from './clis.js';
3
4
  import { relayed } from './relay.js';
4
- import { KIT_WIRE, KIT_WIRE_HEADER } from './wire.js';
5
5
  const MCP_PROTOCOL_VERSION = '2026-07-28';
6
6
  export const UNREACHABLE = 'House is unreachable; call again in a minute';
7
7
  export class Unsettled extends Error {
@@ -34,7 +34,7 @@ export async function callHouse(origin, credential, message, operation = null, s
34
34
  'mcp-protocol-version': MCP_PROTOCOL_VERSION,
35
35
  'mcp-method': message.method,
36
36
  ...(tool === null ? {} : { 'mcp-name': tool }),
37
- [KIT_WIRE_HEADER]: String(KIT_WIRE),
37
+ [KIT_WIRE_HEADER]: KIT_WIRE,
38
38
  },
39
39
  body: mcpBody(message, operation),
40
40
  signal,
package/dist/placement.js CHANGED
@@ -14,12 +14,6 @@ function recorded(name) {
14
14
  export function installCommand() {
15
15
  return recorded('install-command');
16
16
  }
17
- export function machine() {
18
- const placed = recorded('placement');
19
- if (placed === 'container' || placed === 'server' || placed === 'windows')
20
- return placed;
21
- return process.platform === 'darwin' ? 'macos' : 'linux';
22
- }
23
17
  export function placedPrefix() {
24
18
  const prefix = process.env.HOUSE_KIT_PREFIX;
25
19
  if (prefix === undefined || prefix === '')
package/dist/resident.js CHANGED
@@ -8,9 +8,9 @@ import { fileURLToPath } from 'node:url';
8
8
  import { Agents } from './agents.js';
9
9
  import { house } from './api.js';
10
10
  import { received } from './bridge.js';
11
- import { CONVERSATION_METHODS, Conversations } from './conversations.js';
11
+ import { Conversations } from './conversations.js';
12
12
  import { LocalCopies } from './copies.js';
13
- import { restart, unknownMethod } from './end.js';
13
+ import { restart } from './end.js';
14
14
  import { agentBase, enrolled, kitHome, ownerLock, ownerSocket, readEnrolment } from './home.js';
15
15
  import { Calls } from './calls.js';
16
16
  import { killDescendants } from './scope.js';
@@ -111,12 +111,6 @@ function connected() {
111
111
  }
112
112
  async function started() {
113
113
  await connected();
114
- watch(kitHome(), () => {
115
- if (enrolled())
116
- return;
117
- killDescendants();
118
- process.exit(1);
119
- });
120
114
  await placeSkillSet((await readEnrolment()).house);
121
115
  await mkdir(agentBase(), { recursive: true });
122
116
  await installShim(join(kitHome(), 'shim', 'git'), 'git-main');
@@ -127,6 +121,7 @@ export async function resident() {
127
121
  const copies = new LocalCopies(house);
128
122
  await copies.load();
129
123
  await serveOwner(copies);
124
+ await copies.swept();
130
125
  await started().catch((error) => {
131
126
  report(error);
132
127
  process.exit(1);
@@ -135,17 +130,28 @@ export async function resident() {
135
130
  const agents = new Agents(house, () => changed());
136
131
  let connection = null;
137
132
  let reported = false;
133
+ let stopping = false;
134
+ const stop = async (then) => {
135
+ if (stopping)
136
+ return;
137
+ stopping = true;
138
+ conversations.stopped();
139
+ killDescendants();
140
+ await connection?.close();
141
+ then();
142
+ };
138
143
  const idle = () => calls.idle() && conversations.idle() && agents.idle();
139
144
  const changed = () => {
140
145
  if (!idle()) {
141
146
  reported = false;
142
147
  }
143
- else if (update.placedRelease() !== null && conversations.quiet()) {
144
- restart(`Kit ${update.placedRelease()} is placed; its supervisor starts it`);
148
+ else if (update.placedRelease() !== null && conversations.quiet() && process.env.HOUSE_KIT_SANDBOX !== '1') {
149
+ const placed = update.placedRelease();
150
+ void stop(() => restart(`Kit ${placed} is placed; its supervisor starts it`));
145
151
  }
146
152
  else if (!reported) {
147
153
  reported = true;
148
- logged(house.deliver('/kit/idle', {}, idle));
154
+ logged(house.deliver('kits/report-idle', {}, idle));
149
155
  }
150
156
  };
151
157
  const calls = new Calls(house, changed);
@@ -154,28 +160,35 @@ export async function resident() {
154
160
  agents,
155
161
  copies,
156
162
  calls,
157
- send: (notification) => connection?.send(notification) ?? false,
163
+ send: (oneWayCall) => connection?.send(oneWayCall) ?? false,
158
164
  changed,
159
165
  });
160
166
  const signIns = new SignIns(house, agents, calls);
161
167
  const update = new KitUpdate(calls);
162
- if (process.env.HOUSE_KIT_SANDBOX !== '1')
163
- takeUnservedRelease((release) => logged(update.takeRefused(release)));
168
+ takeUnservedRelease((release) => logged(update.takeRefused(release)));
164
169
  removeInputs();
165
- const scripts = new Scripts(calls, (notification) => connection?.send(notification) ?? false);
170
+ const scripts = new Scripts(calls, (oneWayCall) => connection?.send(oneWayCall) ?? false);
166
171
  for (const signal of ['SIGTERM', 'SIGINT']) {
167
172
  process.once(signal, () => {
168
- killDescendants();
169
- removeInputs();
170
- process.kill(process.pid, signal);
173
+ void stop(() => {
174
+ removeInputs();
175
+ process.kill(process.pid, signal);
176
+ });
171
177
  });
172
178
  }
173
- await house.deliver('/kit/restarted', {}).catch(report);
179
+ const unenrolled = () => {
180
+ if (!enrolled())
181
+ void stop(() => process.exit(1));
182
+ };
183
+ watch(kitHome(), unenrolled);
184
+ unenrolled();
185
+ await house.deliver('kits/report-restart', {}).catch(report);
174
186
  logged(agents.refresh());
175
- agents.keepCurrent();
187
+ agents.keepCurrent(() => process.env.HOUSE_KIT_SANDBOX === '1' && reported);
176
188
  connection = holdConnection({
177
189
  opened: () => {
178
190
  conversations.opened();
191
+ scripts.connected();
179
192
  changed();
180
193
  logged(copies.connected());
181
194
  },
@@ -187,21 +200,15 @@ export async function resident() {
187
200
  update.take(call);
188
201
  else if (call.kind === 'run_wizard' || call.kind === 'run_function')
189
202
  scripts.start(call);
190
- else if (CONVERSATION_METHODS.has(call.kind))
203
+ else
191
204
  conversations.call(call);
192
- else {
193
- const refused = { refused: unknownMethod(call.kind) };
194
- void calls.carry(call.input_id, async () => ({ result: refused }));
195
- }
196
205
  },
197
- notification: (notification) => {
198
- if (notification.type === 'watching')
199
- conversations.watching(notification.watching === true);
200
- if (notification.type === 'authority_changed')
201
- logged(copies.changed(notification.rooms));
202
- if (notification.type === 'work_available' && notification.subject === 'agents')
206
+ oneWayCall: (oneWayCall) => {
207
+ if (oneWayCall.type === 'watching')
208
+ conversations.watching(oneWayCall.watching);
209
+ if (oneWayCall.type === 'work_available' && oneWayCall.subject === 'agents')
203
210
  logged(agents.refresh());
204
- scripts.notified(notification);
211
+ scripts.notified(oneWayCall);
205
212
  },
206
213
  });
207
214
  }
package/dist/scripts.js CHANGED
@@ -15,6 +15,11 @@ const SIGNALLED = 128;
15
15
  const NEWLINE = 0x0a;
16
16
  const NO_BASH = "bash is not on the login shell's PATH";
17
17
  const LOST = { refused: 'the Kit lost its connection to House' };
18
+ const UNSENT_CHARS = 64_000;
19
+ // House holds a Web Wizard's run two minutes for its Kit to connect again, so the script waits as long for a dropped connection to come back.
20
+ const RETURN_MS = 120_000;
21
+ // House takes a run on again with its page's terminal size in the frames right after the Kit connects, so a script it sent nothing for in ten seconds is one House no longer carries.
22
+ const TAKEN_ON_MS = 10_000;
18
23
  function causeOf(error) {
19
24
  return error instanceof Error ? error.message : String(error);
20
25
  }
@@ -44,6 +49,12 @@ async function inputFile(value) {
44
49
  export function removeInputs() {
45
50
  rmSync(inputs(), { recursive: true, force: true });
46
51
  }
52
+ function latest(screen) {
53
+ if (screen.length <= UNSENT_CHARS)
54
+ return screen;
55
+ const line = screen.indexOf('\n', screen.length - UNSENT_CHARS);
56
+ return screen.slice(line < 0 ? screen.length - UNSENT_CHARS : line + 1);
57
+ }
47
58
  function struck(line, typed) {
48
59
  return typed.some((typedLine) => line.includes(typedLine));
49
60
  }
@@ -130,25 +141,54 @@ export class Scripts {
130
141
  start(call) {
131
142
  void this.calls.carry(call.input_id, () => this.run(call.input_id, planned(call)));
132
143
  }
133
- notified(notification) {
134
- const run = this.runs.get(String(notification.wizard));
144
+ notified(oneWayCall) {
145
+ if (!('wizard' in oneWayCall))
146
+ return;
147
+ const run = this.runs.get(oneWayCall.wizard);
135
148
  if (run === undefined)
136
149
  return;
137
- if (notification.type === 'wizard_input')
138
- this.typed(run, String(notification.data));
139
- if (notification.type === 'wizard_size')
140
- this.resized(run, { cols: Number(notification.cols), rows: Number(notification.rows) });
141
- if (notification.type === 'wizard_end' && run.plan.terminal === 'page')
150
+ this.waited(run, null);
151
+ if (oneWayCall.type === 'wizard_input')
152
+ this.typed(run, oneWayCall.data);
153
+ if (oneWayCall.type === 'wizard_size')
154
+ this.resized(run, { cols: oneWayCall.cols, rows: oneWayCall.rows });
155
+ if (oneWayCall.type === 'wizard_end' && run.plan.terminal === 'page')
142
156
  this.end(run, {});
143
157
  }
144
158
  disconnected() {
145
- for (const run of this.runs.values())
146
- this.end(run, LOST);
159
+ for (const run of this.runs.values()) {
160
+ if (run.plan.terminal === 'page')
161
+ this.waited(run, RETURN_MS);
162
+ else
163
+ this.end(run, LOST);
164
+ }
165
+ }
166
+ connected() {
167
+ for (const [id, run] of this.runs) {
168
+ if (run.waiting === null)
169
+ continue;
170
+ this.waited(run, TAKEN_ON_MS);
171
+ if (run.unsent !== '' && this.send({ type: 'wizard_output', wizard: id, data: run.unsent }))
172
+ run.unsent = '';
173
+ }
147
174
  }
148
175
  async run(id, plan) {
149
176
  const size = plan.terminal === 'page' ? null : FIRST_SIZE;
150
177
  const output = plan.function === null ? null : new KeptOutput(plan.function.outputCap);
151
- const run = { plan, input: null, output, process: null, pipes: [], terminal: null, size, typed: [], ended: null, sized: Promise.withResolvers() };
178
+ const run = {
179
+ plan,
180
+ input: null,
181
+ output,
182
+ process: null,
183
+ pipes: [],
184
+ terminal: null,
185
+ size,
186
+ typed: [],
187
+ unsent: '',
188
+ waiting: null,
189
+ ended: null,
190
+ sized: Promise.withResolvers(),
191
+ };
152
192
  if (size !== null)
153
193
  run.sized.resolve();
154
194
  this.runs.set(id, run);
@@ -184,7 +224,8 @@ export class Scripts {
184
224
  run.process = terminal;
185
225
  run.terminal = terminal;
186
226
  terminal.onData((data) => {
187
- this.send({ type: 'wizard_output', wizard: id, data });
227
+ if (!this.send({ type: 'wizard_output', wizard: id, data }))
228
+ run.unsent = latest(`${run.unsent}${data}`);
188
229
  output?.add(data);
189
230
  });
190
231
  for (const data of run.typed.splice(0))
@@ -242,10 +283,17 @@ export class Scripts {
242
283
  end(run, result) {
243
284
  if (run.ended !== null)
244
285
  return;
286
+ this.waited(run, null);
245
287
  run.ended = result;
246
288
  run.sized.resolve();
247
289
  this.stop(run);
248
290
  }
291
+ waited(run, ms) {
292
+ if (run.waiting !== null)
293
+ clearTimeout(run.waiting);
294
+ run.waiting = ms === null ? null : setTimeout(() => this.end(run, LOST), ms);
295
+ run.waiting?.unref();
296
+ }
249
297
  stop(run) {
250
298
  if (run.process !== null)
251
299
  killTree(run.process);