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

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.
Files changed (107) hide show
  1. package/README.md +45 -26
  2. package/dist/abort.js +9 -0
  3. package/dist/acp.js +48 -85
  4. package/dist/agents.js +312 -53
  5. package/dist/api.js +40 -4
  6. package/dist/app-git.js +48 -0
  7. package/dist/bootstrap.json +10 -14
  8. package/dist/bridge.js +92 -77
  9. package/dist/chatgpt.js +32 -0
  10. package/dist/clis-main.js +23 -0
  11. package/dist/clis.js +213 -71
  12. package/dist/codex-main.js +58 -0
  13. package/dist/conversations.js +428 -233
  14. package/dist/copies.js +233 -171
  15. package/dist/end.js +23 -0
  16. package/dist/enrol-main.js +7 -1
  17. package/dist/events.js +525 -0
  18. package/dist/files.js +24 -3
  19. package/dist/git-main.js +2 -2
  20. package/dist/git.js +15 -9
  21. package/dist/home.js +127 -9
  22. package/dist/house-cli.js +291 -0
  23. package/dist/house-main.js +5 -102
  24. package/dist/inputs.js +37 -0
  25. package/dist/instructions.js +10 -31
  26. package/dist/kit-cli.js +68 -0
  27. package/dist/kit-main.js +8 -16
  28. package/dist/login.js +129 -94
  29. package/dist/logout.js +19 -0
  30. package/dist/mcp.js +39 -0
  31. package/dist/operation.js +7 -4
  32. package/dist/parts.js +82 -0
  33. package/dist/placement.js +30 -0
  34. package/dist/refusals.js +53 -0
  35. package/dist/relay.js +20 -0
  36. package/dist/resident.js +122 -41
  37. package/dist/scope.js +203 -0
  38. package/dist/secret-input.js +7 -2
  39. package/dist/service-main.js +9 -0
  40. package/dist/service.js +33 -0
  41. package/dist/shell.js +3 -0
  42. package/dist/sign-in.js +47 -28
  43. package/dist/skills.js +80 -16
  44. package/dist/stream.js +89 -13
  45. package/dist/transcription.js +170 -0
  46. package/dist/update.js +138 -0
  47. package/dist/wire.js +6 -0
  48. package/dist/work.js +346 -0
  49. package/how-we-work.md +22 -14
  50. package/package.json +5 -7
  51. package/skills/ask-matt/SKILL.md +17 -11
  52. package/skills/ask-matt/agents/openai.yaml +1 -0
  53. package/skills/code-review/SKILL.md +5 -5
  54. package/skills/codebase-design/DESIGN-IT-TWICE.md +1 -1
  55. package/skills/codebase-design/SKILL.md +0 -2
  56. package/skills/diagnosing-bugs/SKILL.md +2 -4
  57. package/skills/domain-modeling/{CONTEXT-FORMAT.md → GLOSSARY-FORMAT.md} +10 -10
  58. package/skills/domain-modeling/SKILL.md +12 -14
  59. package/skills/grill-me/SKILL.md +1 -2
  60. package/skills/grill-me/agents/openai.yaml +1 -0
  61. package/skills/grill-with-docs/SKILL.md +1 -2
  62. package/skills/grill-with-docs/agents/openai.yaml +1 -0
  63. package/skills/grilling/SKILL.md +2 -2
  64. package/skills/handoff/SKILL.md +2 -3
  65. package/skills/handoff/agents/openai.yaml +1 -0
  66. package/skills/implement/SKILL.md +5 -4
  67. package/skills/implement/agents/openai.yaml +1 -0
  68. package/skills/implement-spec/SKILL.md +40 -0
  69. package/skills/implement-spec/agents/openai.yaml +5 -0
  70. package/skills/improve-codebase-architecture/SKILL.md +6 -7
  71. package/skills/improve-codebase-architecture/agents/openai.yaml +1 -0
  72. package/skills/pr/CREDITS.md +3 -0
  73. package/skills/pr/LICENSE +21 -0
  74. package/skills/pr/SKILL.md +170 -0
  75. package/skills/pr/agents/openai.yaml +3 -0
  76. package/skills/prototype/SKILL.md +0 -2
  77. package/skills/research/SKILL.md +0 -2
  78. package/skills/retro/LICENSE +21 -0
  79. package/skills/retro/SKILL.md +44 -0
  80. package/skills/retro/agents/openai.yaml +5 -0
  81. package/skills/tdd/SKILL.md +2 -4
  82. package/skills/teach/SKILL.md +3 -4
  83. package/skills/teach/agents/openai.yaml +1 -0
  84. package/skills/to-questionnaire/SKILL.md +1 -2
  85. package/skills/to-questionnaire/agents/openai.yaml +1 -0
  86. package/skills/to-spec/SKILL.md +1 -2
  87. package/skills/to-spec/agents/openai.yaml +1 -0
  88. package/skills/to-tickets/SKILL.md +3 -4
  89. package/skills/to-tickets/agents/openai.yaml +1 -0
  90. package/skills/triage/AGENT-BRIEF.md +207 -0
  91. package/skills/triage/LICENSE +21 -0
  92. package/skills/triage/OUT-OF-SCOPE.md +105 -0
  93. package/skills/triage/SKILL.md +112 -0
  94. package/skills/triage/agents/openai.yaml +5 -0
  95. package/skills/wait-what/SKILL.md +2 -3
  96. package/skills/wait-what/agents/openai.yaml +1 -0
  97. package/skills/wayfinder/SKILL.md +5 -6
  98. package/skills/wayfinder/agents/openai.yaml +1 -0
  99. package/skills/wizard/LICENSE +21 -0
  100. package/skills/wizard/SKILL.md +44 -0
  101. package/skills/wizard/agents/openai.yaml +3 -0
  102. package/skills/wizard/template.sh +223 -0
  103. package/skills/writing-for-agents/SKILL.md +0 -2
  104. package/dist/blocks.js +0 -51
  105. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  106. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  107. /package/skills/{resolving-merge-conflicts → implement-spec}/LICENSE +0 -0
