@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.
- package/dist/THIRD-PARTY-NOTICES.txt +26 -1
- package/dist/alpd.js +10768 -2592
- package/dist/attachments.d.ts +25 -49
- package/dist/attachments.js +45 -8
- package/dist/build-manifest.json +14 -1
- package/dist/conversation.js +18 -2
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +141 -2
- package/dist/files.js +377 -68
- package/dist/git.d.ts +8 -2
- package/dist/git.js +111 -12
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/dist/main.js +57 -12
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +198 -0
- package/dist/operations.d.ts +12 -2
- package/dist/operations.js +22 -11
- package/dist/registry.js +1 -1
- package/dist/scheduler.js +8 -2
- package/dist/schedules.d.ts +2 -1
- package/dist/schedules.js +6 -4
- package/dist/server.d.ts +4 -2
- package/dist/server.js +171 -43
- package/dist/store.d.ts +3 -1
- package/dist/store.js +4 -3
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +43 -7
- package/dist/terminals.js +222 -139
- package/dist/windows-terminal.d.ts +29 -0
- package/dist/windows-terminal.js +122 -0
- package/dist/worktrees.d.ts +25 -1
- package/dist/worktrees.js +74 -2
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +11 -7
- package/src/attachments.ts +46 -8
- package/src/conversation.ts +22 -2
- package/src/disk.ts +175 -0
- package/src/files.ts +505 -80
- package/src/git.ts +113 -18
- package/src/index.ts +1 -0
- package/src/main.ts +53 -13
- package/src/native-terminal.ts +122 -0
- package/src/operations.ts +28 -12
- package/src/registry.ts +1 -1
- package/src/scheduler.ts +13 -3
- package/src/schedules.ts +5 -2
- package/src/server.ts +164 -36
- package/src/store.ts +2 -1
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +205 -155
- package/src/windows-terminal.ts +123 -0
- package/src/worktrees.ts +97 -2
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows terminals (best-effort, like Paseo/Orca): the platform PTY through node-pty (ConPTY).
|
|
3
|
+
* There is no protection helper on Windows: closing a terminal kills its pty (node-pty `kill`),
|
|
4
|
+
* which ends the shell; processes it started may keep running. Terminals report `protection: 'none'`.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import type { PtySpawn } from './terminals.js';
|
|
10
|
+
|
|
11
|
+
type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
|
|
12
|
+
pid: number; write(data: string): void; resize(cols: number, rows: number): void; kill(signal?: string): void;
|
|
13
|
+
onData(listener: (data: string) => void): { dispose(): void }; onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
|
|
14
|
+
} };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* In the ALP executable (t-1e02) node-pty is not in node_modules: the build embeds its JavaScript and
|
|
18
|
+
* the win32 prebuilt (conpty.node, conpty/conpty.dll, OpenConsole.exe), extracted with the other
|
|
19
|
+
* assets. registerPackaged publishes assetDir on globalThis; read it there so this adapter needs no package import.
|
|
20
|
+
*/
|
|
21
|
+
function packagedNodePty(): string | undefined {
|
|
22
|
+
const assets = (globalThis as { [key: symbol]: { assetDir?: () => string | undefined } | undefined })[Symbol.for('alp.packaged')]?.assetDir?.();
|
|
23
|
+
const entry = assets ? path.join(assets, 'node-pty', 'lib', 'index.js') : undefined;
|
|
24
|
+
return entry && existsSync(entry) ? entry : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
let loaded: NodePty | null | undefined;
|
|
28
|
+
/** node-pty, or undefined when it cannot load on this host. */
|
|
29
|
+
export function loadNodePty(): NodePty | undefined {
|
|
30
|
+
if (loaded === undefined) {
|
|
31
|
+
try { loaded = createRequire(import.meta.url)(packagedNodePty() ?? 'node-pty') as NodePty; } catch { loaded = null; }
|
|
32
|
+
}
|
|
33
|
+
return loaded ?? undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function windowsTerminalCapability(): { available: boolean; protection?: 'none'; reason?: string } {
|
|
37
|
+
return loadNodePty() ? { available: true, protection: 'none' } : { available: false, reason: 'node_pty_unavailable' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The shell for a Windows terminal: COMSPEC when absolute, else cmd.exe. */
|
|
41
|
+
export function windowsShell(env: NodeJS.ProcessEnv = process.env): string {
|
|
42
|
+
const candidate = env.ComSpec ?? env.COMSPEC;
|
|
43
|
+
return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : 'cmd.exe';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const windowsPtySpawn: PtySpawn = (file, args, options) => {
|
|
47
|
+
if (options.signal?.aborted) throw new Error('Terminal startup cancelled');
|
|
48
|
+
const pty = loadNodePty();
|
|
49
|
+
if (!pty) throw new Error('node-pty is unavailable on this host');
|
|
50
|
+
// The executable uses the conpty.dll and OpenConsole.exe it embeds: with the system ConPTY, node-pty's
|
|
51
|
+
// kill() forks a console-list helper through process.execPath, which there is alp.exe (it would refuse
|
|
52
|
+
// the script and leave node-pty waiting 5 s). With the DLL, kill() ends the session by closing input.
|
|
53
|
+
const spawnOptions = { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true, ...(packagedNodePty() ? { useConptyDll: true } : {}) };
|
|
54
|
+
const child = typeof process.versions.bun === 'string' ? spawnUnderBun(pty, file, args, spawnOptions) : pty.spawn(file, args, spawnOptions);
|
|
55
|
+
let killed = false;
|
|
56
|
+
return {
|
|
57
|
+
pid: child.pid,
|
|
58
|
+
write(data: string) { if (!killed) child.write(data); },
|
|
59
|
+
resize(cols: number, rows: number) { if (!killed) try { child.resize(cols, rows); } catch { /* exited */ } },
|
|
60
|
+
// Best-effort: node-pty ends the ConPTY session and its shell; descendants are not guaranteed.
|
|
61
|
+
kill() { if (killed) return; killed = true; try { child.kill(); } catch { /* already exited */ } },
|
|
62
|
+
onData: listener => child.onData(listener),
|
|
63
|
+
onExit: listener => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal })),
|
|
64
|
+
};
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The ALP executable runs on Bun (t-1e02), where node-pty's input stream, `new net.Socket({ fd })`
|
|
69
|
+
* around the fd it opens on ConPTY's input pipe, takes the fd but never writes to it (output, read
|
|
70
|
+
* by a worker, works; probed on windows-2022 with Bun 1.4.2). While node-pty spawns (synchronously),
|
|
71
|
+
* hand it a small writer for that fd instead: the same calls node-pty makes on its input socket
|
|
72
|
+
* (setEncoding, write, destroy, readable), with writes in order through fs.write and the fd closed
|
|
73
|
+
* once on destroy.
|
|
74
|
+
*/
|
|
75
|
+
function spawnUnderBun(pty: NodePty, file: string, args: string[], options: Record<string, unknown>) {
|
|
76
|
+
const load = createRequire(import.meta.url);
|
|
77
|
+
const fs = load('node:fs') as typeof import('node:fs');
|
|
78
|
+
const net = load('node:net') as { Socket: new (...args: unknown[]) => unknown };
|
|
79
|
+
const Socket = net.Socket;
|
|
80
|
+
function InputSocket(this: unknown, ...rest: unknown[]) {
|
|
81
|
+
const [opts] = rest as [{ fd?: unknown; writable?: boolean; readable?: boolean } | undefined];
|
|
82
|
+
if (opts && typeof opts.fd === 'number' && opts.writable === true && opts.readable === false) return fdWriter(fs, opts.fd);
|
|
83
|
+
return new Socket(...rest);
|
|
84
|
+
}
|
|
85
|
+
InputSocket.prototype = Socket.prototype;
|
|
86
|
+
net.Socket = InputSocket as unknown as typeof Socket;
|
|
87
|
+
try { return pty.spawn(file, args, options); } finally { net.Socket = Socket; }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A write-only stand-in for net.Socket over a pipe fd: ordered writes, closed once; after a failed write it drops the rest. */
|
|
91
|
+
function fdWriter(fs: typeof import('node:fs'), fd: number) {
|
|
92
|
+
let queue: Promise<void> = Promise.resolve();
|
|
93
|
+
let closed = false;
|
|
94
|
+
let failed = false;
|
|
95
|
+
const writer = {
|
|
96
|
+
readable: false,
|
|
97
|
+
writable: true,
|
|
98
|
+
setEncoding() { return writer; },
|
|
99
|
+
write(data: string | Uint8Array) {
|
|
100
|
+
if (closed || failed) return false;
|
|
101
|
+
const bytes = typeof data === 'string' ? Buffer.from(data, 'utf8') : Buffer.from(data);
|
|
102
|
+
queue = queue.then(() => new Promise<void>(resolve => {
|
|
103
|
+
const rest = (offset: number): void => {
|
|
104
|
+
if (closed || failed || offset >= bytes.length) return resolve();
|
|
105
|
+
fs.write(fd, bytes, offset, bytes.length - offset, null, (error, written) => {
|
|
106
|
+
if (error) { failed = true; writer.writable = false; return resolve(); }
|
|
107
|
+
rest(offset + written);
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
rest(0);
|
|
111
|
+
}));
|
|
112
|
+
return true;
|
|
113
|
+
},
|
|
114
|
+
destroy() {
|
|
115
|
+
if (closed) return writer;
|
|
116
|
+
closed = true;
|
|
117
|
+
writer.writable = false;
|
|
118
|
+
void queue.then(() => fs.close(fd, () => {}));
|
|
119
|
+
return writer;
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
return writer;
|
|
123
|
+
}
|
package/src/worktrees.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
|
-
import {
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, readFile, realpath, stat } from 'node:fs/promises';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import { user_worktree } from '@anhlp/alp-core';
|
|
5
6
|
import { RegistryError, type RegistryService, type Registry, type WorkspaceRecord } from './registry.js';
|
|
6
7
|
|
|
7
8
|
type Mapping = { id: string; source: string; commonDir: string; parent: string };
|
|
8
9
|
type Context = { principalId?: string; principalEpoch?: string; mappingIds?: string[]; authorizedRoots?: string[] };
|
|
10
|
+
/** What the owner confirms before a legacy managed worktree is adopted (t-c1ba), each proven from Git and the filesystem. */
|
|
11
|
+
export type AdoptionFacts = { workspaceId: string; directory: string; source: string; commonDir: string; gitDir: string; branch: string; head: string };
|
|
9
12
|
const fail = (reason: string, message: string, code = 1004): never => {
|
|
10
13
|
throw new RegistryError(code, message, { reason });
|
|
11
14
|
};
|
|
@@ -52,7 +55,8 @@ export function createWorkspaceWorktrees(
|
|
|
52
55
|
home: string,
|
|
53
56
|
registry: RegistryService,
|
|
54
57
|
guard: <T>(directory: string, run: () => Promise<T>) => Promise<T>,
|
|
55
|
-
register: (directory: string) => Promise<void
|
|
58
|
+
register: (directory: string) => Promise<void>,
|
|
59
|
+
adoptWorkspace?: (directory: string, verify: (canonical: string) => Promise<void>) => Promise<void>
|
|
56
60
|
) {
|
|
57
61
|
const adapter = git();
|
|
58
62
|
async function approved(context: Context, source: string, mappingId: string, native = true) {
|
|
@@ -77,6 +81,62 @@ export function createWorkspaceWorktrees(
|
|
|
77
81
|
fail('identity_changed', 'Source identity changed', 1003);
|
|
78
82
|
return w;
|
|
79
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* Proves what adopting a managed worktree would certify. The registry row only names what to
|
|
86
|
+
* check; it is never evidence of identity, and never permission to delete.
|
|
87
|
+
*/
|
|
88
|
+
async function adoptionFacts(r: Registry, id: string): Promise<AdoptionFacts> {
|
|
89
|
+
const w = workspace(r, id);
|
|
90
|
+
const meta = w.worktree;
|
|
91
|
+
if (!meta || meta.kind !== 'user' || meta.removedAt || w.archivedAt)
|
|
92
|
+
return fail('not_managed', 'Only a present managed user worktree can be adopted', 1003);
|
|
93
|
+
if (Object.values(r.worktreeJournal ?? {}).some((j) => j.intent.id === w.id))
|
|
94
|
+
fail('reconciliation_required', 'Workspace is pending reconciliation');
|
|
95
|
+
// The source repository and its commonDir as the host approves them now, not as the row recorded them.
|
|
96
|
+
const mapping = (await worktreeMappings(home)).find(
|
|
97
|
+
(m) => m.id === meta.mappingId && m.source === meta.source && m.commonDir === meta.commonDir
|
|
98
|
+
);
|
|
99
|
+
if (!mapping) return fail('outside_workspace', 'The host does not approve its destination mapping now', 1003);
|
|
100
|
+
const directory = path.join(mapping.parent, w.id);
|
|
101
|
+
const branch = `alp/workspace/${w.id}`;
|
|
102
|
+
if (!/^wks_[0-9a-f]{16}$/.test(w.id) || w.directory !== directory || (w.canonical ?? w.directory) !== directory || meta.branch !== branch)
|
|
103
|
+
fail('identity_changed', 'Not a generated managed worktree', 1003);
|
|
104
|
+
// No symlink anywhere on the path: it is a real directory whose canonical path is itself.
|
|
105
|
+
const info = await lstat(directory).catch(() => undefined);
|
|
106
|
+
if (!info?.isDirectory() || (await realpath(directory).catch(() => undefined)) !== directory)
|
|
107
|
+
fail('identity_changed', 'Managed worktree path is missing or not canonical', 1003);
|
|
108
|
+
const origin = await adapter.facts(mapping.source).catch(() => undefined);
|
|
109
|
+
if (origin?.commonDir !== mapping.commonDir) fail('identity_changed', 'Source repository identity changed', 1003);
|
|
110
|
+
// Git lists it as a linked worktree of that repository on its own branch, neither locked nor prunable.
|
|
111
|
+
const row = await adapter.inspect(mapping.source, directory, branch).catch(() => undefined);
|
|
112
|
+
const target = row ? await adapter.facts(directory).catch(() => undefined) : undefined;
|
|
113
|
+
if (
|
|
114
|
+
!row ||
|
|
115
|
+
!target ||
|
|
116
|
+
target.commonDir !== mapping.commonDir ||
|
|
117
|
+
target.gitDir === target.commonDir ||
|
|
118
|
+
target.gitDir !== meta.gitDir ||
|
|
119
|
+
target.branch !== branch ||
|
|
120
|
+
row.HEAD !== target.head
|
|
121
|
+
)
|
|
122
|
+
return fail('identity_changed', 'Git does not list it as this managed worktree', 1003);
|
|
123
|
+
return { workspaceId: w.id, directory, source: mapping.source, commonDir: mapping.commonDir, gitDir: target.gitDir, branch, head: target.head };
|
|
124
|
+
}
|
|
125
|
+
const owner = (context: Context) => {
|
|
126
|
+
if ((context.principalId ?? 'owner') !== 'owner' || (context.principalEpoch ?? 'owner') !== 'owner' || context.mappingIds || context.authorizedRoots)
|
|
127
|
+
fail('owner_only', 'Only the host owner adopts a workspace', 1003);
|
|
128
|
+
};
|
|
129
|
+
/** Owner-private append-only record of every adoption request and its outcome. */
|
|
130
|
+
async function audit(entry: Record<string, unknown>) {
|
|
131
|
+
const file = path.join(home, 'state', 'workspace-adoptions.jsonl');
|
|
132
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
133
|
+
const handle = await open(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
|
|
134
|
+
try {
|
|
135
|
+
await handle.writeFile(JSON.stringify({ at: new Date().toISOString(), ...entry }) + '\n');
|
|
136
|
+
} finally {
|
|
137
|
+
await handle.close();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
80
140
|
async function clean(source: string, target: string, branch: string, head: string) {
|
|
81
141
|
if (!(await adapter.inspect(source, target, branch)))
|
|
82
142
|
fail('outcome_unknown', 'Worktree creation needs owner reconciliation', 1005);
|
|
@@ -98,6 +158,41 @@ export function createWorkspaceWorktrees(
|
|
|
98
158
|
} catch {}
|
|
99
159
|
return { ...row, branch, ...(worktree ? { managedWorktree: true } : {}) };
|
|
100
160
|
},
|
|
161
|
+
/** What adopting this legacy managed worktree would certify (t-c1ba); it changes nothing. */
|
|
162
|
+
async adoption(workspaceId: string, context: Context = {}) {
|
|
163
|
+
owner(context);
|
|
164
|
+
return adoptionFacts(await registry.snapshot(), workspaceId);
|
|
165
|
+
},
|
|
166
|
+
/**
|
|
167
|
+
* Certifies a managed worktree that predates birth certification, once the owner confirmed the
|
|
168
|
+
* facts `adoption` showed. The facts are proven again under the runtime's removal guard, which
|
|
169
|
+
* also refuses any checkout an assignment, claim, lease or session still owns. Removal stays a
|
|
170
|
+
* separate request with all of its own checks.
|
|
171
|
+
*/
|
|
172
|
+
async adopt(p: { workspaceId: string; confirm: AdoptionFacts }, context: Context = {}) {
|
|
173
|
+
owner(context);
|
|
174
|
+
if (!adoptWorkspace) return fail('guard_unavailable', 'Runtime cannot prove safe adoption', 1005);
|
|
175
|
+
const confirmed = (facts: AdoptionFacts) =>
|
|
176
|
+
!!p.confirm &&
|
|
177
|
+
typeof p.confirm === 'object' &&
|
|
178
|
+
Object.keys(p.confirm).length === Object.keys(facts).length &&
|
|
179
|
+
(Object.keys(facts) as (keyof AdoptionFacts)[]).every((k) => p.confirm[k] === facts[k]);
|
|
180
|
+
const facts = await adoptionFacts(await registry.snapshot(), p.workspaceId);
|
|
181
|
+
if (!confirmed(facts)) fail('confirmation_mismatch', 'The workspace differs from what was confirmed; review it and confirm again', 1003);
|
|
182
|
+
// Logged before certification: no adoption happens unrecorded.
|
|
183
|
+
await audit({ event: 'adoption.requested', actor: 'owner', ...facts });
|
|
184
|
+
try {
|
|
185
|
+
await adoptWorkspace(facts.directory, async () => {
|
|
186
|
+
if (!confirmed(await adoptionFacts(await registry.snapshot(), p.workspaceId)))
|
|
187
|
+
fail('confirmation_mismatch', 'The workspace changed after it was confirmed; review it and confirm again', 1003);
|
|
188
|
+
});
|
|
189
|
+
} catch (error: any) {
|
|
190
|
+
await audit({ event: 'adoption.refused', actor: 'owner', workspaceId: facts.workspaceId, reason: error?.data?.reason ?? 'failed', error: error?.message ?? String(error) }).catch(() => {});
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
await audit({ event: 'adoption.certified', actor: 'owner', workspaceId: facts.workspaceId, directory: facts.directory });
|
|
194
|
+
return { adopted: facts };
|
|
195
|
+
},
|
|
101
196
|
async assertAvailable(directory: string) {
|
|
102
197
|
const r = await registry.snapshot();
|
|
103
198
|
const canonical = await realpath(directory).catch(() => path.resolve(directory));
|