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

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 +11047 -3021
  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 +37 -11
  16. package/dist/native-terminal.d.ts +45 -0
  17. package/dist/native-terminal.js +198 -0
  18. package/dist/operations.d.ts +8 -2
  19. package/dist/operations.js +20 -10
  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 +166 -42
  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 +30 -11
  72. package/src/native-terminal.ts +122 -0
  73. package/src/operations.ts +27 -11
  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 +157 -35
  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/git.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
3
- import { lstat, realpath } from 'node:fs/promises';
3
+ import { lstat, realpath, stat } from 'node:fs/promises';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { user_worktree } from '@anhlp/alp-core';
7
7
  import { ERROR, RPC_ERROR, WORKSPACE_GIT, blockedFilePath } from '@anhlp/alp-protocol';
8
- import type { GitChange, GitCompare, GitDiffFile, GitDiffHunk, GitDiffPage, GitStatus, GitStatusFile } from '@anhlp/alp-protocol';
8
+ import type { GitChange, GitCompare, GitDiffFile, GitDiffHunk, GitDiffPage, GitFacts, GitStatus, GitStatusFile } from '@anhlp/alp-protocol';
9
9
  import { FileAccessError, PRIVATE_KEY, likelyBinary, readConfinedFile, relativeSegments } from './files.js';
10
10
  import { IgnoreUnknown, resolveGit, searchPathOutside } from './gitignore.js';
11
11
  import { RegistryError } from './registry.js';
@@ -38,6 +38,10 @@ import { RpcError } from './rpc-error.js';
38
38
  * (files.ts PRIVATE_KEY), historical and deleted ones included; untracked files are read by alpd
39
39
  * itself, confined as workspace.files.read confines a read. Errors carry fixed messages; the
40
40
  * cause is logged, never answered.
41
+ *
42
+ * `workspace.git.facts` reads in the same box for an owner's host directory that need not be a
43
+ * registry workspace (a project-only, preflight or nested folder): its repository's root, branch,
44
+ * HEAD, origin and whether anything changed, never a file list or content.
41
45
  */
42
46
 