package/dist/skills.js CHANGED
@@ -1,18 +1,31 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { readFileSync } from 'node:fs';
2
- import { cp, lstat, mkdir, readdir, realpath, rm, symlink, writeFile } from 'node:fs/promises';
3
+ import { cp, lstat, mkdir, readdir, realpath, rm, symlink } from 'node:fs/promises';
3
4
  import { homedir } from 'node:os';
4
5
  import { join, relative } from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
6
7
  import { parse } from 'yaml';
7
8
  import { KIT_VERSION } from './clis.js';
8
- import { refusalCode } from './copies.js';
9
9
  import { kitHome, readConfiguration, readHome, writeHome } from './home.js';
10
- export const HOW_WE_WORK = '/private/library/how-we-work.md';
10
+ import { refusalOf } from './refusals.js';
11
+ const HOW_WE_WORK = '/rooms/private/how-we-work.md';
11
12
  const SKILL_SET = fileURLToPath(new URL('../skills/', import.meta.url));
12
13
  const HOW_WE_WORK_TEXT = readFileSync(new URL('../how-we-work.md', import.meta.url), 'utf8');
14
+ const SHIPPED_HOW_WE_WORK = [
15
+ 'ae4dda60da7b174f22dc5fa9bf07fc27c25864932a74230de4f9f509ddd91f41',
16
+ '0bdcd43e1603ba6673a3cae56d70bbf90657cbeefd124e91a47be2ca1cbd6c93',
17
+ '4106a87ec66da6f7b2a10e74d18e6559d68d5f4fe7415dae68f5c7bdb9081968',
18
+ 'ac814a2197038f037b657bb719340395f89f319ac9fcdd386629c3fe2cec68f1',
19
+ '29951ee394aad9979eecfed3e5dc32c2c86e2226b6a380db5dbd4f305f4d1156',
20
+ ];
13
21
  const RECORD = 'skill-set.json';
14
- const CREATED = 'how-we-work-created';
22
+ const WRITTEN = 'how-we-work.json';
15
23
  const UNWRITABLE = new Set(['room_not_found', 'operation_denied']);
