@agentshouse/kit 0.2.1-ccf188e02985d → 0.2.1-ccffb3f637815

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 (164) hide show
  1. package/README.md +37 -41
  2. package/dist/acp.js +66 -12
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +122 -53
  5. package/dist/api.js +15 -10
  6. package/dist/binaries.js +89 -0
  7. package/dist/bridge.js +29 -28
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +62 -50
  12. package/dist/connect.js +108 -0
  13. package/dist/connection.js +120 -0
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +594 -219
  16. package/dist/copies.js +772 -279
  17. package/dist/earlier.js +263 -0
  18. package/dist/end.js +12 -5
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +206 -38
  21. package/dist/git-main.js +24 -29
  22. package/dist/git.js +90 -15
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +80 -29
  25. package/dist/house-cli.js +155 -164
  26. package/dist/house-main.js +3 -3
  27. package/dist/instructions.js +29 -11
  28. package/dist/keys.js +238 -0
  29. package/dist/kit-cli.js +18 -8
  30. package/dist/kit-main.js +3 -3
  31. package/dist/login.js +36 -22
  32. package/dist/logout.js +2 -2
  33. package/dist/mcp.js +42 -3
  34. package/dist/old-references.js +27 -0
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +15 -20
  37. package/dist/refusals.js +37 -21
  38. package/dist/relay.js +21 -0
  39. package/dist/resident.js +128 -82
  40. package/dist/scope.js +15 -4
  41. package/dist/scripts.js +303 -0
  42. package/dist/secret-input.js +1 -1
  43. package/dist/settings.js +188 -0
  44. package/dist/sign-in.js +67 -21
  45. package/dist/silence.js +28 -0
  46. package/dist/skills.js +42 -97
  47. package/dist/supervisor.js +163 -0
  48. package/dist/transcription.js +88 -45
  49. package/dist/translate.js +19 -18
  50. package/dist/update.js +118 -120
  51. package/dist/wire.js +30 -4
  52. package/dist/work.js +27 -2
  53. package/dist/workspace.js +103 -0
  54. package/package.json +26 -22
  55. package/dist/authority-main.js +0 -22
  56. package/dist/bootstrap.json +0 -24
  57. package/dist/chatgpt.js +0 -32
  58. package/dist/clis-main.js +0 -23
  59. package/dist/configure-main.js +0 -6
  60. package/dist/enrol-main.js +0 -10
  61. package/dist/inputs.js +0 -37
  62. package/dist/parts.js +0 -82
  63. package/dist/service-main.js +0 -9
  64. package/dist/service.js +0 -55
  65. package/dist/stream.js +0 -123
  66. package/how-we-work.md +0 -33
  67. package/skills/ask-matt/LICENSE +0 -21
  68. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  69. package/skills/ask-matt/SKILL.md +0 -97
  70. package/skills/ask-matt/agents/openai.yaml +0 -5
  71. package/skills/code-review/LICENSE +0 -21
  72. package/skills/code-review/SKILL.md +0 -89
  73. package/skills/code-review/agents/openai.yaml +0 -3
  74. package/skills/codebase-design/DEEPENING.md +0 -37
  75. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  76. package/skills/codebase-design/LICENSE +0 -21
  77. package/skills/codebase-design/SKILL.md +0 -114
  78. package/skills/codebase-design/agents/openai.yaml +0 -3
  79. package/skills/diagnosing-bugs/LICENSE +0 -21
  80. package/skills/diagnosing-bugs/SKILL.md +0 -138
  81. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  82. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  83. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  84. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  85. package/skills/domain-modeling/LICENSE +0 -21
  86. package/skills/domain-modeling/SKILL.md +0 -74
  87. package/skills/domain-modeling/agents/openai.yaml +0 -3
  88. package/skills/grill-me/LICENSE +0 -21
  89. package/skills/grill-me/SKILL.md +0 -7
  90. package/skills/grill-me/agents/openai.yaml +0 -5
  91. package/skills/grill-with-docs/LICENSE +0 -21
  92. package/skills/grill-with-docs/SKILL.md +0 -7
  93. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  94. package/skills/grilling/LICENSE +0 -21
  95. package/skills/grilling/SKILL.md +0 -30
  96. package/skills/grilling/agents/openai.yaml +0 -3
  97. package/skills/handoff/LICENSE +0 -21
  98. package/skills/handoff/SKILL.md +0 -16
  99. package/skills/handoff/agents/openai.yaml +0 -5
  100. package/skills/implement/LICENSE +0 -21
  101. package/skills/implement/SKILL.md +0 -17
  102. package/skills/implement/agents/openai.yaml +0 -5
  103. package/skills/implement-spec/LICENSE +0 -21
  104. package/skills/implement-spec/SKILL.md +0 -40
  105. package/skills/implement-spec/agents/openai.yaml +0 -5
  106. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  107. package/skills/improve-codebase-architecture/LICENSE +0 -21
  108. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  109. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  110. package/skills/pr/CREDITS.md +0 -3
  111. package/skills/pr/LICENSE +0 -21
  112. package/skills/pr/SKILL.md +0 -170
  113. package/skills/pr/agents/openai.yaml +0 -3
  114. package/skills/prototype/LICENSE +0 -21
  115. package/skills/prototype/LOGIC.md +0 -67
  116. package/skills/prototype/SKILL.md +0 -26
  117. package/skills/prototype/UI.md +0 -112
  118. package/skills/prototype/agents/openai.yaml +0 -3
  119. package/skills/research/LICENSE +0 -21
  120. package/skills/research/SKILL.md +0 -12
  121. package/skills/research/agents/openai.yaml +0 -3
  122. package/skills/retro/LICENSE +0 -21
  123. package/skills/retro/SKILL.md +0 -44
  124. package/skills/retro/agents/openai.yaml +0 -5
  125. package/skills/tdd/LICENSE +0 -21
  126. package/skills/tdd/SKILL.md +0 -38
  127. package/skills/tdd/agents/openai.yaml +0 -3
  128. package/skills/tdd/mocking.md +0 -59
  129. package/skills/tdd/tests.md +0 -77
  130. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  131. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  132. package/skills/teach/LICENSE +0 -21
  133. package/skills/teach/MISSION-FORMAT.md +0 -31
  134. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  135. package/skills/teach/SKILL.md +0 -140
  136. package/skills/teach/agents/openai.yaml +0 -5
  137. package/skills/to-questionnaire/LICENSE +0 -21
  138. package/skills/to-questionnaire/SKILL.md +0 -54
  139. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  140. package/skills/to-spec/LICENSE +0 -21
  141. package/skills/to-spec/SKILL.md +0 -75
  142. package/skills/to-spec/agents/openai.yaml +0 -5
  143. package/skills/to-tickets/LICENSE +0 -21
  144. package/skills/to-tickets/SKILL.md +0 -105
  145. package/skills/to-tickets/agents/openai.yaml +0 -5
  146. package/skills/triage/AGENT-BRIEF.md +0 -207
  147. package/skills/triage/LICENSE +0 -21
  148. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  149. package/skills/triage/SKILL.md +0 -112
  150. package/skills/triage/agents/openai.yaml +0 -5
  151. package/skills/wait-what/LICENSE +0 -21
  152. package/skills/wait-what/SKILL.md +0 -7
  153. package/skills/wait-what/agents/openai.yaml +0 -5
  154. package/skills/wayfinder/LICENSE +0 -21
  155. package/skills/wayfinder/SKILL.md +0 -128
  156. package/skills/wayfinder/agents/openai.yaml +0 -5
  157. package/skills/wizard/LICENSE +0 -21
  158. package/skills/wizard/SKILL.md +0 -44
  159. package/skills/wizard/agents/openai.yaml +0 -3
  160. package/skills/wizard/template.sh +0 -223
  161. package/skills/writing-for-agents/LICENSE +0 -21
  162. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  163. package/skills/writing-for-agents/SKILL.md +0 -81
  164. package/skills/writing-for-agents/agents/openai.yaml +0 -3
