@anhlp/alp-daemon 0.0.1-beta.4 → 0.0.1-beta.6

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 (82) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +26 -1
  2. package/dist/alpd.js +10768 -2592
  3. package/dist/attachments.d.ts +25 -49
  4. package/dist/attachments.js +45 -8
  5. package/dist/build-manifest.json +14 -1
  6. package/dist/conversation.js +18 -2
  7. package/dist/disk.d.ts +67 -0
  8. package/dist/disk.js +152 -0
  9. package/dist/files.d.ts +141 -2
  10. package/dist/files.js +377 -68
  11. package/dist/git.d.ts +8 -2
  12. package/dist/git.js +111 -12
  13. package/dist/index.d.ts +1 -0
  14. package/dist/index.js +3 -0
  15. package/dist/main.js +57 -12
  16. package/dist/native-terminal.d.ts +45 -0
  17. package/dist/native-terminal.js +198 -0
  18. package/dist/operations.d.ts +12 -2
  19. package/dist/operations.js +22 -11
  20. package/dist/registry.js +1 -1
  21. package/dist/scheduler.js +8 -2
  22. package/dist/schedules.d.ts +2 -1
  23. package/dist/schedules.js +6 -4
  24. package/dist/server.d.ts +4 -2
  25. package/dist/server.js +171 -43
  26. package/dist/store.d.ts +3 -1
  27. package/dist/store.js +4 -3
  28. package/dist/terminal-native/README.md +201 -0
  29. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  30. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  31. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  32. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  33. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  34. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  35. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  36. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  37. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  38. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  39. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  40. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  41. package/dist/terminal-native/terminal-owner.c +389 -0
  42. package/dist/terminal-screen.d.ts +24 -0
  43. package/dist/terminal-screen.js +99 -0
  44. package/dist/terminals.d.ts +43 -7
  45. package/dist/terminals.js +222 -139
  46. package/dist/windows-terminal.d.ts +29 -0
  47. package/dist/windows-terminal.js +122 -0
  48. package/dist/worktrees.d.ts +25 -1
  49. package/dist/worktrees.js +74 -2
  50. package/native/README.md +201 -0
  51. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  52. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  53. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  54. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  55. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  56. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  57. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  58. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  59. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  60. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  61. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  62. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  63. package/native/terminal-owner.c +389 -0
  64. package/package.json +11 -7
  65. package/src/attachments.ts +46 -8
  66. package/src/conversation.ts +22 -2
  67. package/src/disk.ts +175 -0
  68. package/src/files.ts +505 -80
  69. package/src/git.ts +113 -18
  70. package/src/index.ts +1 -0
  71. package/src/main.ts +53 -13
  72. package/src/native-terminal.ts +122 -0
  73. package/src/operations.ts +28 -12
  74. package/src/registry.ts +1 -1
  75. package/src/scheduler.ts +13 -3
  76. package/src/schedules.ts +5 -2
  77. package/src/server.ts +164 -36
  78. package/src/store.ts +2 -1
  79. package/src/terminal-screen.ts +74 -0
  80. package/src/terminals.ts +205 -155
  81. package/src/windows-terminal.ts +123 -0
  82. package/src/worktrees.ts +97 -2
package/src/operations.ts CHANGED
@@ -2,11 +2,11 @@ import { createHash, createHmac, randomBytes } from 'node:crypto';
2
2
  import { lstat, stat } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { CAPABILITY, ERROR, RPC_ERROR } from '@anhlp/alp-protocol';
