@anhlp/alp-runtime 0.0.0-beta.2 → 0.0.1-beta.10

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 (97) hide show
  1. package/dist/acp-transport.js +7 -36
  2. package/dist/antigravity-transport.d.ts +27 -2
  3. package/dist/antigravity-transport.js +104 -58
  4. package/dist/assignment-results.d.ts +55 -0
  5. package/dist/assignment-results.js +181 -0
  6. package/dist/attachments.d.ts +84 -0
  7. package/dist/attachments.js +213 -0
  8. package/dist/board-domain.js +2 -2
  9. package/dist/board.d.ts +6 -0
  10. package/dist/board.js +7 -0
  11. package/dist/catalog.d.ts +13 -0
  12. package/dist/catalog.js +11 -2
  13. package/dist/claude-transport.d.ts +80 -0
  14. package/dist/claude-transport.js +271 -23
  15. package/dist/compact.d.ts +29 -0
  16. package/dist/compact.js +49 -0
  17. package/dist/configure.d.ts +44 -0
  18. package/dist/configure.js +64 -0
  19. package/dist/contracts.d.ts +216 -7
  20. package/dist/contracts.js +11 -0
  21. package/dist/conversation.d.ts +45 -0
  22. package/dist/conversation.js +62 -0
  23. package/dist/index.d.ts +18 -5
  24. package/dist/index.js +48 -4
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +10 -0
  28. package/dist/language.js +26 -0
  29. package/dist/live.d.ts +2 -2
  30. package/dist/live.js +7 -2
  31. package/dist/mailbox.d.ts +2 -0
  32. package/dist/mailbox.js +3 -1
  33. package/dist/mcp-tools.d.ts +8 -0
  34. package/dist/mcp-tools.js +26 -0
  35. package/dist/model-catalog.d.ts +162 -0
  36. package/dist/model-catalog.js +338 -0
  37. package/dist/model-probes.d.ts +7 -0
  38. package/dist/model-probes.js +69 -0
  39. package/dist/providers.js +2 -0
  40. package/dist/recall.d.ts +2 -2
  41. package/dist/recall.js +4 -3
  42. package/dist/resolve.d.ts +2 -0
  43. package/dist/resolve.js +9 -5
  44. package/dist/runtime-context.d.ts +1 -1
  45. package/dist/runtime-context.js +1 -1
  46. package/dist/runtime.d.ts +9 -0
  47. package/dist/runtime.js +2078 -269
  48. package/dist/session-config.d.ts +378 -6
  49. package/dist/session-config.js +19 -15
  50. package/dist/session-state.d.ts +54 -7
  51. package/dist/skill-resources.d.ts +30 -0
  52. package/dist/skill-resources.js +55 -0
  53. package/dist/tool-detail.js +4 -1
  54. package/dist/tools.d.ts +154 -1
  55. package/dist/tools.js +99 -11
  56. package/dist/transport.js +3 -1
  57. package/dist/workspace.d.ts +31 -5
  58. package/dist/workspace.js +92 -11
  59. package/dist/worktree-domain.d.ts +2 -1
  60. package/dist/worktree-domain.js +4 -1
  61. package/dist/write-error.d.ts +2 -0
  62. package/dist/write-error.js +10 -0
  63. package/package.json +12 -4
  64. package/src/acp-transport.ts +10 -37
  65. package/src/antigravity-transport.ts +128 -55
  66. package/src/assignment-results.ts +154 -0
  67. package/src/attachments.ts +254 -0
  68. package/src/board-domain.ts +2 -2
  69. package/src/board.ts +7 -0
  70. package/src/catalog.ts +13 -2
  71. package/src/claude-transport.ts +333 -23
  72. package/src/compact.ts +62 -0
  73. package/src/configure.ts +93 -0
  74. package/src/contracts.ts +199 -8
  75. package/src/conversation.ts +81 -0
  76. package/src/index.ts +18 -5
  77. package/src/input-limits.ts +65 -0
  78. package/src/language.ts +28 -0
  79. package/src/live.ts +7 -3
  80. package/src/mailbox.ts +4 -1
  81. package/src/mcp-tools.ts +33 -0
  82. package/src/model-catalog.ts +316 -0
  83. package/src/model-probes.ts +58 -0
  84. package/src/providers.ts +3 -0
  85. package/src/recall.ts +4 -3
  86. package/src/resolve.ts +15 -7
  87. package/src/runtime-context.ts +2 -2
  88. package/src/runtime.ts +2253 -264
  89. package/src/session-config.ts +25 -14
  90. package/src/session-state.ts +39 -3
  91. package/src/skill-resources.ts +73 -0
  92. package/src/tool-detail.ts +4 -1
  93. package/src/tools.ts +97 -10
  94. package/src/transport.ts +3 -1
  95. package/src/workspace.ts +124 -18
  96. package/src/worktree-domain.ts +5 -1
  97. package/src/write-error.ts +4 -0