package/dist/files.js CHANGED
@@ -1,42 +1,210 @@
1
- import { createHash } from 'node:crypto';
2
- import { mkdir, writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { HouseRefusal, retrying } from './api.js';
5
- import { relayed } from './relay.js';
6
- export function verified(bytes, sha256, name) {
7
- if (createHash('sha256').update(bytes).digest('hex') !== sha256)
8
- throw new Error(`${name} did not arrive whole; download it again`);
9
- return bytes;
10
- }
11
- export async function placeFiles(house, directory, files, signal) {
12
- const paths = [];
13
- for (const file of files) {
14
- const original = await retrying(() => house.post('/kit/conversation/originals/get', { version: file.version, download: true }, signal), signal);
15
- const answer = await fetch(relayed(original.download.url), { signal });
16
- if (!answer.ok)
17
- throw new Error(`${file.name} did not download: ${answer.status}`);
18
- const folder = join(directory, '.house', 'files', original.message, file.version);
19
- await mkdir(join(directory, '.house')).catch((error) => {
20
- if (error.code !== 'EEXIST')
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { createReadStream, createWriteStream } from 'node:fs';
3
+ import { mkdir, rename, rm } from 'node:fs/promises';
4
+ import { request } from 'node:http';
5
+ import { request as httpsRequest } from 'node:https';
6
+ import { basename, dirname, extname, join } from 'node:path';
7
+ import { Readable, Transform } from 'node:stream';
8
+ import { pipeline } from 'node:stream/promises';
9
+ import { parseDocument } from 'yaml';
10
+ import { retryDelay } from './api.js';
11
+ import { Unsettled } from './mcp.js';
12
+ import { proxyUnlessRelayed, relayed } from './relay.js';
13
+ const STALLED_ROUNDS = 8;
14
+ const PART_CHECKSUM = 'x-amz-checksum-sha256';
15
+ const LINK = /\]\((\/rooms\/[^/)\s]+\/[^)\s]+)\)/gu;
16
+ const MEDIA_TYPES = new Map([
17
+ ['avif', 'image/avif'],
18
+ ['csv', 'text/csv'],
19
+ ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
20
+ ['gif', 'image/gif'],
21
+ ['heic', 'image/heic'],
22
+ ['html', 'text/html'],
23
+ ['jpeg', 'image/jpeg'],
24
+ ['jpg', 'image/jpeg'],
25
+ ['json', 'application/json'],
26
+ ['m4a', 'audio/mp4'],
27
+ ['md', 'text/markdown'],
28
+ ['mov', 'video/quicktime'],
29
+ ['mp3', 'audio/mpeg'],
30
+ ['mp4', 'video/mp4'],
31
+ ['ogg', 'audio/ogg'],
32
+ ['pdf', 'application/pdf'],
33
+ ['png', 'image/png'],
34
+ ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
35
+ ['svg', 'image/svg+xml'],
36
+ ['txt', 'text/plain'],
37
+ ['wav', 'audio/wav'],
38
+ ['webm', 'video/webm'],
39
+ ['webp', 'image/webp'],
40
+ ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
41
+ ['zip', 'application/zip'],
42
+ ]);
43
+ export function mediaTypeOf(path) {
44
+ return MEDIA_TYPES.get(extname(path).slice(1).toLowerCase());
45
+ }
46
+ export function linkedPaths(text) {
47
+ return [...new Set(Array.from(text.matchAll(LINK), (link) => link[1]))];
48
+ }
49
+ export function fileInfo(answer) {
50
+ const document = parseDocument(answer);
51
+ if (document.errors.length > 0)
52
+ return null;
53
+ const details = document.toJS();
54
+ if (typeof details?.download !== 'string')
55
+ return null;
56
+ return {
57
+ download: details.download,
58
+ sha256: String(details.sha256),
59
+ revision: String(details.revision),
60
+ bytes: Number(details.bytes),
61
+ media_type: typeof details.media_type === 'string' ? details.media_type : null,
62
+ };
63
+ }
64
+ export function paused(milliseconds) {
65
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
66
+ }
67
+ export function storeRefusal(act, status) {
68
+ return new Error(`the ${act} answered ${status}; ${act} the file again`);
69
+ }
70
+ export function opened(url, method, headers, way, body) {
71
+ return new Promise((answered, failed) => {
72
+ const target = way.socketPath === undefined ? relayed(url) : null;
73
+ if (target !== null)
74
+ proxyUnlessRelayed();
75
+ const sent = target === null
76
+ ? request({ socketPath: way.socketPath, path: url, method, headers }, answered)
77
+ : (target.protocol === 'https:' ? httpsRequest : request)(target, { method, headers }, answered);
78
+ sent.on('error', (error) => failed(way.unreached(error)));
79
+ if (body === undefined)
80
+ sent.end();
81
+ else
82
+ pipeline(body, sent).catch(() => undefined);
83
+ });
84
+ }
85
+ function ranged(file, start, end) {
86
+ return end === start ? undefined : createReadStream(file, { start, end: end - 1 });
87
+ }
88
+ export async function* fileRange(file, start, end, unreadable) {
89
+ try {
90
+ yield* ranged(file, start, end) ?? [];
91
+ }
92
+ catch (error) {
93
+ throw unreadable(error);
94
+ }
95
+ }
96
+ export async function sentPart(url, file, start, end, headers, way) {
97
+ const answer = await opened(url, 'PUT', { ...headers, 'content-length': String(end - start) }, way, ranged(file, start, end));
98
+ await answer.toArray();
99
+ if (answer.statusCode !== 200)
100
+ throw way.refused(answer.statusCode);
101
+ }
102
+ async function partDigests(uploading, partBytes) {
103
+ const whole = createHash('sha256');
104
+ const digests = [];
105
+ for (let start = 0; digests.length === 0 || start < uploading.bytes; start += partBytes) {
106
+ const end = Math.min(start + partBytes, uploading.bytes);
107
+ const digest = createHash('sha256');
108
+ for await (const chunk of uploading.read(start, end)) {
109
+ digest.update(chunk);
110
+ whole.update(chunk);
111
+ }
112
+ digests.push(digest.digest());
113
+ }
114
+ if (whole.digest('hex') !== uploading.sha256)
115
+ throw new Error(`${uploading.name} changed while it was uploaded; upload it again`);
116
+ return digests;
117
+ }
118
+ export async function uploaded(declared, uploading) {
119
+ const partBytes = declared.part_bytes;
120
+ const digests = await partDigests(uploading, partBytes);
121
+ const partSha256 = digests.map((digest) => digest.toString('hex'));
122
+ let answer = await finishing(uploading, declared.id, partSha256);
123
+ let idle = 0;
124
+ let stalled = 0;
125
+ while ('upload' in answer) {
126
+ const { id, parts } = answer.upload;
127
+ let sent = 0;
128
+ let failure = null;
129
+ for (const { part, url } of parts ?? []) {
130
+ const start = (part - 1) * partBytes;
131
+ try {
132
+ await uploading.send(url, start, Math.min(start + partBytes, uploading.bytes), {
133
+ [PART_CHECKSUM]: digests[part - 1].toString('base64'),
134
+ });
135
+ sent++;
136
+ }
137
+ catch (error) {
138
+ failure = error;
139
+ break;
140
+ }
141
+ }
142
+ if (sent > 0) {
143
+ idle = 0;
144
+ stalled = 0;
145
+ }
146
+ else {
147
+ if (failure !== null && ++stalled >= STALLED_ROUNDS)
148
+ throw failure;
149
+ // A round that sent no part, its store unreachable, is followed by the next finishing call on the jittered curve.
150
+ await paused(retryDelay(idle++));
151
+ }
152
+ answer = await finishing(uploading, id, partSha256);
153
+ }
154
+ return answer;
155
+ }
156
+ async function finishing(uploading, upload, partSha256) {
157
+ for (let unsettled = 1;; unsettled++) {
158
+ try {
159
+ return await uploading.finish(upload, partSha256);
160
+ }
161
+ catch (error) {
162
+ if (!(error instanceof Unsettled) || unsettled === STALLED_ROUNDS)
21
163
  throw error;
22
- });
23
- await mkdir(folder, { recursive: true });
24
- const path = join(folder, file.name);
25
- await writeFile(path, verified(Buffer.from(await answer.arrayBuffer()), file.sha256, file.name));
26
- paths.push(path);
164
+ }
165
+ // A finishing call House did not settle, unreached or refused short of final, is sent again on the jittered curve as a conversation resends it, so a dropped connection or a House restart resumes the upload instead of ending it.
166
+ await paused(retryDelay(unsettled - 1));
27
167
  }
28
- return paths;
29
- }
30
- export function uploadBytes(upload, bytes) {
31
- return retrying(async () => {
32
- const answer = await fetch(relayed(upload.url), {
33
- method: 'POST',
34
- headers: { 'content-type': 'application/octet-stream', 'x-house-byte-operation': upload.operation },
35
- body: bytes,
168
+ }
169
+ async function drained(body) {
170
+ for await (const _chunk of body)
171
+ ;
172
+ }
173
+ export async function downloaded(address, fetching, destination, name) {
174
+ for (let asked = 1;; asked++) {
175
+ const { download, sha256 } = await address();
176
+ const answer = await fetching(download);
177
+ if (answer.status === 403 && asked === 1) {
178
+ await drained(answer.body);
179
+ continue;
180
+ }
181
+ if (answer.status !== 200) {
182
+ await drained(answer.body);
183
+ throw storeRefusal('download', answer.status);
184
+ }
185
+ await mkdir(dirname(destination), { recursive: true });
186
+ const partial = join(dirname(destination), `.${basename(destination)}.${randomUUID()}`);
187
+ const digest = createHash('sha256');
188
+ const hashed = new Transform({
189
+ transform(chunk, _encoding, done) {
190
+ digest.update(chunk);
191
+ done(null, chunk);
192
+ },
36
193
  });
37
- const text = await answer.text();
38
- if (!answer.ok)
39
- throw new HouseRefusal(upload.url, answer.status, text);
40
- return JSON.parse(text);
41
- });
194
+ try {
195
+ await pipeline(answer.body, hashed, createWriteStream(partial, { flags: 'wx' }));
196
+ if (digest.digest('hex') !== sha256)
197
+ throw new Error(`${name} did not arrive whole; download it again`);
198
+ await rename(partial, destination);
199
+ }
200
+ catch (error) {
201
+ await rm(partial, { force: true });
202
+ throw error;
203
+ }
204
+ return;
205
+ }
206
+ }
207
+ export async function fetched(url, signal) {
208
+ const answer = await fetch(relayed(url), { signal });
209
+ return { status: answer.status, body: answer.body === null ? Readable.from([]) : Readable.fromWeb(answer.body) };
42
210
  }
package/dist/git-main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
- import { accessSync, constants, realpathSync, statSync } from 'node:fs';
3
+ import { accessSync, constants, mkdtempSync, realpathSync, rmSync, statSync } from 'node:fs';
4
4
  import { request } from 'node:http';
5
5
  import { constants as system } from 'node:os';
6
6
  import { delimiter, dirname, join } from 'node:path';
@@ -52,11 +52,12 @@ function nativeGit() {
52
52
  }
53
53
  return null;
54
54
  }
55
- function captured(git, args) {
55
+ function captured(git, args, { input, index } = {}) {
56
56
  const ran = spawnSync(git, args, {
57
- stdio: ['ignore', 'pipe', 'ignore'],
57
+ input,
58
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'],
58
59
  maxBuffer: Infinity,
59
- env: { ...process.env, LC_ALL: 'C' },
60
+ env: { ...process.env, LC_ALL: 'C', ...(index === undefined ? {} : { GIT_INDEX_FILE: index }) },
60
61
  });
61
62
  return ran.status === 0 ? ran.stdout.toString('utf8') : null;
62
63
  }
@@ -78,30 +79,25 @@ function delegated(git, args) {
78
79
  child.once('close', (status, signal) => settle({ status, signal }));
79
80
  });
80
81
  }