5
- import { closeTask, createTask, epicReport, loadTasks, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
5
+ import { closeTask, createTask, epicReport, loadTasks, rejectGate, reopenTask, resolveGate } from '@anhlp/alp-core/tasks';
6
6
  import { taskRows } from '@anhlp/alp-core/task-rows';
7
7
  import { deleteEntry, duplicateEntry, getEntry, listEntries, renameEntry, saveEntry, setGivenSkills } from '@anhlp/alp-core/library-edit';
8
8
  import { listTeams } from '@anhlp/alp-core/teams';
9
- import { MODELS } from '@anhlp/alp-core/models';
9
+ import { catalogEntries } from '@anhlp/alp-runtime/index';
10
10
  import { listProviders } from '@anhlp/alp-core/providers';
11
11
  import { languageSetting, setLanguage, LANGUAGE_CHARS } from '@anhlp/alp-core/user-settings';
12
12
  import { syncProjectSettings } from '@anhlp/alp-core/init';
@@ -27,9 +27,13 @@ export type OperationsOptions = {
27
27
  templates?: Record<string, string>;
28
28
  /** Project roots the daemon knows from its session records, for a team save's sync. */
29
29
  knownProjects?: () => Iterable<string>;
30
+ /** A gate changed through task.gate.resolve: the runtime syncs the project's gate cards and mail. */
31
+ onGateChange?: (projectRoot: string) => Promise<void> | void;
30
32
  };
31
33
 
32
- type Handler = (params: any) => Promise<unknown>;
34
+ /** `caller.agent`: the connection said in daemon.hello that an ALP agent started it (t-ca1f). */
35
+ export type Caller = { agent?: boolean };
36
+ type Handler = (params: any, caller?: Caller) => Promise<unknown>;
33
37
 
34
38
  /** How long task.create remembers a requestId (§10): within one alpd process only. */
35
39
  const REQUEST_TTL_MS = 10 * 60 * 1000;
@@ -47,7 +51,7 @@ const SECRET_MAPS: Record<string, string[][]> = {
47
51
  const failure = (code: number, reason: string, message: string, extra: object = {}) => new RpcError(code, message, { reason, ...extra });
48
52
 
49
53
  /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
50
- function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
54
+ export function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
51
55
  if (error instanceof RpcError || typeof error?.code !== 'string' || error?.name !== 'AlpError') return error;
52
56
  const message = error.message as string;
53
57
  switch (error.code) {
@@ -56,6 +60,7 @@ function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry
56
60
  case 'TASK_NOT_FOUND': return failure(ERROR.notFound, 'unknown_task', message);
57
61
  case 'TASK_CHANGED': case 'REVISION_CONFLICT': return failure(ERROR.conflict, 'revision_conflict', message);
58
62
  case 'INVALID_TASK': case 'TASK_CYCLE': case 'TASK_TAKEN': case 'TASK_UNVERIFIED': return failure(ERROR.conflict, 'task_state', message);
63
+ case 'GATE_USER_ONLY': return failure(ERROR.forbidden, 'user_only', message);
59
64
  case 'TASKS_LOCKED': return failure(ERROR.unavailable, 'busy', message);
60
65
  case 'IN_USE': return failure(ERROR.conflict, 'in_use', message);
61
66
  case 'INVALID_SCOPE': return failure(RPC_ERROR.invalidParams, 'invalid_scope', message);
@@ -119,7 +124,7 @@ function unredact(kind: string, content: Record<string, unknown>, previous: Reco
119
124
  return next;
120
125
  }
121
126
 
122
- export function createOperations({ home, templates, knownProjects = () => [] }: OperationsOptions = {}) {
127
+ export function createOperations({ home, templates, knownProjects = () => [], onGateChange }: OperationsOptions = {}) {
123
128
  /** Revisions on the wire are keyed per alpd process, so they never carry a hash of secret content. */
124
129
  const revisionKey = randomBytes(32);
125
130
  const toWire = (revision: string | null | undefined) => revision == null ? null : `r${createHmac('sha256', revisionKey).update(revision).digest('base64url').slice(0, 22)}`;
@@ -156,8 +161,8 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
156
161
  catch (error: any) { if (error?.code === 'NOT_FOUND') return undefined; throw error; }
157
162
  }
158
163
 
159
- const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async params => {
160
- try { return await handler(params); }
164
+ const guard = (handler: Handler, context?: Parameters<typeof fromCore>[1]): Handler => async (params, caller) => {
165
+ try { return await handler(params, caller); }
161
166
  catch (error) { throw fromCore(error, context); }
162
167
  };
163
168
 
@@ -189,22 +194,33 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
189
194
  return result;
190
195
  }),
191
196
 
192
- 'task.update': guard(async ({ projectRoot, id, action, note, ifRev }) => {
197
+ 'task.update': guard(async ({ projectRoot, id, action, note, ifRev }, caller) => {
193
198
  const root = await project(projectRoot);
194
199
  const options = ifRev !== undefined ? { ifRev } : undefined;
195
200
  if (action === 'reopen') {
196
201
  const task = await reopenTask(root, id, { ...(note ? { note } : {}) }, 'user', options);
197
202
  return { id: task.id, status: task.status, rev: task.rev };
198
203
  }
199
- const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}) }, 'user', options);
204
+ const task = await closeTask(root, id, { reason: 'done', ...(note ? { summary: note } : {}), agent: caller?.agent === true, channel: 'web' }, 'user', options);
200
205
  const { tasks } = await loadTasks(root);
201
206
  const landed = tasks.some(entry => entry.parent === task.id) ? epicReport(task.id, tasks).text.split('\n')[0] : undefined;
202
207
  return { id: task.id, status: task.status, rev: task.rev, ...(landed ? { landed } : {}) };
203
208
  }),
204
209
 
205
- 'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev }) => {
210
+ // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
211
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
212
+ 'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = 'web' }, caller) => {
206
213
  const root = await project(projectRoot);
207
- const task = await resolveGate(root, id, gate, { by: 'user', ...(note ? { note } : {}), ...(ifRev !== undefined ? { ifRev } : {}) });
214
+ // Only the user decides a human gate: never a connection an ALP agent opened (t-ca1f).
215
+ if (caller?.agent) {
216
+ const { tasks } = await loadTasks(root);
217
+ if (tasks.find(task => task.id === id)?.gates.find(entry => entry.id === gate)?.kind === 'human') throw failure(ERROR.forbidden, 'user_only', 'Only the user decides a human gate; this connection was opened by an ALP agent');
218
+ }
219
+ const guarded = ifRev !== undefined ? { ifRev } : {};
220
+ const task = reject === true
221
+ ? await rejectGate(root, id, gate, { by: 'user', channel, ...(note ? { reason: note } : {}), ...guarded })
222
+ : await resolveGate(root, id, gate, { by: 'user', channel, ...(note ? { note } : {}), ...(choice !== undefined ? { choice } : {}), ...guarded });
223
+ await onGateChange?.(root);
208
224
  return { id: task.id, status: task.status, rev: task.rev };
209
225
  }),
