@anhlp/alp-runtime 0.0.0-stage → 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 (127) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +6 -2
  4. package/dist/acp-transport.d.ts +130 -0
  5. package/dist/acp-transport.js +482 -0
  6. package/dist/antigravity-transport.d.ts +107 -0
  7. package/dist/antigravity-transport.js +665 -0
  8. package/dist/assignment-results.d.ts +55 -0
  9. package/dist/assignment-results.js +181 -0
  10. package/dist/attachments.d.ts +84 -0
  11. package/dist/attachments.js +213 -0
  12. package/dist/board-domain.d.ts +56 -0
  13. package/dist/board-domain.js +157 -0
  14. package/dist/board.d.ts +27 -0
  15. package/dist/board.js +76 -0
  16. package/dist/catalog.d.ts +44 -0
  17. package/dist/catalog.js +47 -0
  18. package/dist/claude-transport.d.ts +251 -0
  19. package/dist/claude-transport.js +931 -0
  20. package/dist/compact.d.ts +29 -0
  21. package/dist/compact.js +49 -0
  22. package/dist/configure.d.ts +44 -0
  23. package/dist/configure.js +64 -0
  24. package/dist/contracts.d.ts +378 -0
  25. package/dist/contracts.js +16 -0
  26. package/dist/conversation.d.ts +45 -0
  27. package/dist/conversation.js +62 -0
  28. package/dist/events.d.ts +1 -0
  29. package/dist/events.js +0 -0
  30. package/dist/github.d.ts +10 -0
  31. package/dist/github.js +39 -0
  32. package/dist/handoff.d.ts +36 -0
  33. package/dist/handoff.js +73 -0
  34. package/dist/index.d.ts +39 -0
  35. package/dist/index.js +122 -0
  36. package/dist/input-limits.d.ts +25 -0
  37. package/dist/input-limits.js +48 -0
  38. package/dist/language.d.ts +51 -0
  39. package/dist/language.js +94 -0
  40. package/dist/live.d.ts +48 -0
  41. package/dist/live.js +50 -0
  42. package/dist/mailbox.d.ts +26 -0
  43. package/dist/mailbox.js +38 -0
  44. package/dist/mcp-tools.d.ts +123 -0
  45. package/dist/mcp-tools.js +97 -0
  46. package/dist/model-catalog.d.ts +162 -0
  47. package/dist/model-catalog.js +338 -0
  48. package/dist/model-probes.d.ts +7 -0
  49. package/dist/model-probes.js +69 -0
  50. package/dist/permission-path.d.ts +2 -0
  51. package/dist/permission-path.js +44 -0
  52. package/dist/process-info.d.ts +14 -0
  53. package/dist/process-info.js +32 -0
  54. package/dist/providers.d.ts +28 -0
  55. package/dist/providers.js +73 -0
  56. package/dist/recall.d.ts +42 -0
  57. package/dist/recall.js +61 -0
  58. package/dist/resolve.d.ts +123 -0
  59. package/dist/resolve.js +242 -0
  60. package/dist/runtime-context.d.ts +43 -0
  61. package/dist/runtime-context.js +61 -0
  62. package/dist/runtime.d.ts +13 -0
  63. package/dist/runtime.js +4818 -0
  64. package/dist/session-config.d.ts +2345 -0
  65. package/dist/session-config.js +209 -0
  66. package/dist/session-state.d.ts +190 -0
  67. package/dist/session-state.js +0 -0
  68. package/dist/skill-resources.d.ts +30 -0
  69. package/dist/skill-resources.js +55 -0
  70. package/dist/tool-detail.d.ts +81 -0
  71. package/dist/tool-detail.js +332 -0
  72. package/dist/tool-results.d.ts +12 -0
  73. package/dist/tool-results.js +25 -0
  74. package/dist/tools.d.ts +827 -0
  75. package/dist/tools.js +463 -0
  76. package/dist/transport.d.ts +47 -0
  77. package/dist/transport.js +171 -0
  78. package/dist/usage.d.ts +25 -0
  79. package/dist/usage.js +60 -0
  80. package/dist/workspace.d.ts +127 -0
  81. package/dist/workspace.js +340 -0
  82. package/dist/worktree-domain.d.ts +89 -0
  83. package/dist/worktree-domain.js +199 -0
  84. package/dist/write-error.d.ts +2 -0
  85. package/dist/write-error.js +10 -0
  86. package/package.json +262 -4
  87. package/src/acp-transport.ts +481 -0
  88. package/src/antigravity-transport.ts +740 -0
  89. package/src/assignment-results.ts +154 -0
  90. package/src/attachments.ts +254 -0
  91. package/src/board-domain.ts +185 -0
  92. package/src/board.ts +87 -0
  93. package/src/catalog.ts +43 -0
  94. package/src/claude-transport.ts +1097 -0
  95. package/src/compact.ts +62 -0
  96. package/src/configure.ts +93 -0
  97. package/src/contracts.ts +363 -0
  98. package/src/conversation.ts +81 -0
  99. package/src/events.ts +1 -0
  100. package/src/github.ts +37 -0
  101. package/src/handoff.ts +86 -0
  102. package/src/index.ts +41 -0
  103. package/src/input-limits.ts +65 -0
  104. package/src/language.ts +130 -0
  105. package/src/live.ts +90 -0
  106. package/src/mailbox.ts +49 -0
  107. package/src/mcp-tools.ts +106 -0
  108. package/src/model-catalog.ts +316 -0
  109. package/src/model-probes.ts +58 -0
  110. package/src/permission-path.ts +37 -0
  111. package/src/process-info.ts +40 -0
  112. package/src/providers.ts +87 -0
  113. package/src/recall.ts +86 -0
  114. package/src/resolve.ts +238 -0
  115. package/src/runtime-context.ts +49 -0
  116. package/src/runtime.ts +5608 -0
  117. package/src/session-config.ts +312 -0
  118. package/src/session-state.ts +180 -0
  119. package/src/skill-resources.ts +73 -0
  120. package/src/tool-detail.ts +397 -0
  121. package/src/tool-results.ts +26 -0
  122. package/src/tools.ts +466 -0
  123. package/src/transport.ts +118 -0
  124. package/src/usage.ts +79 -0
  125. package/src/workspace.ts +424 -0
  126. package/src/worktree-domain.ts +220 -0
  127. package/src/write-error.ts +4 -0