43
47
  export const GIT_READ = Object.freeze({
@@ -73,6 +77,10 @@ const FIXED = Object.freeze({
73
77
  stale: 'The checkout changed since the cursor was given; ask again without a cursor',
74
78
  invalidCursor: 'cursor is not one alpd gave for this workspace and comparison',
75
79
  notFound: 'No workspace with this workspaceId',
80
+ noRegistry: 'Registry needs ALP_HOME',
81
+ invalidDirectory: 'directory must be an absolute, normalised path with no . or .. segment',
82
+ noDirectory: 'No directory at this path',
83
+ notDirectory: 'The path is not a directory',
76
84
  });
77
85
 
78
86
  /** A Git read that failed: answered as `1000 git_failed` with a fixed message; `cause` is logged only. */
@@ -108,12 +116,14 @@ export const gitReadsRunning = () => running;
108
116
 
109
117
  type Box = { git: string; root: string; env: NodeJS.ProcessEnv; deadline: number; overrides: string[] };
110
118
 
119
+ const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
120
+
111
121
  /** Flags before every subcommand: nothing the repository names may run, nothing is paged or coloured. */
112
122
  const BOXED = [
113
123
  '--no-pager', '--literal-pathspecs',
114
- '-c', 'core.fsmonitor=false', '-c', `core.hooksPath=${os.devNull}`, '-c', 'core.pager=cat', '-c', 'core.untrackedCache=false',
124
+ '-c', 'core.fsmonitor=false', '-c', `core.hooksPath=${NULL_DEVICE}`, '-c', 'core.pager=cat', '-c', 'core.untrackedCache=false',
115
125
  '-c', 'core.quotePath=false', '-c', 'color.ui=never', '-c', 'diff.autoRefreshIndex=false', '-c', 'diff.noprefix=false',
116
- '-c', 'diff.mnemonicPrefix=false', '-c', 'diff.relative=false', '-c', 'diff.suppressBlankEmpty=false', '-c', `diff.orderFile=${os.devNull}`,
126
+ '-c', 'diff.mnemonicPrefix=false', '-c', 'diff.relative=false', '-c', 'diff.suppressBlankEmpty=false', '-c', `diff.orderFile=${NULL_DEVICE}`,
117
127
  '-c', 'log.showSignature=false', '-c', 'submodule.recurse=false', '-c', 'protocol.allow=never', '-c', 'maintenance.auto=false',
118
128
  '-c', 'gc.auto=0', '-c', 'status.showStash=false', '-c', 'status.renames=true', '-c', 'diff.renames=true',
119
129
  ];
@@ -207,7 +217,8 @@ function recentEnough(box: Box): Promise<boolean> {
207
217
 
208
218
  // ---- The workspace and its repository ----
209
219
 
210
- type Located = { kind: 'not_repository' } | { kind: 'unsupported' } | { kind: 'repository'; root: string; gitDir: string };
220
+ /** `top`, when unsupported: the nearest directory above the root that holds a `.git` entry. */
221
+ type Located = { kind: 'not_repository' } | { kind: 'unsupported'; top: string } | { kind: 'repository'; root: string; gitDir: string };
211
222
 
212
223
  const missing = (error: unknown) => ['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException)?.code ?? '');
213
224
 
@@ -217,7 +228,7 @@ async function locate(root: string): Promise<Located> {
217
228
  try { await lstat(path.join(root, '.git')); } catch (error) { if (!missing(error)) failed('cannot examine .git'); entry = false; }
218
229
  if (!entry) {
219
230
  for (let directory = path.dirname(root); ; directory = path.dirname(directory)) {
220
- try { await lstat(path.join(directory, '.git')); return { kind: 'unsupported' }; } catch (error) { if (!missing(error)) failed('cannot examine .git above the workspace'); }
231
+ try { await lstat(path.join(directory, '.git')); return { kind: 'unsupported', top: directory }; } catch (error) { if (!missing(error)) failed('cannot examine .git above the workspace'); }
221
232
  if (path.dirname(directory) === directory) return { kind: 'not_repository' };
222
233
  }
223
234
  }
@@ -239,7 +250,7 @@ function environment(root: string, gitDir: string): NodeJS.ProcessEnv {
239
250
  let searchPath: string;
240
251
  try { searchPath = searchPathOutside(root); } catch { failed('the workspace cannot be examined'); }
241
252
  return {
242
- ...env, PATH: searchPath!, GIT_DIR: gitDir, GIT_WORK_TREE: root, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: os.devNull, GIT_ATTR_NOSYSTEM: '1',
253
+ ...env, PATH: searchPath!, GIT_DIR: gitDir, GIT_WORK_TREE: root, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: NULL_DEVICE, GIT_ATTR_NOSYSTEM: '1',
243
254
  GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0', GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', GIT_PROTOCOL_FROM_USER: '0', LC_ALL: 'C', LANG: 'C',
244
255
  };
245
256
  }
@@ -248,12 +259,6 @@ const EMPTY_TREE = { sha1: '4b825dc642cb6eb9a060e54bf8d69288fbee4904', sha256: '
248
259
 
249
260
  type Repository = Box & { remoteUrl: string | null; emptyTree: string; gitDir: string; config: string };
250
261
 
251
- /**
252
- * The box for a located repository: the configuration overrides that neutralize every filter it
253
- * names, origin's URL, its object format. A filter name `-c` cannot carry, or a work tree
254
- * configured elsewhere than the workspace, refuses (unsupported or failed), never runs Git
255
- * without the overrides.
256
- */
257
262
  /** The configuration a box is built from: origin, the work tree, the object format and every filter driver. */
258
263
  const CONFIG_READ = ['config', '--null', '--get-regexp', '^(remote\\.origin\\.url|core\\.worktree|extensions\\.objectformat|filter\\..+\\.(smudge|clean|process|required))$'];
259
264
 
@@ -267,6 +272,12 @@ async function sameConfig(repo: Repository): Promise<void> {
267
272
  if (hash(stdout) !== repo.config) failed('the repository configuration changed during the read');
268
273
  }
269
274
 
275
+ /**
276
+ * The box for a located repository: the configuration overrides that neutralize every filter it
277
+ * names, origin's URL, its object format. A filter name `-c` cannot carry, or a work tree
278
+ * configured elsewhere than the workspace, refuses (unsupported or failed), never runs Git
279
+ * without the overrides.
280
+ */
270
281
  async function boxFor(located: Extract<Located, { kind: 'repository' }>, git: string, deadline: number): Promise<Repository | 'unsupported'> {
271
282
  const box: Box = { git, root: located.root, env: environment(located.root, located.gitDir), deadline, overrides: [] };
272
283
  if (!(await recentEnough(box))) throw new RpcError(ERROR.unavailable, FIXED.tooOld, { reason: 'git_unavailable' });
@@ -321,6 +332,9 @@ export function scrubRemoteUrl(url: string | null): string | null {
321
332
  if (scheme) {
322
333
  const protocol = scheme[1]!.toLowerCase();
323
334
  if (protocol === 'file') return null;
335
+ // A slash inside malformed user information must not turn a credential
336
+ // fragment into an apparent authority (for example user:pa/ss@host).
337
+ try { if (!new URL(value).host) return null; } catch { return null; }
324
338
  const host = scheme[2]!.slice(scheme[2]!.lastIndexOf('@') + 1);
325
339
  return host ? `${protocol}://${host}${scheme[3]}` : null;
326
340
  }
@@ -329,6 +343,9 @@ export function scrubRemoteUrl(url: string | null): string | null {
329
343
  // letter. User information is everything up to the last '@' before the first slash.
330
344
  const slash = value.indexOf('/');
331
345
  const at = (slash < 0 ? value : value.slice(0, slash)).lastIndexOf('@');
346
+ // A colon before the final @ is ambiguous with a repository path or malformed credentials.
347
+ // Refuse rather than exposing part of user information as a host/path.
348
+ if (value.includes('@') && value.indexOf(':') >= 0 && value.indexOf(':') < value.lastIndexOf('@')) return null;
332
349
  const scp = /^([^@/:]+):(.*)$/.exec(at < 0 ? value : value.slice(at + 1));
333
350
  if (scp && scp[1]!.length > 1 && !scp[2]!.startsWith('\\')) return `${scp[1]}:${scp[2]}`;
334
351
  return null;
@@ -551,7 +568,7 @@ function sized(file: GitDiffFile): { file: GitDiffFile; cost: number } {
551
568
  for (const hunk of file.hunks) for (const line of hunk.lines) content += Buffer.byteLength(line.content, 'utf8');
552
569
  const bytes = cost(file);
553
570
  if (content <= WORKSPACE_GIT.maxFileBytes && bytes <= PAGE_BYTES) return { file, cost: bytes };
554
- const large: GitDiffFile = { ...file, kind: 'too_large', hunks: [] };
571
+ const large: GitDiffFile = { ...file, kind: 'too_large', additions: 0, deletions: 0, hunks: [] };
555
572
  return { file: large, cost: cost(large) };
556
573
  }
557
574
 
@@ -561,7 +578,8 @@ const PAGE_BYTES = WORKSPACE_GIT.maxTotalBytes - 16 * 1024;
561
578
  // ---- The service ----
562
579
 
563
580
  export type GitReaderOptions = {
564
- registry: { resolve(workspaceId: string): Promise<string> };
581
+ /** Resolves a workspaceId for status and diff; without it they are unavailable (facts needs none). */
582
+ registry?: { resolve(workspaceId: string): Promise<string> };
565
583
  /** Which git: a name looked up on PATH (outside the workspace), or an absolute path (tests). */
566
584
  binary?: string;
567
585
  timeoutMs?: number;
@@ -579,6 +597,7 @@ export function createGitReader({ registry, binary = 'git', timeoutMs = GIT_READ
579
597
  /** The workspace's real path, or the registry's refusal (its messages are fixed). */
580
598
  async function workspaceRoot(workspaceId: unknown): Promise<string> {
581
599
  if (typeof workspaceId !== 'string' || !workspaceId) throw new RpcError(RPC_ERROR.invalidParams, 'workspaceId is required', { reason: 'invalid_params' });
600
+ if (!registry) throw new RpcError(ERROR.unavailable, FIXED.noRegistry);
582
601
  try {
583
602
  return await registry.resolve(workspaceId);
584
603
  } catch (error) {
@@ -726,6 +745,81 @@ export function createGitReader({ registry, binary = 'git', timeoutMs = GIT_READ
726
745
  };
727
746
  }
728
747
 
748
+ /**
749
+ * The directory workspace.git.facts is asked about, as its real path: absolute, already
750
+ * normalised (no empty, `.` or `..` segment, no trailing separator), and a directory.
751
+ */
752
+ async function requestedDirectory(directory: unknown): Promise<string> {
753
+ const invalid = () => new RpcError(RPC_ERROR.invalidParams, FIXED.invalidDirectory, { reason: 'invalid_path' });
754
+ if (typeof directory !== 'string' || !directory || [...directory].length > 4096 || directory.includes('\0')) throw invalid();
755
+ if (!path.isAbsolute(directory) || path.normalize(directory) !== directory) throw invalid();
756
+ const { root } = path.parse(directory);
757
+ const rest = directory.slice(root.length);
758
+ if (rest && rest.split(/[\\/]/).some(segment => segment === '' || segment === '.' || segment === '..')) throw invalid();
759
+ const absent = () => new RpcError(ERROR.notFound, FIXED.noDirectory, { reason: 'not_found' });
760
+ let real: string;
761
+ try { real = await realpath(directory); } catch (error) { if (missing(error)) throw absent(); throw error; }
762
+ let info;
763
+ try { info = await stat(real); } catch (error) { if (missing(error)) throw absent(); throw error; }
764
+ if (!info.isDirectory()) throw new RpcError(ERROR.notFound, FIXED.notDirectory, { reason: 'not_directory' });
765
+ return real;
766
+ }
767
+
768
+ /**
769
+ * workspace.git.facts: what the directory's checkout is, each answer explicit. Its repository's
770
+ * top level (`ok`), a folder inside one (`not_repository_root`, the enclosing repository's
771
+ * facts), no `.git` at or above it (`unknown`, before any Git runs), or a repository alpd does
772
+ * not read (`unsupported`). One porcelain status, stopped at its first change row.
773
+ */
774
+ async function facts(directory: unknown): Promise<GitFacts> {
775
+ const real = await requestedDirectory(directory);
776
+ const deadline = Date.now() + timeoutMs;
777
+ let located = await locate(real);
778
+ if (located.kind === 'not_repository') return { kind: 'unknown' };
779
+ let kind: 'ok' | 'not_repository_root' = 'ok';
780
+ if (located.kind === 'unsupported') {
781
+ // Inside a .git directory is no work tree of the repository above it.
782
+ if (path.relative(located.top, real).split(path.sep).includes('.git')) return { kind: 'unsupported', reason: 'inside_git_dir' };
783
+ located = await locate(located.top);
784
+ if (located.kind !== 'repository') failed('the enclosing repository changed during the read');
785
+ kind = 'not_repository_root';
786
+ }
787
+ const found = located as Extract<Located, { kind: 'repository' }>;
788
+ let git: string | undefined;
789
+ try { git = resolveGit(binary, undefined, found.root); } catch (error) { if (error instanceof IgnoreUnknown) failed('the directory cannot be examined'); throw error; }
790
+ if (!git) throw new RpcError(ERROR.unavailable, FIXED.unavailable, { reason: 'git_unavailable' });
791
+ const repo = await boxFor(found, git, deadline);
792
+ if (repo === 'unsupported') return { kind: 'unsupported', reason: 'worktree_elsewhere' };
793
+ const branch: { oid?: string; head?: string } = {};
794
+ let dirty = false;
795
+ let pending = '';
796
+ const { stopped } = await runGit(repo, ['status', '--porcelain=v2', '-z', '--branch', '--no-ahead-behind', '--untracked-files=all', '--ignored=no', '--ignore-submodules=dirty'], {
797
+ onData: chunk => {
798
+ const fields = (pending + chunk.toString('utf8')).split('\0');
799
+ pending = fields.pop()!;
800
+ for (const field of fields) {
801
+ if (!field) continue;
802
+ if (!field.startsWith('# ')) { dirty = true; return true; }
803
+ const [name, ...rest] = field.slice(2).split(' ');
804
+ if (name === 'branch.oid') branch.oid = rest.join(' ');
805
+ else if (name === 'branch.head') branch.head = rest.join(' ');
806
+ }
807
+ // Headers come first: a row begun is a change, however long its path.
808
+ if (pending && !pending.startsWith('#')) { dirty = true; return true; }
809
+ if (pending.length > 64 * 1024) failed('status header over its bound');
810
+ return false;
811
+ },
812
+ });
813
+ if (!stopped && pending) failed('unterminated status');
814
+ await sameConfig(repo);
815
+ const detached = branch.head === '(detached)';
816
+ return {
817
+ kind, repoRoot: repo.root, branch: !detached && branch.head && validBranchName(branch.head) ? branch.head : null, detached,
818
+ head: branch.oid && /^[0-9a-f]{40,64}$/.test(branch.oid) ? branch.oid : null,
819
+ hasRemote: repo.remoteUrl !== null, remoteUrl: scrubRemoteUrl(repo.remoteUrl), dirty,
820
+ };
821
+ }
822
+
729
823
  /** The untracked files Git does not ignore, at most `limit` that are not blocked (more: `more`). */
730
824
  async function untrackedOf(repo: Repository, relative: string | undefined, limit: number) {
731
825
  const found: string[] = [];
@@ -919,7 +1013,7 @@ export function createGitReader({ registry, binary = 'git', timeoutMs = GIT_READ
919
1013
  type Result = { file: GitDiffFile; cost: number } | undefined;
920
1014
 
921
1015
  async function diffWindow(repo: Repository, planned: Planned[], mode: GitCompare['mode'], range: string[], diffFlags: string[], ignoreWhitespace: boolean): Promise<Result[]> {
922
- const shown = (entry: Entry, kind: GitDiffFile['kind'], extra: Partial<GitDiffFile> = {}, _cost = 0): Result => sized({ path: entry.path, ...(entry.oldPath ? { oldPath: entry.oldPath } : {}), change: entry.change, kind, additions: 0, deletions: 0, hunks: [], ...extra });
1016
+ const shown = (entry: Entry, kind: GitDiffFile['kind'], extra: Partial<GitDiffFile> = {}): Result => sized({ path: entry.path, ...(entry.oldPath ? { oldPath: entry.oldPath } : {}), change: entry.change, kind, additions: 0, deletions: 0, hunks: [], ...extra });
923
1017
  const readable = (size: number) => size <= GIT_READ.maxScanBytes;
924
1018
  const wanted = new Map<string, number>();
925
1019
  for (const entry of planned) {
@@ -987,7 +1081,7 @@ export function createGitReader({ registry, binary = 'git', timeoutMs = GIT_READ
987
1081
  const parsed = parseSection(section);
988
1082
  results[item!.index] = parsed.binary
989
1083
  ? shown(item!.entry, 'binary')
990
- : shown(item!.entry, 'text', { additions: parsed.additions, deletions: parsed.deletions, hunks: parsed.hunks }, section.bytes);
1084
+ : shown(item!.entry, 'text', { additions: parsed.additions, deletions: parsed.deletions, hunks: parsed.hunks });
991
1085
  }
992
1086
  // A file Git listed but gave no section for has no content change (its stat only changed).
993
1087
  }
@@ -1026,7 +1120,7 @@ export function createGitReader({ registry, binary = 'git', timeoutMs = GIT_READ
1026
1120
  if (holdsKey(bytes)) return shown(entry, 'withheld');
1027
1121
  if (likelyBinary(bytes)) return shown(entry, 'binary');
1028
1122
  const { hunks, additions } = addedHunks(DECODER.decode(bytes));
1029
- return shown(entry, 'text', { additions, hunks }, bytes.length + additions);
1123
+ return shown(entry, 'text', { additions, hunks });
1030
1124
  }
1031
1125
 
1032
1126
  /** Runs a read, answering any failure that is not a refusal as `1000 git_failed` (its cause logged). */
@@ -1039,6 +1133,7 @@ export function createGitReader({ registry, binary = 'git', timeoutMs = GIT_READ
1039
1133
  return {
1040
1134
  status: (workspaceId: unknown) => guarded('workspace.git.status', () => status(workspaceId)),
1041
1135
  diff: (params: DiffParams) => guarded('workspace.git.diff', () => diff(params)),
1136
+ facts: (directory: unknown) => guarded('workspace.git.facts', () => facts(directory)),
1042
1137
  };
1043
1138
  }
1044
1139
 
package/src/index.ts CHANGED
@@ -9,3 +9,4 @@ export { createScheduler, duration, renderPrompt, SCHEDULE_GRACE_MS, SCHEDULE_TI
9
9
  export type { ScheduleDelivery, Scheduler } from './scheduler.js';
10
10
  export { attachmentLimits, attachmentName, createAttachmentStore, readAttachmentConfig, sniffMimeType } from './attachments.js';
11
11
  export type { AttachmentReader, AttachmentRuntime, AttachmentStore, Principal } from './attachments.js';
12
+ export { createDiskGuard, isDiskError } from './disk.js';
package/src/main.ts CHANGED
@@ -1,19 +1,21 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { openSync, writeSync } from 'node:fs';
2
+ import { fstatSync, openSync, writeSync } from 'node:fs';
3
3
  import { mkdir, open, readFile, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import templates from 'alp:templates';
7
7
  import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION, withDaemonLifecycle } from '@anhlp/alp-client/index';
8
- import { attachmentStageDir, createAlpRuntime, reclaimCopies, reclaimWorktrees } from '@anhlp/alp-runtime/index';
8
+ import { attachmentStageDir, createAlpRuntime, liveProbes, ModelCatalog, reclaimCopies, reclaimWorktrees, setActiveCatalog } from '@anhlp/alp-runtime/index';
9
9
  import { createDaemonServer } from './server.js';
10
10
  import { acquireLock, heartbeat, releaseLock, updateLock } from './lock.js';
11
11
  import { createStore } from './store.js';
12
+ import { createDiskGuard, guardOutput, isDiskError } from './disk.js';
12
13
  import { readAttachmentConfig } from './attachments.js';
13
14
  import { validateUserSettings } from '@anhlp/alp-core/validation';
14
15
  import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } from '@anhlp/alp-core/backup';
15
16
  import { migrateState } from '@anhlp/alp-core/migrations';
16
17
  import { createLogger } from '@anhlp/alp-core/log';
18
+ import { selfCommand, selfEntry } from '@anhlp/alp-core/packaged';
17
19
 
18
20
  declare const __ALP_VERSION__: string;
19
21
  const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev';
@@ -38,7 +40,8 @@ async function detach(home: string) {
38
40
  await assertPrivateDirectory(path.dirname(log), { create: true });
39
41
  await rotate(log);
40
42
  const output = await open(log, 'a', 0o600);
41
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
43
+ const self = selfCommand('daemon', { script: fileURLToPath(import.meta.url) });
44
+ const child = spawn(self.command, self.args, {
42
45
  detached: true,
43
46
  stdio: ['ignore', output.fd, output.fd, 'ipc'],
44
47
  env: process.env,
@@ -76,7 +79,7 @@ async function detach(home: string) {
76
79
  * log at start as the detached launcher does, then writes its output there itself. The
77
80
  * manager's own file keeps only what Node prints when it dies.
78
81
  */
79
- async function serviceLog(home: string) {
82
+ async function serviceLog(home: string, onError: (error: unknown) => void) {
80
83
  await assertPrivateDirectory(home, { create: true });
81
84
  const { log } = daemonPaths(home);
82
85
  await assertPrivateDirectory(path.dirname(log), { create: true });
@@ -84,7 +87,7 @@ async function serviceLog(home: string) {
84
87
  const fd = openSync(log, 'a', 0o600);
85
88
  for (const stream of [process.stdout, process.stderr]) {
86
89
  stream.write = ((chunk: string | Uint8Array, encoding?: unknown, callback?: unknown) => {
87
- try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch {}
90
+ try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch (error) { onError(error); }
88
91
  const done = typeof encoding === 'function' ? encoding : callback;
89
92
  if (typeof done === 'function') done();
90
93
  return true;
@@ -213,13 +216,18 @@ async function run(home: string) {
213
216
  assignmentResultFile: path.join(home, 'state', 'assignment-results.json'), recallFile: path.join(home, 'state', 'recall.json'), pauseFile: path.join(home, 'state', 'pause.json'), liveFile: path.join(home, 'state', 'live.json'),
214
217
  autoResume: settings?.limits?.autoResume !== false, recoveryResume: settings?.recovery?.autoResume !== false && !opened.restored, previousExit: exit,
215
218
  });
216
- const store = createStore(path.join(home, 'state'));
219
+ // A full disk pauses ALP's work instead of stopping alpd (t-2831).
220
+ const disk = createDiskGuard({ home, runtime, log, ...(Number(process.env.ALP_DISK_CHECK_MS) > 0 ? { intervalMs: Number(process.env.ALP_DISK_CHECK_MS) } : {}) });
221
+ diskReport = error => { disk.report(error); };
222
+ const store = createStore(path.join(home, 'state'), { onWriteError: error => { disk.report(error); } });
217
223
  let stopping: Promise<void> | undefined;
218
224
  const shutdown = (code = 0) => {
219
225
  stopping ??= (async () => {
220
226
  const force = setTimeout(() => process.exit(code), 10_000);
221
227
  force.unref();
222
228
  clearInterval(beat);
229
+ disk.stop();
230
+ modelCatalog?.stop();
223
231
  await server.close().catch(() => {});
224
232
  await runtime.shutdown().catch(() => {});
225
233
  await store.flush();
@@ -234,7 +242,12 @@ async function run(home: string) {
234
242
  // The operator may lower the attachment limits (never raise them): <ALP_HOME>/attachments.json.
235
243
  const attachmentConfig = await readAttachmentConfig(home);
236
244
  for (const problem of attachmentConfig.problems) log.warn(problem, { code: 'ALP_ATTACHMENT_CONFIG' });
237
- const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, home, templates, attachmentOptions: { limits: attachmentConfig.limits }, onShutdown: () => void shutdown() });
245
+ // The live model catalog (t-e5ee): static rows at once, provider lists in the background, every 6 h.
246
+ // ALP_MODEL_CATALOG=static keeps the static rows only (tests, offline hosts).
247
+ const modelCatalog = process.env.ALP_MODEL_CATALOG === 'static' ? undefined : new ModelCatalog({ home, probes: liveProbes() });
248
+ setActiveCatalog(modelCatalog);
249
+ void modelCatalog?.start().catch(() => {});
250
+ const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, home, templates, attachmentOptions: { limits: attachmentConfig.limits }, modelCatalog, onShutdown: () => void shutdown() });
238
251
  const beat = setInterval(() => {
239
252
  void heartbeat(home).then(owned => { if (!owned) void shutdown(1); });
240
253
  const now = new Date();
@@ -242,8 +255,9 @@ async function run(home: string) {
242
255
  }, 30_000);
243
256
  beat.unref();
244
257
  for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
245
- process.on('uncaughtException', error => { log.error('uncaught exception; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
246
- process.on('unhandledRejection', error => { log.error('unhandled rejection; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
258
+ // A write the disk refused is no reason to stop: the disk guard pauses work until it takes writes again.
259
+ process.on('uncaughtException', error => { if (disk.report(error)) return; log.error('uncaught exception; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
260
+ process.on('unhandledRejection', error => { if (disk.report(error)) return; log.error('unhandled rejection; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
247
261
  phase = 'listen';
248
262
  try {
249
263
  await server.listen();
@@ -256,22 +270,27 @@ async function run(home: string) {
256
270
  await updateLock(home, { ...lock, ready: true });
257
271
  // Clients that cannot locate alpd themselves (the Paseo plugin) start it from here next time.
258
272
  const { install } = daemonPaths(home);
259
- await writeFile(`${install}.tmp`, JSON.stringify({ entry: fileURLToPath(import.meta.url), version: VERSION }), { mode: 0o600 })
273
+ await writeFile(`${install}.tmp`, JSON.stringify({ entry: selfEntry(fileURLToPath(import.meta.url)), version: VERSION }), { mode: 0o600 })
260
274
  .then(() => rename(`${install}.tmp`, install))
261
275
  .catch(error => log.warn('could not record alpd\'s location', { code: 'ALP_INSTALL_RECORD_FAILED', error }));
262
276
  if (opened.restored) await clearRestoredMarker(home).catch(error => log.warn('could not clear the restore marker', { code: 'ALP_STATE_RESTORED', error }));
277
+ disk.start();
263
278
  if (process.connected) process.send?.('alpd.ready');
264
279
  log.info(`alpd ${VERSION} ready on ${socket} (pid ${process.pid})`, { event: 'ready', version: VERSION, pid: process.pid });
265
280
  }
266
281
 
267
282
  const home = alpHome();
283
+ /** Where a failed write to alpd's own output goes once the disk guard exists. */
284
+ let diskReport = (_error: unknown) => {};
285
+ // Before anything logs: a log write the full disk refused must not end alpd (t-2831).
286
+ guardOutput(error => { if (isDiskError(error)) diskReport(error); }, { fstatSync, writeSync });
268
287
  try {
269
288
  if (process.argv.includes('--detach')) await detach(home);
270
289
  else {
271
290
  // A direct foreground/login invocation is an explicit start. Do this before
272
291
  // admission registration, so a stop published during startup is preserved.
273
292
  if (!process.connected) await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
274
- if (process.argv.includes('--service')) await serviceLog(home);
293
+ if (process.argv.includes('--service')) await serviceLog(home, error => { if (isDiskError(error)) diskReport(error); });
275
294
  if (process.connected) await run(home);
276
295
  else {
277
296
  // Retain admission through readiness even if the requesting service client
@@ -0,0 +1,122 @@
1
+ /** Identity-bound native PTY owner; shipped helper only, never runtime compilation. */
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { existsSync, readFileSync, statSync } from 'node:fs';
5
+ import { fileURLToPath } from 'node:url';
6
+ import path from 'node:path';
7
+ import { StringDecoder } from 'node:string_decoder';
8
+ export type CleanupResult = { observed: number; live: number; uncertain: number; coverage?: 'root-only'; outputOpen?: boolean };
9
+ type Exit = { exitCode: number | null; signal?: number };
10
+ type Listener<T> = (event: T) => void;
11
+ const sha = (value: Buffer) => createHash('sha256').update(value).digest('hex');
12
+ function binary() {
13
+ const libc = process.platform === 'linux' ? (process.report?.getReport() as { header?: { glibcVersionRuntime?: string } })?.header?.glibcVersionRuntime ? 'glibc' : 'musl' : undefined;
14
+ const slot = [process.platform, process.arch, libc].filter(Boolean).join('-');
15
+ // The ALP executable (t-1e02) extracts its helper; registerPackaged in @anhlp/alp-core/packaged publishes assetDir here.
16
+ // Read through globalThis so this shipped adapter stays free of package imports.
17
+ const assets = (globalThis as { [key: symbol]: { assetDir?: () => string | undefined } | undefined })[Symbol.for('alp.packaged')]?.assetDir?.();
18
+ const adjacent = assets ? path.join(assets, 'terminal-native') : path.join(path.dirname(fileURLToPath(import.meta.url)), 'terminal-native');
19
+ const dir = assets || existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../native');
20
+ const file = path.join(dir, 'prebuilt', slot, 'terminal-owner');
21
+ const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), 'manifest.json'), 'utf8'));
22
+ if (!statSync(file).isFile() || manifest.protocol !== 1 || manifest.slot !== slot || manifest.source !== sha(readFileSync(path.join(dir, 'terminal-owner.c'))) || manifest.sha256 !== sha(readFileSync(file))) throw new Error('Native helper manifest mismatch');
23
+ return file;
24
+ }
25
+ /** Only an authenticated helper's exact capability record can select compatibility. */
26
+ export function nativeCapabilityOf(probe: { status: number | null; stdout: string }, platform: NodeJS.Platform): { available: boolean; protection?: 'root-only'; reason?: string } {
27
+ if (probe.status === 0 && probe.stdout.trim() === 'alp-terminal-owner:1') return { available: true };
28
+ if (platform === 'linux' && probe.status === 0 && probe.stdout.trim() === 'alp-terminal-owner:1:root-only') return { available: true, protection: 'root-only', reason: 'bound_signal_unavailable' };
29
+ return { available: false, reason: 'native_capability_unavailable' };
30
+ }
31
+ export function nativeTerminalCapability(): ReturnType<typeof nativeCapabilityOf> {
32
+ try {
33
+ const probe = spawnSync(binary(), ['--capability'], { encoding: 'utf8', timeout: 2_000, maxBuffer: 4096 });
34
+ return nativeCapabilityOf(probe, process.platform);
35
+ } catch { return { available: false, reason: 'native_prebuilt_unavailable' }; }
36
+ }
37
+ export async function nativePtySpawn(file: string, args: string[], options: { name: string; cols: number; rows: number; cwd: string; env: Record<string, string>; killGraceMs?: number; signal?: AbortSignal; protection?: 'root-only' | 'none' }) {
38
+ if (options.signal?.aborted) throw new Error('Native terminal startup cancelled');
39
+ const child = spawn(binary(), [...(options.protection === 'root-only' ? ['--root-only'] : []), String(options.cols), String(options.rows), String(options.killGraceMs ?? 1000), options.cwd, file, ...args], { env: options.env, stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe'] });
40
+ const control = child.stdio[4] as import('node:stream').Writable;
41
+ const events = child.stdio[3] as import('node:stream').Readable;
42
+ const data = new Set<Listener<string>>(), exits = new Set<Listener<Exit>>();
43
+ const decoder = new StringDecoder('utf8'); let buffered = '', protocol = '', exit: Exit | undefined, pid = 0;
44
+ let readyResolve!: () => void, readyReject!: (error: Error) => void, finish!: (result: CleanupResult) => void;
45
+ const ready = new Promise<void>((resolve, reject) => { readyResolve = resolve; readyReject = reject; });
46
+ const finished = new Promise<CleanupResult>(resolve => { finish = resolve; });
47
+ let result: CleanupResult | undefined, completed = false, closing = false, adapterFailed = false;
48
+ let controlBlocked = false, pendingResize: string | undefined;
49
+ const resizeCommand = (command: string) => {
50
+ if (closing || result) return;
51
+ if (controlBlocked) { pendingResize = command; return; }
52
+ controlBlocked = !control.write(command);
53
+ };
54
+ control.on('drain', () => {
55
+ controlBlocked = false;
56
+ const next = pendingResize; pendingResize = undefined;
57
+ if (next) resizeCommand(next);
58
+ });
59
+ const closeOwner = () => {
60
+ if (closing || result) return;
61
+ closing = true; pendingResize = undefined;
62
+ // No queue of resizes can stand ahead of cleanup: closing fd4 wakes native POLLHUP.
63
+ control.destroy(); child.stdin?.end();
64
+ };
65
+ const fail = (reason: string) => {
66
+ adapterFailed = true;
67
+ readyReject(new Error(reason));
68
+ // No bare child PID signaling. Closing owner input/control asks native bound cleanup.
69
+ closeOwner();
70
+ };
71
+ const timer = setTimeout(() => fail('Native terminal startup timed out'), 5000);
72
+ const complete = (value: CleanupResult) => { if (!completed) { completed = true; result = adapterFailed ? { ...value, uncertain: Math.max(1, value.uncertain) } : value; finish(result); } };
73
+ child.on('error', error => { fail(error.message); complete({ observed: 0, live: 0, uncertain: 1 }); });
74
+ child.on('close', () => {
75
+ clearTimeout(timer);
76
+ if (!pid) readyReject(new Error('Native terminal refused startup'));
77
+ // close follows every stdio end: service exit disposal cannot discard trailing PTY output.
78
+ exit ??= { exitCode: null };
79
+ for (const listener of exits) listener(exit);
80
+ complete(result ?? { observed: 0, live: 0, uncertain: 1 });
81
+ });
82
+ child.stderr?.resume();
83
+ // Pipes may fail after native exit. Native protocol/close supplies the authoritative outcome.
84
+ child.stdin?.on('error', () => {}); control.on('error', () => {});
85
+ child.stdout?.on('data', (chunk: Buffer) => {
86
+ const text = decoder.write(chunk);
87
+ if (data.size) for (const listener of data) listener(text);
88
+ else if (Buffer.byteLength(buffered) + Buffer.byteLength(text) <= 1024*1024) buffered += text;
89
+ else fail('Native terminal output limit exceeded');
90
+ });
91
+ events.on('data', (chunk: Buffer) => {
92
+ protocol += chunk.toString('utf8');
93
+ if (protocol.length > 8192) { fail('Invalid native protocol'); return; }
94
+ let newline;
95
+ while ((newline = protocol.indexOf('\n')) >= 0) {
96
+ const line = protocol.slice(0, newline); protocol = protocol.slice(newline + 1);
97
+ try {
98
+ const value = JSON.parse(line);
99
+ if (value.ready && value.protocol === 1 && Number.isSafeInteger(value.ready) && value.ready > 1) { pid = value.ready; clearTimeout(timer); readyResolve(); }
100
+ else if ('exitCode' in value) { exit = { exitCode: value.exitCode, signal: value.signal }; }
101
+ else if (value.cleanup === true && ['observed', 'live', 'uncertain'].every(key => Number.isSafeInteger(value[key]) && value[key] >= 0)) result = value;
102
+ else if (value.refused === 'terminal_protection_ack_required' || value.refused === 'terminal_unsupported') { readyReject(Object.assign(new Error('Native terminal capability changed before startup'), { terminalReason: value.refused })); }
103
+ else if (value.error) fail(String(value.error));
104
+ else fail('Invalid native event');
105
+ } catch { fail('Invalid native JSON'); }
106
+ }
107
+ });
108
+ const abort = () => fail('Native terminal startup cancelled');
109
+ options.signal?.addEventListener('abort', abort, { once: true });
110
+ if (options.signal?.aborted) abort();
111
+ try { await ready; } catch (error) { const cleanupResult = await finished; throw Object.assign(error instanceof Error ? error : new Error(String(error)), { cleanupResult }); }
112
+ finally { options.signal?.removeEventListener('abort', abort); }
113
+ return {
114
+ pid,
115
+ write(value: string) { if (closing || result) return; if ((child.stdin?.writableLength ?? 0) + Buffer.byteLength(value) > 1024*1024) { fail('Native input limit exceeded'); return; } child.stdin?.write(value); },
116
+ resize(cols: number, rows: number) { if (Number.isInteger(cols) && Number.isInteger(rows) && cols > 0 && cols <= 1000 && rows > 0 && rows <= 1000) resizeCommand(`R ${cols} ${rows}\n`); },
117
+ kill() { closeOwner(); },
118
+ cleanup() { closeOwner(); return finished; },
119
+ onData(listener: Listener<string>) { data.add(listener); if (buffered) { const value = buffered; buffered = ''; queueMicrotask(() => { if (data.has(listener)) listener(value); }); } return { dispose() { data.delete(listener); } }; },
120
+ onExit(listener: Listener<Exit>) { exits.add(listener); if (exit && completed) { const value = exit; queueMicrotask(() => { if (exits.has(listener)) listener(value); }); } return { dispose() { exits.delete(listener); } }; },
121
+ };
122
+ }
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;
@@ -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 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: [] });