package/src/workspace.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';
3
+ import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
 
@@ -140,17 +140,40 @@ export async function createWorktree(workdir: string, root: string, id: string,
140
140
  return { checkout, path: target, workdir: path.join(target, relative), branch, base, ...(fingerprint ? { fingerprint } : {}) };
141
141
  }
142
142
 
143
+ /** Whether `directory` is the top level of a working git worktree. */
144
+ async function validWorktree(directory: string) {
145
+ const top = await git(directory, ['rev-parse', '--show-toplevel']).catch(() => undefined);
146
+ if (top?.code !== 0) return false;
147
+ const [a, b] = await Promise.all([realpath(top.stdout.trim()).catch(() => ''), realpath(directory).catch(() => directory)]);
148
+ return a === b && (await git(directory, ['status', '--porcelain'])).code === 0;
149
+ }
150
+
143
151
  /**
144
- * Checks out an assignment's existing branch again at its worktree's place, after
145
- * reclaimWorktrees committed and removed it, so the assignment continues there.
152
+ * Continues an assignment in its worktree after a restart. A worktree that is still valid
153
+ * is reused as is, whatever it holds. A directory left without valid git metadata (a crash
154
+ * mid-write) is never deleted: it moves aside to `preserved` and the branch is checked out
155
+ * again at its place.
146
156
  */