@@ -0,0 +1,220 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { describeVerification, runVerify, verifyConfig, type Verification, type VerifyConfig } from '@anhlp/alp-core/verify';
4
+ import { recordVerification, loadTasks } from '@anhlp/alp-core/tasks';
5
+ import { checkoutFingerprint, checkoutKey, commitWorktree, linkModules, mergeWorktree, removeWorktree, type Worktree, type WorktreeChange } from './workspace.js';
6
+ import { writes } from './catalog.js';
7
+ import { nativeEnvironment } from './providers.js';
8
+ import { mainOf } from './tools.js';
9
+ import { errorData, plainObject, toolResult } from './tool-results.js';
10
+ import type { RuntimeOptions } from './contracts.js';
11
+ import type { Session, Assignment } from './session-state.js';
12
+
13
+ type WorktreeContext = {
14
+ options: RuntimeOptions;
15
+ releaseResult(assignmentId: string): Promise<void>;
16
+ leases: Map<string, { assignment: string; agent: string }>;
17
+ rootOf(sessionId: string): string;
18
+ lineage(sessionId: string): string[];
19
+ runLog(rootId: string, entry: Record<string, unknown>): void;
20
+ runHooks(sessionId: string, session: Session, event: string, details?: Record<string, unknown>, taskId?: string): Promise<string | undefined>;
21
+ touchTask(rootId: string, id: string): void;
22
+ };
23
+
24
+ /** Checkout mutation and verification retain one shared queue per checkout. */
25
+ export function createWorktreeDomain({ options, leases, releaseResult, rootOf, lineage, runLog, runHooks, touchTask }: WorktreeContext) {
26
+ const merging = new Map<string, Promise<unknown>>();
27
+
28
+ /** Commits a finished isolated assignment's work and keeps it for the requester to merge. */
29
+ async function settleWorktree(parentId: string, parent: Session, assignment: Assignment) {
30
+ const worktree = assignment.worktree!;
31
+ try {
32
+ const change = await commitWorktree(worktree, `alp: ${assignment.agent} assignment ${assignment.id}`);
33
+ if (!change.files.length) {
34
+ await removeWorktree(worktree, { deleteBranch: true });
35
+ await releaseResult(assignment.id);
36
+ return { branch: worktree.branch, files: [], note: 'No changes; the worktree was removed' };
37
+ }
38
+ const described = { branch: worktree.branch, base: worktree.base, commit: change.commit, files: change.files, stat: change.stat };
39
+ if (parent.closed) {
40
+ await removeWorktree(worktree);
41
+ runLog(rootOf(parentId), { event: 'worktree.kept', assignmentId: assignment.id, branch: worktree.branch });
42
+ return { ...described, note: 'The requester closed; the change stays on the branch' };
43
+ }
44
+ parent.worktrees.set(assignment.id, { agent: assignment.agent, worktree, change, ...(assignment.taskId ? { taskId: assignment.taskId } : {}) });
45
+ return { ...described, next: 'Apply it with alp_merge, or drop it with alp_discard' };
46
+ } catch (error) {
47
+ await removeWorktree(worktree).catch(() => {});
48
+ return { branch: worktree.branch, error: errorData(error).message };
49
+ }
50
+ }
51
+
52
+ async function worktreeTool(sessionId: string, session: Session, args: unknown, action: 'merge' | 'discard') {
53
+ if (!plainObject(args, ['assignmentId', 'skipVerify']) || typeof args.assignmentId !== 'string' ||
54
+ (args.skipVerify !== undefined && (action !== 'merge' || typeof args.skipVerify !== 'string' || !args.skipVerify.trim()))) {
55
+ return toolResult(false, { error: action === 'merge' ? 'assignmentId is required; skipVerify, when given, says why to merge without verification' : 'assignmentId is required' });
56
+ }
57
+ const pending = session.worktrees.get(args.assignmentId);
58
+ if (!pending) {
59
+ return toolResult(false, { error: session.assignments.has(args.assignmentId) ? 'The assignment is still running; wait for its result' : 'No unmerged worktree change with that assignment id' });
60
+ }
61
+ const { worktree, change } = pending;
62
+ if (action === 'discard') {
63
+ session.worktrees.delete(args.assignmentId);
64
+ await removeWorktree(worktree, { deleteBranch: true });
65
+ await releaseResult(args.assignmentId);
66
+ runLog(rootOf(sessionId), { event: 'worktree.discarded', assignmentId: args.assignmentId, branch: worktree.branch });
67
+ return toolResult(true, { discarded: args.assignmentId, branch: worktree.branch });
68
+ }
69
+ if (!writes(session.mapping.mode)) return toolResult(false, { error: 'Merging needs workspace-write or full-access' });
70
+ if ([...session.assignments.values()].some(assignment => assignment.mode !== 'read-only' && assignment.isolation === 'shared')) {
71
+ return toolResult(false, { error: 'A writer assignment is working in this checkout; merge after its result' });
72
+ }
73
+ // Claimed before any await, so a repeated call cannot merge it twice.
74
+ session.worktrees.delete(args.assignmentId);
75
+ const checkout = await checkoutKey(session.mapping.workdir);
76
+ const holder = leases.get(checkout);
77
+ if (holder && !lineage(sessionId).includes(holder.assignment)) {
78
+ session.worktrees.set(args.assignmentId, pending);
79
+ return toolResult(false, { error: `${holder.agent} in another session is writing this checkout; merge after it finishes` });
80
+ }
81
+ const project = session.mapping.agent.projectRoot;
82
+ const rootId = rootOf(sessionId);
83
+ let config: VerifyConfig | undefined;
84
+ try { config = await verifyConfig(project); }
85
+ catch (error) {
86
+ session.worktrees.set(args.assignmentId, pending);
87
+ return toolResult(false, { error: errorData(error).message });
88
+ }
89
+ let verified: Verification | undefined;
90
+ if (config && args.skipVerify === undefined) {
91
+ const verification = verified = await verifyIn(project, worktreeDirectory(worktree, project), config);
92
+ noteVerification(rootId, project, pending.taskId, args.assignmentId, 'worktree', verification);
93
+ if (!verification.passed) {
94
+ session.worktrees.set(args.assignmentId, { ...pending, verification });
95
+ return toolResult(false, {
96
+ assignmentId: args.assignmentId,
97
+ error: `${describeVerification(verification)} in the assignment's worktree; nothing was applied`,
98
+ verification: verificationResult(verification),
99
+ branch: worktree.branch,
100
+ next: verification.skipped
101
+ ? 'The check could not run, which says nothing about the change; call alp_merge again, or alp_merge it with skipVerify saying why'
102
+ : `Delegate again with continueFrom "${args.assignmentId}"${pending.taskId ? ` and taskId ${pending.taskId}` : ''} to fix it in a worktree that starts from this change; or alp_discard it; or alp_merge it with skipVerify saying why`,
103
+ });
104
+ }
105
+ } else if (config && pending.taskId) {
106
+ await recordVerification(project, pending.taskId, { passed: false, skipped: args.skipVerify }, session.mapping.agent.name).catch(() => {});
107
+ runLog(rootId, { event: 'verify', assignmentId: args.assignmentId, where: 'worktree', skipped: args.skipVerify });
108
+ }
109
+ // A blocking merge hook can refuse the change before anything is applied.
110
+ const refused = await runHooks(sessionId, session, 'merge', { assignment: args.assignmentId, branch: worktree.branch }, pending.taskId);
111
+ if (refused) {
112
+ session.worktrees.set(args.assignmentId, pending);
113
+ return toolResult(false, { assignmentId: args.assignmentId, error: `A merge hook refused it; nothing was applied:\n${refused}`, branch: worktree.branch, next: `Fix what it reports in a new assignment with continueFrom "${args.assignmentId}", or alp_discard it` });
114
+ }
115
+ let merged: Awaited<ReturnType<typeof mergeWorktree>>;
116
+ let moved = false;
117
+ try {
118
+ ({ merged, moved } = await inCheckout(checkout, async () => {
119
+ const before = await checkoutFingerprint(worktree.checkout).catch(() => undefined);
120
+ return { merged: await mergeWorktree(worktree, change), moved: !worktree.fingerprint || before !== worktree.fingerprint };
121
+ }));
122
+ } catch (error) {
123
+ session.worktrees.set(args.assignmentId, pending);
124
+ return toolResult(false, { error: errorData(error).message, branch: worktree.branch, next: 'Merge the branch yourself, or alp_discard it' });
125
+ }
126
+ // A conflicted change keeps its branch for reference.
127
+ await removeWorktree(worktree, { deleteBranch: merged.status !== 'conflicts' });
128
+ if (merged.status !== 'conflicts') await releaseResult(args.assignmentId);
129
+ runLog(rootId, { event: 'worktree.merged', assignmentId: args.assignmentId, branch: worktree.branch, ...merged });
130
+ // The checkout changed since the assignment started, so the worktree's check says little about the result: check the checkout too.
131
+ let checked: Verification | undefined;
132
+ if (config && args.skipVerify === undefined && merged.status === 'applied' && moved) {
133
+ checked = await inCheckout(checkout, () => verifyIn(project, session.mapping.workdir, config!));
134
+ noteVerification(rootId, project, pending.taskId, args.assignmentId, 'checkout', checked);
135
+ }
136
+ return toolResult(true, {
137
+ assignmentId: args.assignmentId,
138
+ ...merged,
139
+ ...(merged.status === 'conflicts' ? { branch: worktree.branch } : {}),
140
+ ...(verified ? { verification: verificationResult(checked ?? verified), ...(checked ? { verifiedIn: 'your checkout, which changed since the assignment started' } : {}) } : {}),
141
+ ...(args.skipVerify !== undefined && config ? { verification: { skipped: args.skipVerify } } : {}),
142
+ next: merged.status === 'conflicts' ? `Resolve the conflict markers in the listed files, then verify${config ? ' with alp_verify' : ''}`
143
+ : checked && !checked.passed ? `The change passed in its worktree but ${describeVerification(checked)} in your checkout, which changed meanwhile; fix it, then run alp_verify`
144
+ : 'Review the applied change; it is not committed',
145
+ });
146
+ }
147
+
148
+ /** Work on a checkout, one at a time: merges and the verify runs that check them. */
149
+ function inCheckout<T>(checkout: string, work: () => Promise<T>): Promise<T> {
150
+ const previous = merging.get(checkout) ?? Promise.resolve();
151
+ const attempt = previous.catch(() => {}).then(work);
152
+ merging.set(checkout, attempt);
153
+ void attempt.finally(() => { if (merging.get(checkout) === attempt) merging.delete(checkout); }).catch(() => {});
154
+ return attempt;
155
+ }
156
+
157
+ /** The directory in a worktree that corresponds to the project root. */
158
+ function worktreeDirectory(worktree: Worktree, project: string) {
159
+ let real = project;
160
+ try { real = realpathSync(project); } catch {}
161
+ return path.join(worktree.path, path.relative(worktree.checkout, real));
162
+ }
163
+
164
+ /** Runs the project's verify commands in `directory`; a worktree borrows the project's node_modules for the run. */
165
+ async function verifyIn(project: string, directory: string, config: VerifyConfig) {
166
+ const same = path.resolve(directory) === path.resolve(project);
167
+ const unlinkModules = same ? async () => {} : await linkModules(project, directory).catch(() => async () => {});
168
+ try {
169
+ return await runVerify(directory, config, { env: nativeEnvironment(options) });
170
+ } finally {
171
+ await unlinkModules();
172
+ }
173
+ }
174
+
175
+ /** What an agent sees of a verification: each step's exit code and time, and the end of a failed step's output. */
176
+ function verificationResult(verification: Verification | { passed: boolean; commands: Array<Record<string, any>>; cwd?: string; skipped?: string }) {
177
+ const failed = verification.commands.find(command => command.exitCode !== 0);
178
+ return {
179
+ passed: verification.passed,
180
+ ...(verification.skipped ? { skipped: verification.skipped } : {}),
181
+ steps: verification.commands.map(({ step, command, exitCode, ms, timedOut, idle }) => ({ step, command, exitCode, ms, ...(timedOut ? { timedOut } : {}), ...(idle ? { idle } : {}) })),
182
+ ...(failed?.output ? { output: failed.output } : {}),
183
+ };
184
+ }
185
+
186
+ /** Logs a verification, and records it on the task it counts for. */
187
+ function noteVerification(rootId: string, project: string, taskId: string | undefined, assignmentId: string | undefined, where: 'worktree' | 'checkout', verification: Verification) {
188
+ runLog(rootId, { event: 'verify', ...(assignmentId ? { assignmentId } : {}), ...(taskId ? { taskId } : {}), where, passed: verification.passed, detail: describeVerification(verification) });
189
+ if (taskId) void recordVerification(project, taskId, { ...verification, where }, 'alpd').then(() => touchTask(rootId, taskId), () => {});
190
+ }
191
+
192
+ /** The start of the brief of an assignment that continues an earlier worktree change. */
193
+ function continuedBrief(from: string, continued: { agent: string; change: WorktreeChange; verification?: Verification }) {
194
+ const failed = continued.verification?.commands.find(command => command.exitCode !== 0);
195
+ return `Your worktree starts from the change of ${continued.agent}'s assignment ${from}, committed on your branch (${continued.change.files.length} files: ${continued.change.files.slice(0, 20).join(', ')}). Build on it rather than starting over.` +
196
+ (continued.verification && !continued.verification.passed
197
+ ? ` The project's checks failed on it: ${describeVerification(continued.verification)}, running \`${failed?.command}\`. The end of its output:\n${failed?.output.slice(-1500) ?? ''}`
198
+ : '');
199
+ }
200
+
201
+ async function verifyTool(sessionId: string, session: Session, args: unknown) {
202
+ if (!plainObject(args, ['taskId']) || (args.taskId !== undefined && typeof args.taskId !== 'string')) return toolResult(false, { error: 'alp_verify takes only taskId' });
203
+ if (args.taskId !== undefined && (session.parent || session.mapping.agent.name !== mainOf(session.mapping))) return toolResult(false, { error: 'Only main records a verification on a task; call alp_verify without taskId' });
204
+ const project = session.mapping.agent.projectRoot;
205
+ let config: VerifyConfig | undefined;
206
+ try { config = await verifyConfig(project); } catch (error) { return toolResult(false, { error: errorData(error).message }); }
207
+ if (!config) return toolResult(false, { error: 'This project has no verify commands (verify in .alp/settings.json); run its checks yourself' });
208
+ if (args.taskId !== undefined) {
209
+ const task = (await loadTasks(project)).tasks.find(entry => entry.id === args.taskId);
210
+ if (!task) return toolResult(false, { error: `No task ${args.taskId}` });
211
+ if (task.status === 'closed') return toolResult(false, { error: `${args.taskId} is closed` });
212
+ }
213
+ const checkout = await checkoutKey(session.mapping.workdir);
214
+ const verification = await inCheckout(checkout, () => verifyIn(project, session.mapping.workdir, config!));
215
+ noteVerification(rootOf(sessionId), project, args.taskId, undefined, 'checkout', verification);
216
+ return toolResult(true, { ...verificationResult(verification), summary: describeVerification(verification), ...(args.taskId ? { recordedOn: args.taskId } : {}) });
217
+ }
218
+
219
+ return { settleWorktree, worktreeTool, inCheckout, verifyIn, verificationResult, noteVerification, continuedBrief, verifyTool };
220
+ }
@@ -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
+ }