210
226
  };
@@ -275,7 +291,7 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
275
291
  'library.skills.set': guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: 'invalid_entry' }),
276
292
 
277
293
  'library.models': guard(async () => {
278
- const models: Array<{ id: string; label: string; efforts: string[]; effort?: string }> = MODELS.map(model => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} · ${model.label}`, efforts: model.efforts, ...(model.effort ? { effort: model.effort } : {}) }));
294
+ const models: Array<{ id: string; label: string; efforts: string[]; effort?: string }> = catalogEntries.map(model => ({ id: `${model.runtime}:${model.id}`, label: `${model.runtime} · ${model.label}`, efforts: model.efforts, ...(model.effort ? { effort: model.effort } : {}) }));
279
295
  for (const provider of await listProviders(home)) {
280
296
  if (provider.enabled === false || provider.kind === 'antigravity') continue;
281
297
  models.push({ id: `acp:${provider.id}`, label: `${provider.label} · Provider default`, efforts: [] });
package/src/registry.ts CHANGED
@@ -229,7 +229,7 @@ export function createRegistry(home: string, options: { write?: typeof writeFile
229
229
  if (!includeArchived && !live(r, w)) fail('not_found', 'Workspace is archived', 1001);
230
230
  if (Object.values(r.worktreeJournal ?? {}).some(j => j.intent.id === workspaceId)) fail('reconciliation_required', 'Workspace mutation requires reconciliation');
231
231
  const canonical = await identity(w.directory);
232
- if (w.canonical && canonical !== w.canonical) fail('identity_changed', 'Workspace directory identity changed', 1003);
232
+ if (canonical !== (w.canonical ?? w.directory)) fail('identity_changed', 'Workspace directory identity changed', 1003);
233
233
  if (cwd !== undefined && await identity(cwd) !== canonical) fail('cwd_mismatch', 'cwd and workspaceId must agree', -32602);
234
234
  return canonical;
235
235
  },
package/src/scheduler.ts CHANGED
@@ -100,6 +100,8 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
100
100
  const held = new Map<string, { sessionId: string; at: number }>();
101
101
  /** The jobs that wait for a session to be opened again, with the moment the wait began. */
102
102
  const opening = new Map<string, number>();
103
+ /** The jobs that wait for a busy turn to end, with the moment the wait began. */
104
+ const busy = new Map<string, number>();
103
105
  /** The sessions a job is being created for: they are held before the job is written. */
104
106
  const heldSessions = new Map<string, number>();
105
107
  /** The jobs being delivered right now; a cancel that arrives is refused. */
@@ -114,6 +116,8 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
114
116
 
115
117
  const hold = (job: ScheduleJob) => {
116
118
  if (!held.has(job.id)) held.set(job.id, { sessionId: job.sessionId, at: ++sequence });
119
+ // A job that does not keep its session open is tracked, but no session waits for it.
120
+ if (job.keepsSession === false) return;
117
121
  const ids = waiting.get(job.sessionId) ?? new Set<string>();
118
122
  ids.add(job.id);
119
123
  waiting.set(job.sessionId, ids);
@@ -121,6 +125,7 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
121
125
  const releaseId = (id: string) => {
122
126
  const entry = held.get(id);
123
127
  opening.delete(id);
128
+ busy.delete(id);
124
129
  if (!entry) return;
125
130
  held.delete(id);
126
131
  const ids = waiting.get(entry.sessionId);
@@ -247,9 +252,12 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
247
252
  if (snapshot.parentId) return fail(current, 'The session this job continues is not a root session', 'not_a_root');
248
253
  if (projectKey(snapshot.projectRoot) !== projectKey(current.projectRoot)) return fail(current, 'The session this job continues belongs to another project', 'other_project');
249
254
  const waitBusy = async (): Promise<'waiting' | 'failed'> => {
250
- // The session is working. The job waits for the turn to end; it never steers it.
251
- const overdue = now() - Date.parse(current.dueAt);
252
- if (overdue > graceMs) return fail(current, `The session was still busy ${duration(overdue)} after the job was due`, 'session_busy');
255
+ // The session is working. The wait is bounded from the moment it began: how
256
+ // late the job is says nothing about how long a running turn takes to end.
257
+ const since = busy.get(current.id) ?? now();
258
+ busy.set(current.id, since);
259
+ const waited = now() - since;
260
+ if (waited > graceMs) return fail(current, `The session was still busy after waiting ${duration(waited)}`, 'session_busy');
253
261
  // Only the note is written, and only when it says something new: a cancel that
254
262
  // happened meanwhile is not overwritten, and the file is not rewritten every tick.
255
263
  const note = { message: 'The session is busy; the job waits for its turn to end', code: 'session_busy' };
@@ -258,6 +266,8 @@ export function createScheduler({ store, runtime, deliver, ready, session, settl
258
266
  return 'waiting';
259
267
  };
260
268
  if (snapshot.activeTurnId || runtime.starting?.(current.sessionId)) return waitBusy();
269
+ // The session is idle: the wait for a busy turn is over.
270
+ busy.delete(current.id);
261
271
  const dispatch = async (send?: AlpRuntime['prompt']): Promise<'delivered' | 'failed' | 'waiting' | 'skipped'> => {
262
272
  // From here the job is being delivered: a cancel that arrives now is refused, so
263
273
  // the job and the record cannot disagree about what happened.
package/src/schedules.ts CHANGED
@@ -96,7 +96,8 @@ function readJob(text: string, name: string): ScheduleRecord | undefined {
96
96
  && (record.cancelledAt === undefined || isTime(record.cancelledAt))
97
97
  && (record.lateByMs === undefined || (Number.isSafeInteger(record.lateByMs) && record.lateByMs >= 0))
98
98
  && (record.attempts === undefined || (Number.isSafeInteger(record.attempts) && record.attempts >= 0))
99
- && (record.lastError === undefined || isError(record.lastError));
99
+ && (record.lastError === undefined || isError(record.lastError))
100
+ && (record.keepsSession === undefined || record.keepsSession === false);
100
101
  if (!sound) {
101
102
  log.warn(`skipped invalid job ${name}`, { code: 'ALP_SCHEDULE_UNREADABLE', file: name });
102
103
  return undefined;
@@ -118,6 +119,7 @@ function readJob(text: string, name: string): ScheduleRecord | undefined {
118
119
  ...(record.cancelledAt === undefined ? {} : { cancelledAt: record.cancelledAt }),
119
120
  ...(record.lateByMs === undefined ? {} : { lateByMs: record.lateByMs }),
120
121
  ...(record.lastError === undefined ? {} : { lastError: { message: record.lastError.message, ...(record.lastError.code === undefined ? {} : { code: record.lastError.code }) } }),
122
+ ...(record.keepsSession === false ? { keepsSession: false as const } : {}),
121
123
  };
122
124
  }
123
125
 
@@ -162,7 +164,7 @@ export function createScheduleStore(root: string, { now = () => Date.now() } = {
162
164
  * A new job waiting for its time. The id is drawn here, so two jobs never
163
165
  * share one and a job's own id names its delivery.
164
166
  */
165
- async create({ projectRoot, sessionId, prompt, dueAt }: { projectRoot: string; sessionId: string; prompt: string; dueAt: string }): Promise<ScheduleRecord> {
167
+ async create({ projectRoot, sessionId, prompt, dueAt, keepsSession }: { projectRoot: string; sessionId: string; prompt: string; dueAt: string; keepsSession?: boolean }): Promise<ScheduleRecord> {
166
168
  if (typeof projectRoot !== 'string' || !projectRoot) throw new ScheduleStoreError('INVALID_SCHEDULE', 'A job needs the project it continues');
167
169
  // A project is named by its absolute path: a relative one would be read against
168
170
  // the daemon's own directory, which is another project.
@@ -185,6 +187,7 @@ export function createScheduleStore(root: string, { now = () => Date.now() } = {
185
187
  attempts: 0,
186
188
  createdAt: at,
187
189
  updatedAt: at,
190
+ ...(keepsSession === false ? { keepsSession: false as const } : {}),
188
191
  });
189
192
  },
190
193