81
- function staged(listing) {
82
- const entries = new Map();
83
- for (const record of (listing ?? '').split('\0')) {
84
- const tab = record.indexOf('\t');
85
- if (tab >= 0)
86
- entries.set(record.slice(tab + 1), record.slice(0, tab).split(' ')[1]);
82
+ function merged(git, copy, common) {
83
+ const staged = (captured(git, [...copy, 'ls-files', '--stage', '-z']) ?? '').split('\0');
84
+ const input = staged.filter((entry) => /^\d+ [0-9a-f]+ 0\t/.test(entry)).map((entry) => `${entry}\0`).join('');
85
+ const scratch = mkdtempSync(join(common, 'house-index-'));
86
+ try {
87
+ const index = join(scratch, 'index');
88
+ captured(git, [...copy, 'update-index', '-z', '--index-info'], { input, index });
89
+ return captured(git, [...copy, 'write-tree'], { index })?.trim();
90
+ }
91
+ finally {
92
+ rmSync(scratch, { recursive: true, force: true });
87
93
  }
88
- return entries;
89
94
  }
90
- function moved(planned, before, after) {
95
+ function moved(git, copy, before) {
96
+ const renames = ['diff-index', '--cached', '-z', '--name-status', '--find-renames=100%', '--diff-filter=R', before];
97
+ const fields = (captured(git, [...copy, ...renames]) ?? '').split('\0');
91
98
  const moves = [];
92
- for (const line of planned.split('\n')) {
93
- if (!line.startsWith('Renaming '))
94
- continue;
95
- const renaming = line.slice('Renaming '.length);
96
- for (let at = renaming.indexOf(' to '); at >= 0; at = renaming.indexOf(' to ', at + 1)) {
97
- const from = renaming.slice(0, at);
98
- const to = renaming.slice(at + 4);
99
- if (before.has(from) && !after.has(from) && after.get(to) === before.get(from)) {
100
- moves.push({ from, to });
101
- break;
102
- }
103
- }
104
- }
99
+ for (let at = 0; at + 2 < fields.length; at += 3)
100
+ moves.push({ from: fields[at + 1], to: fields[at + 2] });
105
101
  return moves;
106
102
  }
107
103
  function reported(socketPath, body) {
@@ -128,11 +124,10 @@ async function observed(git, args) {
128
124
  if (common === undefined || worktree === undefined || !dirname(common).startsWith(`${localCopies()}/`)) {
129
125
  return delegated(git, args);
130
126
  }
131
- const listing = [...globals, '-C', worktree, 'ls-files', '--stage', '-z'];
132
- const before = name === 'mv' ? staged(captured(git, listing)) : null;
133
- const planned = name === 'mv' ? (captured(git, [...globals, 'mv', '--dry-run', ...args.slice(index + 1)]) ?? '') : '';
127
+ const copy = [...globals, '-C', worktree];
128
+ const before = name === 'mv' ? merged(git, copy, common) : undefined;
134
129
  const outcome = await delegated(git, args);
135
- const moves = before !== null && outcome.status === 0 ? moved(planned, before, staged(captured(git, listing))) : [];
130
+ const moves = before !== undefined && outcome.status === 0 ? moved(git, copy, before) : [];
136
131
  await reported(bridge, { common, worktree, moves });
137
132
  return outcome;
138
133
  }
package/dist/git.js CHANGED
@@ -2,16 +2,16 @@ import { spawn } from 'node:child_process';
2
2
  import { isUtf8 } from 'node:buffer';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { join } from 'node:path';
5
- import { withoutProxy } from './clis.js';
6
5
  import { workspaceRoot } from './home.js';
6
+ import { childEnvironment } from './relay.js';
7
7
  export function localCopies() {
8
8
  return join(workspaceRoot(), 'local-copies');
9
9
  }
10
10
  export const HOUSE_REF = 'refs/house/received';
11
- const COMMITTER = 'House Kit <house-kit@localhost>';
11
+ const COMMITTER = 'Kit <house-kit@localhost>';
12
12
  export function run(cwd, args, input, env = {}) {
13
13
  return new Promise((resolve, reject) => {
14
- const child = spawn('git', args, { cwd, env: { ...withoutProxy(), ...env } });
14
+ const child = spawn('git', args, { cwd, env: { ...childEnvironment(), ...env } });
15
15
  const stdout = [];
16
16
  let stderr = '';
17
17
  child.stdout.on('data', (chunk) => stdout.push(chunk));
@@ -55,11 +55,50 @@ async function blob(repository, object) {
55
55
  export async function blobText(repository, object) {
56
56
  return (await blob(repository, object)).toString('utf8');
57
57
  }
58
- export async function isText(repository, object, maxBytes) {
58
+ export async function blobSizes(repository, objects) {
59
+ if (objects.length === 0)
60
+ return new Map();
61
+ const listed = await git(repository, ['cat-file', '--batch-check=%(objectname) %(objectsize)'], `${[...new Set(objects)].join('\n')}\n`);
62
+ return new Map(listed
63
+ .split('\n')
64
+ .filter((line) => line !== '')
65
+ .map((line) => {
66
+ const [object, size] = line.split(' ');
67
+ return [object, Number(size)];
68
+ }));
69
+ }
70
+ export async function isText(repository, object, size, maxBytes) {
71
+ if (size > maxBytes)
72
+ return false;
59
73
  const bytes = await blob(repository, object);
60
- return bytes.length <= maxBytes && isUtf8(bytes) && !bytes.includes(0);
74
+ return isUtf8(bytes) && !bytes.includes(0);
75
+ }
76
+ export async function* blobBytes(repository, object) {
77
+ const child = spawn('git', ['cat-file', 'blob', object], { cwd: repository, env: childEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] });
78
+ let stderr = '';
79
+ child.stderr.on('data', (chunk) => {
80
+ stderr += chunk.toString('utf8');
81
+ });
82
+ const closed = new Promise((resolve, reject) => {
83
+ child.on('error', reject);
84
+ child.on('close', resolve);
85
+ });
86
+ try {
87
+ yield* child.stdout;
88
+ }
89
+ finally {
90
+ if (child.exitCode === null)
91
+ child.kill();
92
+ }
93
+ if ((await closed) !== 0)
94
+ throw new Error(`git cat-file failed: ${stderr.trim()}`);
95
+ }
96
+ export async function storedFile(repository, file) {
97
+ return (await git(repository, ['hash-object', '-w', '--no-filters', '--', file])).trim();
61
98
  }
62
99
  export function blobId(content) {
100
+ if (typeof content !== 'string')
101
+ return content.blob;
63
102
  const bytes = Buffer.from(content, 'utf8');
64
103
  return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
65
104
  }
@@ -70,18 +109,54 @@ function data(text) {
70
109
  const bytes = Buffer.from(text, 'utf8');
71
110
  return [Buffer.from(`data ${bytes.length}\n`), bytes, Buffer.from('\n')];
72
111
  }
73
- export async function importCommits(repository, commits) {
74
- const stream = [];
112
+ function written(stream, bytes) {
113
+ return new Promise((resolve, reject) => {
114
+ stream.write(bytes, (error) => (error ? reject(error) : resolve()));
115
+ });
116
+ }
117
+ async function imported(stream, commits) {
118
+ await written(stream, Buffer.from('feature done\n'));
75
119
  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));
120
+ await written(stream, Buffer.concat([
121
+ Buffer.from(`commit ${HOUSE_REF}\nmark :${index + 1}\ncommitter ${COMMITTER} ${Math.floor(Date.now() / 1000)} +0000\n`),
122
+ ...data(commit.message),
123
+ ...(commit.from === null ? [] : [Buffer.from(`from ${commit.from}\n`)]),
124
+ ...(commit.merge === undefined ? [] : [Buffer.from(`merge ${commit.merge}\n`)]),
125
+ ...(commit.replaces === true ? [Buffer.from('deleteall\n')] : []),
126
+ ]));
127
+ for await (const [path, content] of commit.files) {
128
+ await written(stream, content === null
129
+ ? Buffer.from(`D ${quoted(path)}\n`)
130
+ : typeof content === 'string'
131
+ ? Buffer.concat([Buffer.from(`M 100644 inline ${quoted(path)}\n`), ...data(content)])
132
+ : Buffer.from(`M 100644 ${content.blob} ${quoted(path)}\n`));
82
133
  }
83
- stream.push(Buffer.from('\n'));
134
+ await written(stream, Buffer.from('\n'));
135
+ }
136
+ await written(stream, Buffer.from('done\n'));
137
+ }
138
+ export async function importCommits(repository, commits) {
139
+ const child = spawn('git', ['fast-import', '--quiet', '--force'], { cwd: repository, env: childEnvironment() });
140
+ let stderr = '';
141
+ child.stdout.resume();
142
+ child.stderr.on('data', (chunk) => {
143
+ stderr += chunk.toString('utf8');
144
+ });
145
+ child.stdin.on('error', () => undefined);
146
+ const closed = new Promise((resolve, reject) => {
147
+ child.on('error', reject);
148
+ child.on('close', resolve);
149
+ });
150
+ try {
151
+ await imported(child.stdin, commits);
152
+ child.stdin.end();
153
+ }
154
+ catch (error) {
155
+ child.stdin.destroy();
156
+ await closed;
157
+ throw error.code === 'EPIPE' ? new Error(`git fast-import failed: ${stderr.trim()}`) : error;
84
158
  }
85
- await git(repository, ['fast-import', '--quiet', '--force'], Buffer.concat(stream));
159
+ if ((await closed) !== 0)
160
+ throw new Error(`git fast-import failed: ${stderr.trim()}`);
86
161
  return revision(repository, HOUSE_REF);
87
162
  }
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
+ }