24
+ const PRESENT = new Set(['path_exists']);
25
+ const CHANGED = new Set(['base_revision_stale', 'path_absent']);
26
+ const UNREADABLE = /^(?:\S+: )?(?:path_not_found|room_not_found|operation_denied)\b/;
27
+ const FAILED = /^exit: [1-9]\d*$/;
28
+ const CUT = /^stderr: shell: output_cut (\d+) of \d+ bytes; continue with: (.+)$/;
16
29
  function skillsDirectory() {
17
30
  return join(homedir(), '.agents', 'skills');
18
31
  }
@@ -50,6 +63,14 @@ async function install() {
50
63
  await writeHome(RECORD, { version: KIT_VERSION, names });
51
64
  }
52
65
  export async function placeSkillSet() {
66
+ try {
67
+ await replaceSkillSet();
68
+ }
69
+ catch (error) {
70
+ process.stderr.write(`kit: the skills could not be placed: ${error.message}\n`);
71
+ }
72
+ }
73
+ async function replaceSkillSet() {
53
74
  const accepted = (await readConfiguration()).skills;
54
75
  const installed = await readHome(RECORD);
55
76
  if (accepted && installed?.version === KIT_VERSION)
@@ -63,21 +84,64 @@ export async function placeSkillSet() {
63
84
  else
64
85
  await rm(join(kitHome(), RECORD), { force: true });
65
86
  }
66
- function documentPresent(refusal) {
67
- const { conflicts } = parse(refusal.slice(refusal.indexOf('\n') + 1));
68
- return conflicts.some((conflict) => conflict.code === 'path_exists');
87
+ function sha256(text) {
88
+ return createHash('sha256').update(text).digest('hex');
89
+ }
90
+ function cutOf(lines) {
91
+ const cut = CUT.exec(lines[0] ?? '');
92
+ return cut !== null && Buffer.byteLength(lines.slice(1).join('\n')) === Number(cut[1]) ? cut : null;
93
+ }
94
+ export async function readHowWeWork(bridge) {
95
+ let document = '';
96
+ for (let command = `cat ${HOW_WE_WORK}`; command !== undefined;) {
97
+ const read = await bridge.tool('shell', { command });
98
+ const text = read.content.map((content) => content.text).join('\n');
99
+ const lines = text.split('\n');
100
+ if (read.isError === true || (FAILED.test(lines[0] ?? '') && lines[1]?.startsWith('stderr: '))) {
101
+ const refusal = read.isError === true ? text : lines.slice(1).join('\n').replace(/^stderr: /gm, '');
102
+ if (UNREADABLE.test(refusal))
103
+ return '';
104
+ throw new Error(refusal);
105
+ }
106
+ const cut = cutOf(lines);
107
+ document += lines.slice(cut === null ? 0 : 1).join('\n');
108
+ command = cut?.[2];
109
+ }
110
+ return document;
111
+ }
112
+ async function currentRevision(bridge) {
113
+ const inspected = await bridge.tool('inspect', { path: HOW_WE_WORK });
114
+ const text = inspected.content.map((content) => content.text).join('\n');
115
+ if (inspected.isError === true)
116
+ throw new Error(text);
117
+ return parse(text).revisions[0].revision;
118
+ }
119
+ async function edit(bridge, change, kept) {
120
+ const edited = await bridge.tool('edit', { changes: [{ ...change, path: HOW_WE_WORK, content: HOW_WE_WORK_TEXT }] });
121
+ if (edited.isError !== true)
122
+ return 'written';
123
+ const text = edited.content.map((content) => content.text).join('\n');
124
+ const refusal = refusalOf(text);
125
+ if (UNWRITABLE.has(refusal?.code ?? ''))
126
+ return 'unwritable';
127
+ if (refusal?.code === 'edit_conflict' && refusal.conflicts.some((conflict) => kept.has(conflict)))
128
+ return 'kept';
129
+ throw new Error(text);
69
130
  }
70
131
  export async function createHowWeWork(bridge) {
71
- if ((await readHome(RECORD)) === null || (await present(join(kitHome(), CREATED))))
132
+ if (!(await readConfiguration()).skills || (await readHome(RECORD))?.version === undefined)
133
+ return;
134
+ const current = sha256(HOW_WE_WORK_TEXT);
135
+ if ((await readHome(WRITTEN)) === current)
136
+ return;
137
+ const created = await edit(bridge, { op: 'create' }, PRESENT);
138
+ if (created === 'unwritable')
72
139
  return;
73
- const created = await bridge.tool('edit', { changes: [{ op: 'create', path: HOW_WE_WORK, content: HOW_WE_WORK_TEXT }] });
74
- if (created.isError === true) {
75
- const text = created.content.map((content) => content.text).join('\n');
76
- const code = refusalCode(text);
77
- if (UNWRITABLE.has(code))
140
+ if (created === 'kept') {
141
+ const base = await currentRevision(bridge);
142
+ const held = sha256(await readHowWeWork(bridge));
143
+ if (held !== current && SHIPPED_HOW_WE_WORK.includes(held) && (await edit(bridge, { op: 'replace', base }, CHANGED)) === 'unwritable')
78
144
  return;
79
- if (code !== 'edit_conflict' || !documentPresent(text))
80
- throw new Error(text);
81
145
  }
82
- await writeFile(join(kitHome(), CREATED), '');
146
+ await writeHome(WRITTEN, current);
83
147
  }
package/dist/stream.js CHANGED
@@ -1,39 +1,115 @@
1
+ import { subscribe } from 'node:diagnostics_channel';
2
+ import { finalRefusal, HouseRefusal, retryDelay } from './api.js';
3
+ import { end, REPLACED, signInAgain, updateRequired } from './end.js';
1
4
  import { readEnrolment } from './home.js';
2
- const SUBPROTOCOL = 'house.kit.stream.1';
5
+ import { relayed } from './relay.js';
6
+ import { KIT_WIRE, tooOld } from './wire.js';
7
+ const PATH = '/kit/stream';
8
+ const SUBPROTOCOL = `house.kit.stream.${KIT_WIRE}`;
9
+ const REFUSAL_HEADER = 'x-house-refusal';
10
+ // House beats each stream every thirty seconds, so two silent beats mean this Kit cannot hear House.
11
+ export const STREAM_SILENCE_MS = 60_000;
12
+ const SYSTEM_STREAM_CLOCK = {
13
+ later: (delay, callback) => setTimeout(callback, delay),
14
+ clear: (timer) => clearTimeout(timer),
15
+ };
16
+ export class StreamSilence {
17
+ timer = null;
18
+ silent;
19
+ clock;
20
+ interval;
21
+ constructor(silent, clock = SYSTEM_STREAM_CLOCK, interval = STREAM_SILENCE_MS) {
22
+ this.silent = silent;
23
+ this.clock = clock;
24
+ this.interval = interval;
25
+ }
26
+ heard() {
27
+ this.stop();
28
+ this.timer = this.clock.later(this.interval, () => {
29
+ this.timer = null;
30
+ this.silent();
31
+ });
32
+ }
33
+ stop() {
34
+ if (this.timer === null)
35
+ return;
36
+ this.clock.clear(this.timer);
37
+ this.timer = null;
38
+ }
39
+ }
3
40
  function streamUrl(house) {
4
- const url = new URL('/kit/stream', house);
41
+ const url = new URL(PATH, house);
5
42
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
6
43
  return url;
7
44
  }
45
+ function header(headers, name) {
46
+ for (let index = 0; index < headers.length; index += 2) {
47
+ if (headers[index].toString('latin1').toLowerCase() === name)
48
+ return headers[index + 1].toString('latin1');
49
+ }
50
+ return '';
51
+ }
52
+ let refused = null;
53
+ subscribe('undici:request:headers', (message) => {
54
+ const { request, response } = message;
55
+ if (!request.path.endsWith(PATH))
56
+ return;
57
+ refused = new HouseRefusal(PATH, response.statusCode, header(response.headers, REFUSAL_HEADER) || response.statusText);
58
+ });
8
59
  export function holdStream(handlers) {
9
60
  let socket = null;
10
61
  let failures = 0;
11
62
  const connect = async () => {
12
63
  const { house, credential } = (await readEnrolment());
13
- const opening = new WebSocket(streamUrl(house), {
64
+ refused = null;
65
+ const opening = new WebSocket(relayed(streamUrl(house)), {
14
66
  protocols: [SUBPROTOCOL],
15
67
  headers: { authorization: `Bearer ${credential}` },
16
68
  });
17
69
  let opened = false;
70
+ let silence = null;
71
+ const closed = (event) => {
72
+ silence?.stop();
73
+ silence = null;
74
+ if (socket === opening)
75
+ socket = null;
76
+ process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
77
+ if (event.reason === 'replaced')
78
+ end(REPLACED);
79
+ if (event.reason === 'credential_rejected' || refused?.status === 401) {
80
+ void signInAgain(credential);
81
+ return;
82
+ }
83
+ if (refused !== null && tooOld(refused.text))
84
+ updateRequired();
85
+ if (finalRefusal(refused))
86
+ end(refused.message);
87
+ // A closed socket reopens in one to three seconds, spread so Kits one restart closed return apart; an opening House refused as retryable or left unanswered backs off on the jittered curve.
88
+ setTimeout(() => void connect(), opened ? 1000 + Math.random() * 2000 : retryDelay(failures++));
89
+ };
18
90
  opening.onopen = () => {
19
91
  opened = true;
20
92
  failures = 0;
21
93
  socket = opening;
94
+ silence = new StreamSilence(() => {
95
+ if (socket !== opening)
96
+ return;
97
+ socket = null;
98
+ opening.onclose = null;
99
+ opening.close();
100
+ closed(new CloseEvent('close', { code: 1006, reason: 'heartbeat_missed' }));
101
+ });
102
+ silence.heard();
22
103
  handlers.opened();
23
104
  };
24
105
  opening.onmessage = (event) => {
25
- handlers.frame(JSON.parse(String(event.data)));
106
+ silence?.heard();
107
+ const frame = JSON.parse(String(event.data));
108
+ if (frame.type !== 'beat')
109
+ handlers.frame(frame);
26
110
  };
27
111
  opening.onerror = () => undefined;
28
- opening.onclose = (event) => {
29
- if (socket === opening)
30
- socket = null;
31
- process.stderr.write(`kit: control stream closed ${event.code} ${event.reason}\n`);
32
- const delay = opened
33
- ? 1000 + Math.random() * 2000
34
- : Math.min(30_000, 1000 * 2 ** failures++);
35
- setTimeout(() => void connect(), delay);
36
- };
112
+ opening.onclose = closed;
37
113
  };
38
114
  void connect();
39
115
  return {
@@ -0,0 +1,170 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { chmod, mkdir, mkdtemp, readdir, readFile, rename, rm, stat } from 'node:fs/promises';
4
+ import { availableParallelism, tmpdir } from 'node:os';
5
+ import { basename, join } from 'node:path';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { unlessAborted } from './abort.js';
8
+ import { failureOf, run } from './clis.js';
9
+ import { kitHome } from './home.js';
10
+ const RELEASE = 'https://github.com/agentshouse/kit/releases/download/engine-2';
11
+ export const MODEL = {
12
+ url: 'https://huggingface.co/ggml-org/parakeet-GGUF/resolve/35156454d1a39de06863303dd209fd2bed6ee079/ggml-parakeet-tdt-0.6b-v3-q4_k.bin',
13
+ sha256: '8b205b8b39c6535e153de6fb11c51db46125d45c4f16ba496fe41a0fe71b885e',
14
+ executable: false,
15
+ };
16
+ export const ENGINES = {
17
+ 'linux-x64': {
18
+ decoder: { url: `${RELEASE}/ffmpeg-linux-x86_64`, sha256: '1f8235d206428305afb89c6e8ab99d100425a0ba61e22bb4c7aff017db8c8de5', executable: true },
19
+ engine: { url: `${RELEASE}/parakeet-cli-linux-x86_64`, sha256: 'bb2585695992fe1927a33960002cdf51b8a90a96ad65593c3d0a9f1fbc0865c2', executable: true },
20
+ },
21
+ 'linux-arm64': {
22
+ decoder: { url: `${RELEASE}/ffmpeg-linux-aarch64`, sha256: 'a7e08a0fae0179d1078312f6bb13d2a9aa4d4c71a1d82a022953f25dee452f5e', executable: true },
23
+ engine: { url: `${RELEASE}/parakeet-cli-linux-aarch64`, sha256: 'cbc0bedc8daae97f1ef9dcee4200c06226218e300e0fd62ead1306d22742b7ed', executable: true },
24
+ },
25
+ 'darwin-arm64': {
26
+ decoder: { url: `${RELEASE}/ffmpeg-darwin-arm64`, sha256: '7abe154aaed3d6b49f5167ca7221bb66bed51388925d99a7e4261a41fe52fba6', executable: true },
27
+ engine: { url: `${RELEASE}/parakeet-cli-darwin-arm64`, sha256: '9a2aafc0922ad7c0b6db6eff1641e96572ba32ac40bf995a1df242ed2febf297', executable: true },
28
+ },
29
+ };
30
+ const CHUNK_SECONDS = 20;
31
+ let held = Promise.resolve();
32
+ let holding = Promise.resolve();
33
+ let setting = null;
34
+ let downloading = null;
35
+ let readiness = { installed: false, failure: null };
36
+ function directory() {
37
+ return join(kitHome(), 'transcription');
38
+ }
39
+ function installed(artifact) {
40
+ return join(directory(), artifact.sha256);
41
+ }
42
+ async function executed(command, args, signal) {
43
+ // A download or a transcription runs as long as its size needs; the setting turning off or the turn's interrupt or end aborts it instead.
44
+ const ran = await run(command, args, 0, false, signal);
45
+ if (ran.status !== 0)
46
+ throw new Error(failureOf(ran, basename(command)));
47
+ return ran.stdout;
48
+ }
49
+ function present(path) {
50
+ return stat(path).then(() => true, () => false);
51
+ }
52
+ async function threads() {
53
+ const [quota, period] = (await readFile('/sys/fs/cgroup/cpu.max', 'utf8').catch(() => 'max')).split(' ');
54
+ const allowed = quota === 'max' ? Infinity : Math.ceil(Number(quota) / Number(period));
55
+ return Math.max(1, Math.floor(Math.min(availableParallelism(), allowed) / 2));
56
+ }
57
+ async function sha256(path) {
58
+ const hash = createHash('sha256');
59
+ await pipeline(createReadStream(path), hash);
60
+ return hash.digest('hex');
61
+ }
62
+ function causeOf(error) {
63
+ return error instanceof Error ? error.message : String(error);
64
+ }
65
+ function pinnedHere() {
66
+ return ENGINES[`${process.platform}-${process.arch}`];
67
+ }
68
+ async function install(artifacts, signal) {
69
+ await mkdir(directory(), { recursive: true });
70
+ const pinned = new Set(artifacts.map((artifact) => artifact.sha256));
71
+ for (const name of await readdir(directory())) {
72
+ if (!pinned.has(name))
73
+ await rm(join(directory(), name), { recursive: true, force: true });
74
+ }
75
+ const missing = [];
76
+ for (const artifact of artifacts)
77
+ if (!(await present(installed(artifact))))
78
+ missing.push(artifact);
79
+ try {
80
+ for (const artifact of missing) {
81
+ const part = `${installed(artifact)}.part`;
82
+ // Three retries carry a large download past a dropped connection before the download fails.
83
+ await executed('curl', ['-fsSL', '--retry', '3', '-o', part, artifact.url], signal);
84
+ if ((await sha256(part)) !== artifact.sha256)
85
+ throw new Error(`${artifact.url} does not match its sha256`);
86
+ }
87
+ for (const artifact of missing) {
88
+ if (artifact.executable)
89
+ await chmod(`${installed(artifact)}.part`, 0o755);
90
+ await rename(`${installed(artifact)}.part`, installed(artifact));
91
+ }
92
+ }
93
+ finally {
94
+ for (const artifact of missing)
95
+ await rm(`${installed(artifact)}.part`, { force: true });
96
+ }
97
+ }
98
+ function reported(next) {
99
+ const changed = next.installed !== readiness.installed || next.failure !== readiness.failure;
100
+ readiness = next;
101
+ return changed;
102
+ }
103
+ async function settle(transcribe) {
104
+ if (transcribe === setting)
105
+ return false;
106
+ setting = transcribe;
107
+ if (!transcribe) {
108
+ await rm(directory(), { recursive: true, force: true });
109
+ return reported({ installed: false, failure: null });
110
+ }
111
+ const download = new AbortController();
112
+ downloading = download;
113
+ try {
114
+ const pinned = pinnedHere();
115
+ await install([pinned.decoder, pinned.engine, MODEL], download.signal);
116
+ return reported({ installed: true, failure: null });
117
+ }
118
+ catch (error) {
119
+ await rm(directory(), { recursive: true, force: true });
120
+ return reported({ installed: false, failure: download.signal.aborted ? null : causeOf(error) });
121
+ }
122
+ finally {
123
+ downloading = null;
124
+ }
125
+ }
126
+ export function holdTranscription(transcribe) {
127
+ if (!transcribe)
128
+ downloading?.abort();
129
+ const settled = holding.then(() => settle(transcribe));
130
+ holding = settled.catch(() => undefined);
131
+ return settled;
132
+ }
133
+ export function transcriptionReport() {
134
+ return readiness;
135
+ }
136
+ async function transcribed(path, signal) {
137
+ const pinned = pinnedHere();
138
+ const work = await mkdtemp(join(tmpdir(), 'kit-transcription-'));
139
+ try {
140
+ await executed(installed(pinned.decoder), ['-nostdin', '-hide_banner', '-loglevel', 'error', '-i', path, '-ar', '16000', '-ac', '1', '-c:a', 'pcm_s16le',
141
+ '-f', 'segment', '-segment_time', String(CHUNK_SECONDS), join(work, '%05d.wav')], signal);
142
+ const parts = (await readdir(work)).sort().flatMap((part) => ['-f', join(work, part)]);
143
+ const text = await executed(installed(pinned.engine), ['-t', String(await threads()), '-np', '-m', installed(MODEL), ...parts], signal);
144
+ return text
145
+ .split('\n')
146
+ .map((line) => line.trim())
147
+ .filter((line) => line !== '')
148
+ .join(' ');
149
+ }
150
+ finally {
151
+ await rm(work, { recursive: true, force: true });
152
+ }
153
+ }
154
+ export async function transcribe(path, signal) {
155
+ if (!readiness.installed)
156
+ return null;
157
+ const before = held;
158
+ let release;
159
+ const mine = new Promise((resolve) => {
160
+ release = resolve;
161
+ });
162
+ held = Promise.all([before, mine]);
163
+ try {
164
+ await unlessAborted(before, signal);
165
+ return readiness.installed ? await transcribed(path, signal) : null;
166
+ }
167
+ finally {
168
+ release();
169
+ }
170
+ }
package/dist/update.js ADDED
@@ -0,0 +1,138 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { run } from './clis.js';
7
+ import { kitHome, workspaceRoot } from './home.js';
8
+ import { service, throughSudo } from './placement.js';
9
+ function directory() {
10
+ return join(kitHome(), 'update');
11
+ }
12
+ function pending() {
13
+ return join(directory(), 'pending.json');
14
+ }
15
+ function outcome() {
16
+ return join(directory(), 'outcome');
17
+ }
18
+ function unit(inputId) {
19
+ return `house-kit-update-${inputId}`;
20
+ }
21
+ function manager() {
22
+ return service() === 'user' ? ['--user'] : [];
23
+ }
24
+ function elevated() {
25
+ return throughSudo() ? ['sudo', '-n'] : [];
26
+ }
27
+ function account() {
28
+ return throughSudo() ? [`--uid=${process.getuid()}`, `--gid=${process.getgid()}`] : [];
29
+ }
30
+ function placement() {
31
+ return service() === 'user' ? ['--workspace', workspaceRoot()] : ['--linux'];
32
+ }
33
+ function record() {
34
+ return `outcome=$1; shift; bash "$0" "$@"; printf %s "$?" > "$outcome"; ${[...elevated(), 'systemctl', ...manager(), 'start', 'house-kit.service'].join(' ')}`;
35
+ }
36
+ async function pendingInput() {
37
+ try {
38
+ return JSON.parse(await readFile(pending(), 'utf8')).input_id;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ async function recorded() {
45
+ const status = await readFile(outcome(), 'utf8').catch(() => null);
46
+ if (status === null)
47
+ return null;
48
+ return status.trim() === '0' ? {} : { refused: `the Kit bootstrap exited with ${status.trim()}` };
49
+ }
50
+ async function forget(inputId) {
51
+ if ((await pendingInput()) !== inputId)
52
+ return;
53
+ await rm(pending(), { force: true });
54
+ await rm(outcome(), { force: true });
55
+ }
56
+ async function finished(inputId) {
57
+ for (;;) {
58
+ const ack = await recorded();
59
+ if (ack !== null)
60
+ return ack;
61
+ // systemctl answers at once, so ten seconds only bounds a stuck service manager.
62
+ if ((await run('systemctl', [...manager(), 'is-active', '--quiet', unit(inputId)], 10_000)).status !== 0) {
63
+ return (await recorded()) ?? { refused: 'the Kit bootstrap did not finish' };
64
+ }
65
+ // The bootstrap runs for minutes, so checking each second sees its outcome within a second at little cost.
66
+ await new Promise((resolve) => setTimeout(resolve, 1000));
67
+ }
68
+ }
69
+ function rerun(script, inputId, flags) {
70
+ return new Promise((resolve) => {
71
+ const [command, ...args] = [
72
+ ...elevated(),
73
+ 'systemd-run',
74
+ ...manager(),
75
+ ...account(),
76
+ '--wait',
77
+ '--collect',
78
+ '--quiet',
79
+ `--unit=${unit(inputId)}`,
80
+ `--setenv=HOME=${homedir()}`,
81
+ `--setenv=HOUSE_KIT_HOME=${kitHome()}`,
82
+ '/bin/sh',
83
+ '-c',
84
+ record(),
85
+ script,
86
+ outcome(),
87
+ ...placement(),
88
+ ...flags,
89
+ ];
90
+ const child = spawn(command, args, { stdio: ['ignore', 'ignore', 'inherit'] });
91
+ child.on('error', () => resolve({ refused: 'no service manager runs this Kit' }));
92
+ child.on('close', () => resolve(null));
93
+ });
94
+ }
95
+ export class Updates {
96
+ inputs;
97
+ queue = Promise.resolve();
98
+ constructor(inputs) {
99
+ this.inputs = inputs;
100
+ }
101
+ async resumed() {
102
+ const inputId = await pendingInput();
103
+ if (inputId === null)
104
+ return;
105
+ await this.enqueue(inputId, () => finished(inputId));
106
+ }
107
+ start(input) {
108
+ void this.enqueue(input.input_id, () => this.carry(input));
109
+ }
110
+ enqueue(inputId, work) {
111
+ const before = this.queue;
112
+ const carried = this.inputs.carry(inputId, async () => {
113
+ await before;
114
+ return { ack: await work(), acknowledged: () => forget(inputId) };
115
+ });
116
+ this.queue = before.then(() => carried);
117
+ return carried;
118
+ }
119
+ async carry(input) {
120
+ if ((await pendingInput()) === input.input_id)
121
+ return finished(input.input_id);
122
+ const answer = await fetch(input.bootstrap);
123
+ if (!answer.ok)
124
+ return { refused: `the Kit bootstrap could not be downloaded: ${answer.status}` };
125
+ const script = Buffer.from(await answer.arrayBuffer());
126
+ if (createHash('sha256').update(script).digest('hex') !== input.sha256) {
127
+ return { refused: 'the Kit bootstrap does not match its sha256' };
128
+ }
129
+ await mkdir(directory(), { recursive: true, mode: 0o700 });
130
+ const path = join(directory(), 'connect-linux.sh');
131
+ await writeFile(path, script, { mode: 0o700 });
132
+ await rm(outcome(), { force: true });
133
+ await writeFile(pending(), `${JSON.stringify({ input_id: input.input_id })}\n`, { mode: 0o600 });
134
+ return (await rerun(path, input.input_id, input.update_clis ? ['--update-clis'] : [])) ?? (await recorded()) ?? {
135
+ refused: 'the Kit bootstrap did not finish',
136
+ };
137
+ }
138
+ }
package/dist/wire.js ADDED
@@ -0,0 +1,6 @@
1
+ import { refusalOf } from './refusals.js';
2
+ export const KIT_WIRE = 2;
3
+ export const KIT_WIRE_HEADER = 'x-house-kit-wire';
4
+ export function tooOld(text) {
5
+ return refusalOf(text)?.code === 'kit_update_required';
6
+ }