147
- export async function reattachWorktree(worktree: Worktree): Promise<Worktree> {
157
+ export async function reattachWorktree(worktree: Worktree): Promise<Worktree & { preserved?: string }> {
158
+ const exists = !!await stat(worktree.path).catch(() => undefined);
159
+ if (exists && await validWorktree(worktree.path)) {
160
+ // A crash mid `git add`/`commit` leaves the index, HEAD or the branch locked; nothing else
161
+ // writes this worktree while its assignment reopens, so the locks are stale and would block
162
+ // every later commit.
163
+ const dirs = await gitDirs(worktree.path);
164
+ if (dirs) await clearStaleLocks(dirs, worktree.branch);
165
+ return worktree;
166
+ }
148
167
  if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
149
- if (await stat(worktree.path).catch(() => undefined)) return worktree;
168
+ let preserved: string | undefined;
169
+ if (exists) {
170
+ preserved = `${worktree.path}.preserved-${new Date().toISOString().replace(/[:.]/g, '-')}`;
171
+ await rename(worktree.path, preserved);
172
+ }
150
173
  await mkdir(path.dirname(worktree.path), { recursive: true, mode: 0o700 });
151
174
  await git(worktree.checkout, ['worktree', 'prune']);
152
175
  await checked(worktree.checkout, ['worktree', 'add', '--quiet', worktree.path, worktree.branch]);
153
- return worktree;
176
+ return preserved ? { ...worktree, preserved } : worktree;
154
177
  }
155
178
 
156
179
  /** A digest of a checkout's state: HEAD, its uncommitted changes, and the names of untracked files. */
@@ -232,31 +255,114 @@ export async function removeWorktree(worktree: Worktree, { deleteBranch = false
232
255
  if (deleteBranch) await git(worktree.checkout, ['branch', '-D', worktree.branch]);
233
256
  }
234
257
 
258
+ /** A linked worktree's own git directory and the repository's common one, both absolute. */
259
+ type GitDirs = { own: string; common: string };
260
+
261
+ async function gitDirs(target: string): Promise<GitDirs | undefined> {
262
+ const result = await git(target, ['rev-parse', '--path-format=absolute', '--absolute-git-dir', '--git-common-dir']);
263
+ if (result.code !== 0) return undefined;
264
+ const [own, common] = result.stdout.trim().split('\n').map(line => path.resolve(line.trim()));
265
+ return own && common ? { own, common } : undefined;
266
+ }
267
+
268
+ /**
269
+ * How old the branch's lock in the shared repository must be before ALP treats it as left by
270
+ * a crash. The user's own git commands in their checkout lock that ref too (`git gc`, `git branch
271
+ * -D`), but only for the moment a ref update takes.
272
+ */
273
+ const SHARED_LOCK_STALE_MS = 10_000;
274
+
275
+ /**
276
+ * Removes the locks a git command killed mid-write left in a worktree, which would fail every
277
+ * later `git add` or `git commit` there: `index.lock`, `HEAD.lock` and any other lock directly in
278
+ * the worktree's own git directory, and every `*.lock` under its `refs/`. Callers run this only
279
+ * where no ALP git command can be at work in that worktree (alpd's start, once it has stopped what
280
+ * a crashed alpd left running, and an assignment reopening): only ALP works in its worktrees, so
281
+ * those locks are stale, as `index.lock` always was. In the repository the worktree shares with
282
+ * the user's checkout, only the lock of the worktree's own branch is touched, and only once it is
283
+ * older than SHARED_LOCK_STALE_MS; every other lock there is the user's business.
284
+ */
285
+ async function clearStaleLocks(dirs: GitDirs, branch: string) {
286
+ if (dirs.own === dirs.common) return;
287
+ const own = (await readdir(dirs.own).catch(() => [] as string[])).filter(name => name.endsWith('.lock'));
288
+ const refs = (await readdir(path.join(dirs.own, 'refs'), { recursive: true }).catch(() => [] as string[])).filter(name => name.endsWith('.lock')).map(name => path.join('refs', name));
289
+ for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {});
290
+ const shared = `${path.join(dirs.common, 'refs', 'heads', ...branch.split('/'))}.lock`;
291
+ const info = await lstat(shared).catch(() => undefined);
292
+ if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {});
293
+ }
294
+
295
+ /** Ignored files that may hold what exists nowhere else, such as credentials: `.env`, `.env.local`. */
296
+ const KEEP_IGNORED = /^\.env/;
297
+
298
+ /**
299
+ * The ignored entries of a worktree that removing it would lose for good. git lists them, and an
300
+ * ignored directory (node_modules, build output) is one entry it does not look into.
301
+ */
302
+ async function ignoredToKeep(target: string) {
303
+ const result = await git(target, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory']);
304
+ if (result.code !== 0) return undefined;
305
+ return result.stdout.split('\0').filter(Boolean).map(entry => entry.replace(/\/$/, '')).filter(entry => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
306
+ }
307
+
308
+ /**
309
+ * Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
310
+ * worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
311
+ * another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
312
+ * not be committed (`detail` says why); `uncommitted`, something was still not committed after
313
+ * that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
314
+ */
315
+ export type LeftWorktree = {
316
+ name: string;
317
+ path: string;
318
+ reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
319
+ branch?: string;
320
+ detail?: string;
321
+ files?: string[];
322
+ };
323
+
324
+ const firstLine = (result: GitResult) => (result.stderr || result.stdout).trim().split('\n')[0] ?? '';
325
+
235
326
  /**
236
327
  * After a crash: commits work left in worktrees under `root` to their branches and
237
- * removes the directories. Returns the branches that were kept.
328
+ * removes the directories. Returns the branches that were kept, and the directories left in
329
+ * place with the reason. A directory is removed only once everything in it is committed to
330
+ * its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
331
+ * stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
332
+ * killed git command left in such a worktree are removed first (clearStaleLocks).
238
333
  */
239
- export async function reclaimWorktrees(root: string) {
334
+ export async function reclaimWorktrees(root: string): Promise<{ kept: string[]; left: LeftWorktree[] }> {
240
335
  const kept: string[] = [];
336
+ const left: LeftWorktree[] = [];
241
337
  const entries = await readdir(root).catch(() => [] as string[]);
242
338
  for (const name of entries) {
243
339
  const target = path.join(root, name);
340
+ const leave = (reason: LeftWorktree['reason'], extra: Omit<LeftWorktree, 'name' | 'path' | 'reason'> = {}) => { left.push({ name, path: target, reason, ...extra }); };
244
341
  if (!(await stat(target).catch(() => undefined))?.isDirectory()) continue;
245
- const common = await git(target, ['rev-parse', '--path-format=absolute', '--git-common-dir']).catch(() => undefined);
246
- if (common?.code !== 0) {
247
- await rm(target, { recursive: true, force: true });
248
- continue;
249
- }
250
- const checkout = path.dirname(common.stdout.trim());
251
- const branch = (await git(target, ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim();
252
- await git(target, ['add', '-A']);
342
+ if (!await validWorktree(target)) { leave('invalid'); continue; }
343
+ const dirs = await gitDirs(target);
344
+ if (!dirs) { leave('invalid'); continue; }
345
+ if (dirs.own === dirs.common) { leave('not-linked'); continue; }
346
+ const checkout = path.dirname(dirs.common);
347
+ const ref = await git(target, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
348
+ const branch = ref.stdout.trim();
349
+ if (ref.code !== 0 || branch !== `alp/${name}`) { leave('other-branch', ref.code === 0 && branch ? { branch } : {}); continue; }
350
+ await clearStaleLocks(dirs, branch);
351
+ const added = await git(target, ['add', '-A']);
352
+ if (added.code !== 0) { leave('commit-failed', { branch, detail: firstLine(added) }); continue; }
253
353
  if ((await git(target, ['diff', '--cached', '--quiet'])).code === 1) {
254
- await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment']);
354
+ const committed = await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment']);
355
+ if (committed.code !== 0) { leave('commit-failed', { branch, detail: firstLine(committed) }); continue; }
255
356
  }
357
+ const status = await git(target, ['status', '--porcelain', '--ignored=no']);
358
+ if (status.code !== 0 || status.stdout.trim()) { leave('uncommitted', { branch }); continue; }
359
+ const ignored = await ignoredToKeep(target);
360
+ if (!ignored) { leave('ignored-files', { branch, detail: 'git could not list its ignored files' }); continue; }
361
+ if (ignored.length) { leave('ignored-files', { branch, files: ignored }); continue; }
256
362
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: '' });
257
363
  kept.push(branch);
258
364
  }
259
- return kept;
365
+ return { kept, left };
260
366
  }
261
367
 
262
368
  /**
@@ -12,6 +12,7 @@ import type { Session, Assignment } from './session-state.js';
12
12
 
13
13
  type WorktreeContext = {
14
14
  options: RuntimeOptions;
15
+ releaseResult(assignmentId: string): Promise<void>;
15
16
  leases: Map<string, { assignment: string; agent: string }>;
16
17
  rootOf(sessionId: string): string;
17
18
  lineage(sessionId: string): string[];
@@ -21,7 +22,7 @@ type WorktreeContext = {
21
22
  };
22
23
 
23
24
  /** Checkout mutation and verification retain one shared queue per checkout. */
24
- export function createWorktreeDomain({ options, leases, rootOf, lineage, runLog, runHooks, touchTask }: WorktreeContext) {
25
+ export function createWorktreeDomain({ options, leases, releaseResult, rootOf, lineage, runLog, runHooks, touchTask }: WorktreeContext) {
25
26
  const merging = new Map<string, Promise<unknown>>();
26
27
 
27
28
  /** Commits a finished isolated assignment's work and keeps it for the requester to merge. */
@@ -31,6 +32,7 @@ export function createWorktreeDomain({ options, leases, rootOf, lineage, runLog,
31
32
  const change = await commitWorktree(worktree, `alp: ${assignment.agent} assignment ${assignment.id}`);
32
33
  if (!change.files.length) {
33
34
  await removeWorktree(worktree, { deleteBranch: true });
35
+ await releaseResult(assignment.id);
34
36
  return { branch: worktree.branch, files: [], note: 'No changes; the worktree was removed' };
35
37
  }
36
38
  const described = { branch: worktree.branch, base: worktree.base, commit: change.commit, files: change.files, stat: change.stat };
@@ -60,6 +62,7 @@ export function createWorktreeDomain({ options, leases, rootOf, lineage, runLog,
60
62
  if (action === 'discard') {
61
63
  session.worktrees.delete(args.assignmentId);
62
64
  await removeWorktree(worktree, { deleteBranch: true });
65
+ await releaseResult(args.assignmentId);
63
66
  runLog(rootOf(sessionId), { event: 'worktree.discarded', assignmentId: args.assignmentId, branch: worktree.branch });
64
67
  return toolResult(true, { discarded: args.assignmentId, branch: worktree.branch });
65
68
  }
@@ -122,6 +125,7 @@ export function createWorktreeDomain({ options, leases, rootOf, lineage, runLog,
122
125
  }
123
126
  // A conflicted change keeps its branch for reference.
124
127
  await removeWorktree(worktree, { deleteBranch: merged.status !== 'conflicts' });
128
+ if (merged.status !== 'conflicts') await releaseResult(args.assignmentId);
125
129
  runLog(rootId, { event: 'worktree.merged', assignmentId: args.assignmentId, branch: worktree.branch, ...merged });
126
130
  // The checkout changed since the assignment started, so the worktree's check says little about the result: check the checkout too.
127
131
  let checked: Verification | undefined;
@@ -0,0 +1,4 @@
1
+ /** Tells `onError` of a failed write (t-e80a); what it throws must not change how the write failed. */
2
+ export function tell(onError: (error: unknown) => void, error: unknown) {
3
+ try { onError(error); } catch {}
4
+ }