@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,389 @@
|
|
|
1
|
+
/* ALP terminal owner protocol 1. Native-only spawn, lifetime acquisition, signals and reap.
|
|
2
|
+
* Linux reduced-protection mode signals only its continuously owned unreaped root. See README.md for proof obligations and platform limits. */
|
|
3
|
+
#define _GNU_SOURCE
|
|
4
|
+
#include <sys/types.h>
|
|
5
|
+
#include <sys/wait.h>
|
|
6
|
+
#include <sys/ioctl.h>
|
|
7
|
+
#include <sys/stat.h>
|
|
8
|
+
#include <poll.h>
|
|
9
|
+
#include <fcntl.h>
|
|
10
|
+
#include <signal.h>
|
|
11
|
+
#include <stdint.h>
|
|
12
|
+
#include <stdio.h>
|
|
13
|
+
#include <stdlib.h>
|
|
14
|
+
#include <string.h>
|
|
15
|
+
#include <errno.h>
|
|
16
|
+
#include <unistd.h>
|
|
17
|
+
#include <time.h>
|
|
18
|
+
#ifdef __APPLE__
|
|
19
|
+
#include <util.h>
|
|
20
|
+
#include <libproc.h>
|
|
21
|
+
#include <mach/mach.h>
|
|
22
|
+
#include <mach/mach_traps.h>
|
|
23
|
+
#include <mach/task_info.h>
|
|
24
|
+
/* Approved private ABI, XNU xnu-12377.1.9 bsd/sys/proc_info_private.h, flavor17.
|
|
25
|
+
* Keep the complete 56-byte layout; parent identity is NEVER adoption authority. */
|
|
26
|
+
struct uniqinfo { uint8_t uuid[16]; uint64_t unique, parent; int32_t version, original_parent_version; uint64_t reserved[2]; };
|
|
27
|
+
_Static_assert(sizeof(struct uniqinfo) == 56, "private ABI size");
|
|
28
|
+
#else
|
|
29
|
+
#include <pty.h>
|
|
30
|
+
#include <dirent.h>
|
|
31
|
+
#include <sys/syscall.h>
|
|
32
|
+
#include <sys/vfs.h>
|
|
33
|
+
#include <linux/magic.h>
|
|
34
|
+
#endif
|
|
35
|
+
#define MAX_TRACKED 4096
|
|
36
|
+
#define QUEUE (1024 * 1024)
|
|
37
|
+
#ifndef START_TIMEOUT_MS
|
|
38
|
+
#define START_TIMEOUT_MS 3000
|
|
39
|
+
#endif
|
|
40
|
+
typedef struct {
|
|
41
|
+
pid_t pid;
|
|
42
|
+
#ifdef __APPLE__
|
|
43
|
+
uint64_t unique;
|
|
44
|
+
#else
|
|
45
|
+
int fd;
|
|
46
|
+
#endif
|
|
47
|
+
} identity;
|
|
48
|
+
static identity known[MAX_TRACKED];
|
|
49
|
+
static size_t count;
|
|
50
|
+
static pid_t root;
|
|
51
|
+
static int scanning_failed, held = 1;
|
|
52
|
+
#ifndef __APPLE__
|
|
53
|
+
static int root_only, compatibility_available;
|
|
54
|
+
/* Exclusive natural parent retains this child (live or WNOWAIT zombie).
|
|
55
|
+
* ECHILD revokes authority permanently; never infer ownership from a PID lookup. */
|
|
56
|
+
static int root_status(void) {
|
|
57
|
+
if (!held || root <= 1) return 2;
|
|
58
|
+
siginfo_t info = {0}; int result;
|
|
59
|
+
do { result=waitid(P_PID,root,&info,WEXITED|WNOHANG|WNOWAIT); } while(result<0 && errno==EINTR);
|
|
60
|
+
if(result<0) { if(errno==ECHILD) held=0; return 2; }
|
|
61
|
+
return info.si_pid==root ? 0 : 1;
|
|
62
|
+
}
|
|
63
|
+
#endif
|
|
64
|
+
static long long clock_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (long long)t.tv_sec*1000+t.tv_nsec/1000000; }
|
|
65
|
+
static void event(const char *s) { (void)!write(3, s, strlen(s)); }
|
|
66
|
+
#ifdef __APPLE__
|
|
67
|
+
static int unique(pid_t p, struct uniqinfo *u) { memset(u, 0, sizeof(*u)); errno = 0; return proc_pidinfo(p, 17, 0, u, sizeof(*u)) == sizeof(*u) && u->unique != 0; }
|
|
68
|
+
static int token(pid_t p, audit_token_t *t) {
|
|
69
|
+
mach_port_t task = MACH_PORT_NULL;
|
|
70
|
+
if (task_name_for_pid(mach_task_self(), p, &task) != KERN_SUCCESS) return 0;
|
|
71
|
+
mach_msg_type_number_t n = TASK_AUDIT_TOKEN_COUNT;
|
|
72
|
+
kern_return_t r = task_info(task, TASK_AUDIT_TOKEN, (task_info_t)t, &n);
|
|
73
|
+
mach_port_deallocate(mach_task_self(), task);
|
|
74
|
+
return r == KERN_SUCCESS && n == TASK_AUDIT_TOKEN_COUNT && t->val[5] == (uint32_t)p;
|
|
75
|
+
}
|
|
76
|
+
static int acquire(pid_t p, identity *out, int session) {
|
|
77
|
+
struct uniqinfo a, b; audit_token_t t;
|
|
78
|
+
if (!held || !unique(p, &a)) return 0;
|
|
79
|
+
if (session && getsid(p) != root) return 0;
|
|
80
|
+
if (!token(p, &t) || !unique(p, &b) || a.unique != b.unique || t.val[7] != (uint32_t)b.version) return 0;
|
|
81
|
+
out->pid = p; out->unique = a.unique; return 1;
|
|
82
|
+
}
|
|
83
|
+
/* 0 exited, 1 live, 2 uncertain. Never infer live from a failed task-port lookup. */
|
|
84
|
+
static int status(identity *id) {
|
|
85
|
+
if (id->pid == root) { siginfo_t info = {0}; if (waitid(P_PID, root, &info, WEXITED|WNOHANG|WNOWAIT) == 0 && info.si_pid == root) return 0; }
|
|
86
|
+
struct uniqinfo u; if (!unique(id->pid, &u)) return errno == ESRCH ? 0 : 2;
|
|
87
|
+
if (u.unique != id->unique) return 0;
|
|
88
|
+
struct proc_bsdinfo b;
|
|
89
|
+
if (proc_pidinfo(id->pid, PROC_PIDTBSDINFO, 0, &b, sizeof(b)) != sizeof(b)) return 2;
|
|
90
|
+
struct uniqinfo after; if (!unique(id->pid, &after)) return errno == ESRCH ? 0 : 2;
|
|
91
|
+
if (after.unique != id->unique) return 0;
|
|
92
|
+
return b.pbi_status == 5 /* SZOMB */ ? 0 : 1;
|
|
93
|
+
}
|
|
94
|
+
static void bound_signal(identity *id, int sig) {
|
|
95
|
+
for (int tries = 0; tries < 4; tries++) {
|
|
96
|
+
identity fresh; audit_token_t t; struct uniqinfo u;
|
|
97
|
+
if (!acquire(id->pid, &fresh, 0) || fresh.unique != id->unique || !token(id->pid, &t) || !unique(id->pid, &u) || u.unique != id->unique || t.val[7] != (uint32_t)u.version) continue;
|
|
98
|
+
int r = proc_signal_with_audittoken(&t, sig);
|
|
99
|
+
if (r == 0 || r != ESRCH) return;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
static void remember(pid_t p) {
|
|
103
|
+
identity id;
|
|
104
|
+
if (!acquire(p, &id, 1)) return;
|
|
105
|
+
for (size_t i=0; i<count; i++) if (known[i].unique == id.unique) return;
|
|
106
|
+
if (count == MAX_TRACKED) { scanning_failed = 1; return; }
|
|
107
|
+
known[count++] = id;
|
|
108
|
+
}
|
|
109
|
+
static void discover(void) {
|
|
110
|
+
if (!held) return;
|
|
111
|
+
int bytes = proc_listallpids(NULL, 0);
|
|
112
|
+
if (bytes <= 0 || bytes > 1024*1024) { scanning_failed = 1; return; }
|
|
113
|
+
/* proc_listallpids(NULL) returns estimated process COUNT, not bytes. */
|
|
114
|
+
size_t capacity = (size_t)bytes + 256;
|
|
115
|
+
pid_t *pids = calloc(capacity, sizeof(pid_t));
|
|
116
|
+
if (!pids) { scanning_failed = 1; return; }
|
|
117
|
+
int n = proc_listallpids(pids, (int)(capacity*sizeof(pid_t)));
|
|
118
|
+
if (n < 0 || (size_t)n >= capacity) scanning_failed = 1;
|
|
119
|
+
else for (int i=0; i<n; i++) if (pids[i]>1) remember(pids[i]);
|
|
120
|
+
free(pids);
|
|
121
|
+
}
|
|
122
|
+
static int capability(void) {
|
|
123
|
+
struct uniqinfo a, b; audit_token_t t;
|
|
124
|
+
return unique(getpid(), &a) && token(getpid(), &t) && unique(getpid(), &b) && a.unique == b.unique && t.val[7] == (uint32_t)b.version;
|
|
125
|
+
}
|
|
126
|
+
#else
|
|
127
|
+
static int pid_signal(int fd, int sig) { return (int)syscall(SYS_pidfd_send_signal, fd, sig, NULL, 0); }
|
|
128
|
+
static int proc_stat(int dir, pid_t *sid, char *state) {
|
|
129
|
+
int f = openat(dir, "stat", O_RDONLY|O_CLOEXEC); if (f < 0) return 0;
|
|
130
|
+
char buf[8192]; ssize_t n = read(f, buf, sizeof(buf)-1); int saved=errno; close(f); errno=saved;
|
|
131
|
+
if (n <= 0) { if(n==0) errno=EIO; return 0; } buf[n]=0;
|
|
132
|
+
char *end = strrchr(buf, ')'); int pp, pg, s;
|
|
133
|
+
if (!end || sscanf(end+1, " %c %d %d %d", state, &pp, &pg, &s) != 4) { errno=EIO; return 0; }
|
|
134
|
+
*sid = (pid_t)s; return 1;
|
|
135
|
+
}
|
|
136
|
+
static int acquire(pid_t p, identity *out, int session) {
|
|
137
|
+
if(root_only) { if(p!=root || root_status()==2) return 0; out->pid=root; out->fd=-1; return 1; }
|
|
138
|
+
if (!held) return 0;
|
|
139
|
+
char name[64]; snprintf(name, sizeof(name), "/proc/%d", p);
|
|
140
|
+
int f=open(name, O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW); if (f<0) return 0;
|
|
141
|
+
pid_t sid; char state;
|
|
142
|
+
if (!proc_stat(f, &sid, &state) || (session && sid != root)) { close(f); return 0; }
|
|
143
|
+
out->pid=p; out->fd=f; return 1;
|
|
144
|
+
}
|
|
145
|
+
static int status(identity *id) {
|
|
146
|
+
if(root_only) return id->pid==root ? root_status() : 2;
|
|
147
|
+
pid_t sid; char state;
|
|
148
|
+
if (!proc_stat(id->fd, &sid, &state)) return errno == ENOENT || errno == ESRCH ? 0 : 2;
|
|
149
|
+
return state == 'Z' || state == 'X' ? 0 : 1;
|
|
150
|
+
}
|
|
151
|
+
static void bound_signal(identity *id, int sig) {
|
|
152
|
+
if(root_only) {
|
|
153
|
+
if(id->pid!=root || root_status()!=1) return;
|
|
154
|
+
/* No reap between waitid and kill: root PID remains continuously reserved. */
|
|
155
|
+
int r; do { r=kill(root,sig); } while(r<0 && errno==EINTR);
|
|
156
|
+
if(r<0 && errno!=ESRCH) scanning_failed=1;
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
(void)pid_signal(id->fd, sig);
|
|
160
|
+
}
|
|
161
|
+
static void remember(pid_t p) {
|
|
162
|
+
identity id;
|
|
163
|
+
if (!acquire(p, &id, 1)) return;
|
|
164
|
+
struct stat st, old; if (fstat(id.fd,&st)) { close(id.fd); scanning_failed=1; return; }
|
|
165
|
+
for (size_t i=0;i<count;i++) if (!fstat(known[i].fd,&old) && old.st_dev==st.st_dev && old.st_ino==st.st_ino) { close(id.fd); return; }
|
|
166
|
+
if (count==MAX_TRACKED) { scanning_failed=1; close(id.fd); return; }
|
|
167
|
+
known[count++]=id;
|
|
168
|
+
}
|
|
169
|
+
static void discover(void) {
|
|
170
|
+
if (root_only || !held) return;
|
|
171
|
+
DIR *d=opendir("/proc"); if (!d) { scanning_failed=1; return; }
|
|
172
|
+
struct dirent *e;
|
|
173
|
+
while ((e=readdir(d))) { char *end; long p=strtol(e->d_name,&end,10); if (*e->d_name && !*end && p>1 && p<=INT32_MAX) remember((pid_t)p); }
|
|
174
|
+
closedir(d);
|
|
175
|
+
}
|
|
176
|
+
static int capability(void) {
|
|
177
|
+
compatibility_available=0;
|
|
178
|
+
/* Reject a proc mount in a different PID namespace (including numeric aliases).
|
|
179
|
+
* The mount must be kernel procfs; /proc/self must report our local PID and SID. */
|
|
180
|
+
int self=open("/proc/self",O_RDONLY|O_DIRECTORY|O_CLOEXEC);
|
|
181
|
+
if(self<0) return 0;
|
|
182
|
+
struct statfs fs; pid_t sid; char state;
|
|
183
|
+
int statfd=openat(self,"stat",O_RDONLY|O_CLOEXEC); char buf[128]={0};
|
|
184
|
+
ssize_t n=statfd<0?-1:read(statfd,buf,sizeof(buf)-1);
|
|
185
|
+
if(statfd>=0) close(statfd);
|
|
186
|
+
/* NSpid lists PIDs from the procfs PID namespace down to ours: exactly one field
|
|
187
|
+
* proves this procfs is our active namespace (ancestor procfs => more fields;
|
|
188
|
+
* unrelated procfs => no /proc/self). Needs no access to PID1; missing => deny. */
|
|
189
|
+
int nspid_ok=0; int statusfd=openat(self,"status",O_RDONLY|O_CLOEXEC);
|
|
190
|
+
if(statusfd>=0) {
|
|
191
|
+
static char st[16384]; size_t len=0; ssize_t k;
|
|
192
|
+
while(len<sizeof(st)-1 && ((k=read(statusfd,st+len,sizeof(st)-1-len))>0 || (k<0 && errno==EINTR))) if(k>0) len+=(size_t)k;
|
|
193
|
+
close(statusfd); st[len]=0;
|
|
194
|
+
char *line=strstr(st,"\nNSpid:");
|
|
195
|
+
if(line && len<sizeof(st)-1) {
|
|
196
|
+
line+=7; char *eol=strchr(line,'\n');
|
|
197
|
+
if(eol) { *eol=0; int fields=0; long v=0; char *q=line, *end;
|
|
198
|
+
for(;;) { while(*q==' '||*q=='\t') q++; if(!*q) break; errno=0; long x=strtol(q,&end,10); if(end==q||errno||(*end&&*end!=' '&&*end!='\t')) { fields=-1; break; } v=x; fields++; q=end; }
|
|
199
|
+
nspid_ok=fields==1 && v==getpid(); }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
char link[32]; ssize_t ln=readlink("/proc/self",link,sizeof(link)-1);
|
|
203
|
+
int link_ok=ln>0 && (link[ln]=0, strtol(link,NULL,10)==getpid());
|
|
204
|
+
int namespace_ok=nspid_ok && link_ok && n>0 && strtol(buf,NULL,10)==getpid() && !fstatfs(self,&fs) && fs.f_type==PROC_SUPER_MAGIC && proc_stat(self,&sid,&state) && sid==getsid(0);
|
|
205
|
+
close(self); if(!namespace_ok) return 0;
|
|
206
|
+
identity id; pid_t saved=root; root=getsid(0);
|
|
207
|
+
int ok=acquire(getpid(), &id, 1); root=saved;
|
|
208
|
+
if (!ok) return 0;
|
|
209
|
+
int r=pid_signal(id.fd, 0); close(id.fd);
|
|
210
|
+
return r==0;
|
|
211
|
+
}
|
|
212
|
+
#endif
|
|
213
|
+
static void signal_all(int sig) { for (size_t i=0;i<count;i++) if (status(&known[i]) != 0) bound_signal(&known[i], sig); }
|
|
214
|
+
static void nonblock(int f) { int flags=fcntl(f,F_GETFL); if(flags>=0) fcntl(f,F_SETFL,flags|O_NONBLOCK); }
|
|
215
|
+
static void close_extra(void) {
|
|
216
|
+
#ifdef __APPLE__
|
|
217
|
+
int n = getdtablesize();
|
|
218
|
+
for(int i=3;i<n;i++) close(i);
|
|
219
|
+
#else
|
|
220
|
+
long n=sysconf(_SC_OPEN_MAX); if(n<0) n=65536;
|
|
221
|
+
for(int i=3;i<n;i++) close(i);
|
|
222
|
+
#endif
|
|
223
|
+
}
|
|
224
|
+
/* Startup failure owns the unreaped root but must never wait indefinitely.
|
|
225
|
+
* Gate EOF prevents exec. All optional signals still use a verified identity. */
|
|
226
|
+
static int abort_start(int master, int gate) {
|
|
227
|
+
close(gate);
|
|
228
|
+
identity id;
|
|
229
|
+
if(acquire(root,&id,0)) {
|
|
230
|
+
bound_signal(&id,SIGKILL);
|
|
231
|
+
#ifndef __APPLE__
|
|
232
|
+
if(id.fd>=0) close(id.fd);
|
|
233
|
+
#endif
|
|
234
|
+
}
|
|
235
|
+
long long deadline=clock_ms()+250; int reaped=0;
|
|
236
|
+
do {
|
|
237
|
+
siginfo_t info={0};
|
|
238
|
+
if(waitid(P_PID,root,&info,WEXITED|WNOHANG|WNOWAIT)==0 && info.si_pid==root) { int r; do { r=waitpid(root,NULL,WNOHANG); } while(r<0 && errno==EINTR); reaped=r==root; break; }
|
|
239
|
+
usleep(1000);
|
|
240
|
+
} while(clock_ms()<deadline);
|
|
241
|
+
held=0; close(master);
|
|
242
|
+
event("{\"error\":\"native_identity_unavailable\"}\n");
|
|
243
|
+
char message[160]; snprintf(message,sizeof(message),"{\"cleanup\":true,\"observed\":1,\"live\":0,\"uncertain\":%d}\n",reaped?0:1); event(message);
|
|
244
|
+
return 78;
|
|
245
|
+
}
|
|
246
|
+
/* A termination signal (e.g. one sent to the daemon's process group) must start
|
|
247
|
+
* bound cleanup, not kill the owner before it reaps the session it owns. */
|
|
248
|
+
static volatile sig_atomic_t stop_requested=0;
|
|
249
|
+
static void request_stop(int sig) { (void)sig; stop_requested=1; }
|
|
250
|
+
int main(int argc, char **argv) {
|
|
251
|
+
signal(SIGPIPE,SIG_IGN);
|
|
252
|
+
struct sigaction stop_action; memset(&stop_action,0,sizeof(stop_action));
|
|
253
|
+
stop_action.sa_handler=request_stop; sigemptyset(&stop_action.sa_mask);
|
|
254
|
+
if(sigaction(SIGTERM,&stop_action,NULL) || sigaction(SIGINT,&stop_action,NULL) || sigaction(SIGHUP,&stop_action,NULL)) return 71;
|
|
255
|
+
struct sigaction child_action; memset(&child_action,0,sizeof(child_action));
|
|
256
|
+
child_action.sa_handler=SIG_DFL; sigemptyset(&child_action.sa_mask);
|
|
257
|
+
if(sigaction(SIGCHLD,&child_action,NULL)) return 71;
|
|
258
|
+
int capable=capability();
|
|
259
|
+
#ifndef __APPLE__
|
|
260
|
+
/* Linux is best-effort (user decision 2026-10-29): when identity-bound protection is
|
|
261
|
+
* unavailable for any reason, offer root-only compatibility, which only signals the
|
|
262
|
+
* unreaped session root and never trusts procfs or pidfd. The caller discloses it. */
|
|
263
|
+
compatibility_available=!capable;
|
|
264
|
+
#endif
|
|
265
|
+
#ifndef __APPLE__
|
|
266
|
+
if(argc==2 && !strcmp(argv[1],"--capability") && compatibility_available) { puts("alp-terminal-owner:1:root-only"); return 0; }
|
|
267
|
+
if(argc>1 && !strcmp(argv[1],"--root-only")) { root_only=1; argc--; argv++; }
|
|
268
|
+
if(argc>=6 && ((root_only && !compatibility_available) || (!root_only && !capable && compatibility_available))) {
|
|
269
|
+
event(!root_only ? "{\"refused\":\"terminal_protection_ack_required\"}\n" : "{\"refused\":\"terminal_unsupported\"}\n");
|
|
270
|
+
event("{\"cleanup\":true,\"observed\":0,\"live\":0,\"uncertain\":0}\n"); return 78;
|
|
271
|
+
}
|
|
272
|
+
#endif
|
|
273
|
+
if (argc==2 && !strcmp(argv[1],"--capability")) { if (!capable) return 78; puts("alp-terminal-owner:1"); return 0; }
|
|
274
|
+
if (argc<6 || (!capable
|
|
275
|
+
#ifndef __APPLE__
|
|
276
|
+
&& !(root_only && compatibility_available)
|
|
277
|
+
#endif
|
|
278
|
+
)) { event("{\"refused\":\"terminal_unsupported\"}\n"); event("{\"cleanup\":true,\"observed\":0,\"live\":0,\"uncertain\":0}\n"); return 78; }
|
|
279
|
+
int cols=atoi(argv[1]),rows=atoi(argv[2]),grace=atoi(argv[3]);
|
|
280
|
+
if(cols<1 || cols>1000 || rows<1 || rows>1000 || grace<0 || grace>10000) return 64;
|
|
281
|
+
unsigned char *out=malloc(QUEUE),*input=malloc(QUEUE);
|
|
282
|
+
if(!out || !input) { free(out); free(input); return 71; }
|
|
283
|
+
int gate[2],started[2]; if(pipe(gate)||pipe(started)) return 71;
|
|
284
|
+
struct winsize ws={.ws_col=(unsigned short)cols,.ws_row=(unsigned short)rows}; int master;
|
|
285
|
+
root=forkpty(&master,NULL,NULL,&ws);
|
|
286
|
+
if (root<0) return 71;
|
|
287
|
+
if (!root) {
|
|
288
|
+
/* The owner's stop handlers must not swallow a hang-up before exec. */
|
|
289
|
+
signal(SIGTERM,SIG_DFL); signal(SIGINT,SIG_DFL); signal(SIGHUP,SIG_DFL);
|
|
290
|
+
close(gate[1]); close(started[0]);
|
|
291
|
+
char ready=getsid(0)==getpid()?'S':'E';
|
|
292
|
+
if(write(started[1],&ready,1)!=1) _exit(126);
|
|
293
|
+
char release=0; if(read(gate[0],&release,1)!=1 || release!='G' || ready!='S') _exit(126);
|
|
294
|
+
close_extra(); signal(SIGPIPE,SIG_DFL);
|
|
295
|
+
if(chdir(argv[4])) _exit(126);
|
|
296
|
+
execv(argv[5],&argv[5]); _exit(127);
|
|
297
|
+
}
|
|
298
|
+
close(gate[0]); close(started[1]); char ready=0;
|
|
299
|
+
struct pollfd startup[3]={{started[0],POLLIN,0},{0,0,0},{4,POLLIN,0}};
|
|
300
|
+
int available=poll(startup,3,START_TIMEOUT_MS);
|
|
301
|
+
int startok=available>0 && !(startup[1].revents&(POLLHUP|POLLERR)) && !(startup[2].revents&(POLLIN|POLLHUP|POLLERR)) && (startup[0].revents&POLLIN) && read(started[0],&ready,1)==1 && ready=='S';
|
|
302
|
+
close(started[0]);
|
|
303
|
+
identity first;
|
|
304
|
+
if(!startok || !acquire(root,&first,1)) return abort_start(master,gate[1]);
|
|
305
|
+
known[count++]=first;
|
|
306
|
+
if(write(gate[1],"G",1)!=1) return abort_start(master,gate[1]);
|
|
307
|
+
close(gate[1]);
|
|
308
|
+
char msg[256]; snprintf(msg,sizeof(msg),"{\"ready\":%d,\"protocol\":1}\n",root); event(msg);
|
|
309
|
+
nonblock(master); nonblock(0); nonblock(1); nonblock(4);
|
|
310
|
+
size_t outn=0,inn=0; char commands[256]; size_t cn=0;
|
|
311
|
+
int cleaning=0, root_notified=0, code=0, sig=0, io_failed=0; long long start=0, lastscan=0;
|
|
312
|
+
for (;;) {
|
|
313
|
+
long long now=clock_ms();
|
|
314
|
+
if(now-lastscan>=20) { discover(); lastscan=now; }
|
|
315
|
+
siginfo_t info={0};
|
|
316
|
+
if(!root_notified && waitid(P_PID,root,&info,WEXITED|WNOHANG|WNOWAIT)==0 && info.si_pid==root) {
|
|
317
|
+
root_notified=1; code=info.si_code==CLD_EXITED?info.si_status:0; sig=info.si_code==CLD_EXITED?0:info.si_status;
|
|
318
|
+
snprintf(msg,sizeof(msg),"{\"exitCode\":%d,\"signal\":%d}\n",code,sig); event(msg); cleaning=cleaning?cleaning:1;
|
|
319
|
+
}
|
|
320
|
+
if((io_failed || stop_requested) && !cleaning) cleaning=1;
|
|
321
|
+
if(cleaning==1) { start=now; discover(); signal_all(SIGHUP); cleaning=2; }
|
|
322
|
+
if(cleaning>=2 && now-start>=grace) { discover(); signal_all(SIGKILL); cleaning=3; }
|
|
323
|
+
if(cleaning==3 && now-start>=grace+250) break;
|
|
324
|
+
struct pollfd fds[4]={{0,inn<QUEUE?POLLIN:0,0},{master,(short)((outn<QUEUE?POLLIN:0)|(inn?POLLOUT:0)),0},{1,outn?POLLOUT:0,0},{4,POLLIN,0}};
|
|
325
|
+
if(poll(fds,4,10)<0 && errno!=EINTR) { io_failed=1; continue; }
|
|
326
|
+
if(fds[0].revents&POLLIN) { ssize_t n=read(0,input+inn,QUEUE-inn); if(n>0) inn+=(size_t)n; else if(n==0) cleaning=cleaning?cleaning:1; }
|
|
327
|
+
if(fds[0].revents&(POLLHUP|POLLERR)) cleaning=cleaning?cleaning:1;
|
|
328
|
+
if(fds[1].revents&POLLIN) { ssize_t n=read(master,out+outn,QUEUE-outn); if(n>0) outn+=(size_t)n; }
|
|
329
|
+
if(fds[1].revents&POLLOUT) { ssize_t n=write(master,input,inn); if(n>0) {inn-=(size_t)n;memmove(input,input+n,inn);} }
|
|
330
|
+
if(fds[2].revents&POLLOUT) { ssize_t n=write(1,out,outn); if(n>0) {outn-=(size_t)n;memmove(out,out+n,outn);} else if(errno!=EAGAIN&&errno!=EINTR) io_failed=1; }
|
|
331
|
+
if(fds[2].revents&(POLLHUP|POLLERR)) io_failed=1;
|
|
332
|
+
if(fds[3].revents&POLLIN) {
|
|
333
|
+
char b[128]; ssize_t n=read(4,b,sizeof(b));
|
|
334
|
+
for(ssize_t i=0;i<n;i++) { if(b[i]=='\n') { commands[cn]=0; int c,r; if(!strcmp(commands,"C")) cleaning=cleaning?cleaning:1; else if(sscanf(commands,"R %d %d",&c,&r)==2 && c>0&&c<=1000&&r>0&&r<=1000) { ws.ws_col=(unsigned short)c;ws.ws_row=(unsigned short)r; ioctl(master,TIOCSWINSZ,&ws); } cn=0; } else if(cn<sizeof(commands)-1) commands[cn++]=b[i]; else {io_failed=1;cn=0;} }
|
|
335
|
+
}
|
|
336
|
+
if(fds[3].revents&(POLLHUP|POLLERR)) cleaning=cleaning?cleaning:1;
|
|
337
|
+
}
|
|
338
|
+
/* Last scan and verification happen BEFORE final root reap: SID still reserved. */
|
|
339
|
+
discover(); signal_all(SIGKILL); usleep(20000);
|
|
340
|
+
int live=0,uncertain=scanning_failed;
|
|
341
|
+
for(size_t i=0;i<count;i++) { int s=status(&known[i]); if(s==1) live++; else if(s==2) uncertain++; }
|
|
342
|
+
siginfo_t final={0};
|
|
343
|
+
if(waitid(P_PID,root,&final,WEXITED|WNOHANG|WNOWAIT)==0 && final.si_pid==root) {
|
|
344
|
+
int reaped; do { reaped=waitpid(root,NULL,WNOHANG); } while(reaped<0 && errno==EINTR);
|
|
345
|
+
if(reaped!=root) uncertain++;
|
|
346
|
+
held=0;
|
|
347
|
+
} else { /* Never blocking reap of a live/unverifiable root; no adoption after this point. */
|
|
348
|
+
held=0; uncertain++;
|
|
349
|
+
}
|
|
350
|
+
/* Drain all remaining PTY output and queued bytes, advancing partial writes.
|
|
351
|
+
* A stalled consumer cannot retain an owner indefinitely: undrained output is
|
|
352
|
+
* explicit uncertainty, NEVER a successful silent tail discard. No discovery
|
|
353
|
+
* or signals occur after final root reap above. */
|
|
354
|
+
long long drain_deadline=clock_ms()+1000; int master_eof=0;
|
|
355
|
+
while((!master_eof || outn) && clock_ms()<drain_deadline) {
|
|
356
|
+
struct pollfd drain[2]={{master,(!master_eof && outn<QUEUE)?POLLIN:0,0},{1,outn?POLLOUT:0,0}};
|
|
357
|
+
if(poll(drain,2,10)<0) { if(errno==EINTR) continue; io_failed=1; break; }
|
|
358
|
+
if(!master_eof && outn<QUEUE && (drain[0].revents&(POLLIN|POLLHUP|POLLERR))) {
|
|
359
|
+
ssize_t n=read(master,out+outn,QUEUE-outn);
|
|
360
|
+
if(n>0) outn+=(size_t)n;
|
|
361
|
+
else if(n==0 || errno==EIO) master_eof=1;
|
|
362
|
+
else if(errno!=EAGAIN && errno!=EINTR) { io_failed=1; master_eof=1; }
|
|
363
|
+
}
|
|
364
|
+
if(outn && (drain[1].revents&POLLOUT)) {
|
|
365
|
+
ssize_t n=write(1,out,outn);
|
|
366
|
+
if(n>0) { outn-=(size_t)n; memmove(out,out+n,outn); }
|
|
367
|
+
else if(errno!=EAGAIN && errno!=EINTR) { io_failed=1; break; }
|
|
368
|
+
}
|
|
369
|
+
if(drain[1].revents&(POLLHUP|POLLERR)) { io_failed=1; break; }
|
|
370
|
+
}
|
|
371
|
+
int limited_coverage=0;
|
|
372
|
+
#ifndef __APPLE__
|
|
373
|
+
limited_coverage=root_only;
|
|
374
|
+
#endif
|
|
375
|
+
/* An unmanaged descendant may retain the PTY indefinitely. Report this known
|
|
376
|
+
* coverage limit separately. Queued/lost bytes and adapter faults still fail. */
|
|
377
|
+
if(outn || (!master_eof && !limited_coverage)) io_failed=1;
|
|
378
|
+
close(master);
|
|
379
|
+
uncertain+=io_failed;
|
|
380
|
+
const char *coverage="";
|
|
381
|
+
#ifndef __APPLE__
|
|
382
|
+
if(root_only) coverage=master_eof ? ",\"coverage\":\"root-only\",\"outputOpen\":false" : ",\"coverage\":\"root-only\",\"outputOpen\":true";
|
|
383
|
+
#endif
|
|
384
|
+
snprintf(msg,sizeof(msg),"{\"cleanup\":true,\"observed\":%zu,\"live\":%d,\"uncertain\":%d%s}\n",count,live,uncertain,coverage); event(msg);
|
|
385
|
+
#ifndef __APPLE__
|
|
386
|
+
for(size_t i=0;i<count;i++) if(known[i].fd>=0) close(known[i].fd);
|
|
387
|
+
#endif
|
|
388
|
+
free(out);free(input); return live||uncertain?2:0;
|
|
389
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-daemon",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP daemon module",
|
|
6
6
|
"files": [
|
|
7
7
|
"src",
|
|
8
8
|
"dist",
|
|
9
|
-
"NOTICE"
|
|
9
|
+
"NOTICE",
|
|
10
|
+
"native/terminal-owner.c",
|
|
11
|
+
"native/README.md",
|
|
12
|
+
"native/prebuilt"
|
|
10
13
|
],
|
|
11
14
|
"exports": {
|
|
12
15
|
"./index": {
|
|
@@ -126,14 +129,15 @@
|
|
|
126
129
|
"node": ">=22.12"
|
|
127
130
|
},
|
|
128
131
|
"dependencies": {
|
|
129
|
-
"@anhlp/alp-core": "0.0.1-beta.
|
|
130
|
-
"@anhlp/alp-runtime": "0.0.1-beta.
|
|
131
|
-
"@anhlp/alp-client": "0.0.1-beta.
|
|
132
|
-
"@anhlp/alp-protocol": "0.0.1-beta.
|
|
132
|
+
"@anhlp/alp-core": "0.0.1-beta.6",
|
|
133
|
+
"@anhlp/alp-runtime": "0.0.1-beta.6",
|
|
134
|
+
"@anhlp/alp-client": "0.0.1-beta.6",
|
|
135
|
+
"@anhlp/alp-protocol": "0.0.1-beta.6",
|
|
133
136
|
"@anthropic-ai/sdk": "^0.131.0",
|
|
134
137
|
"ws": "^8.22.0",
|
|
135
138
|
"zod": "4.4.3",
|
|
136
|
-
"@anthropic-ai/claude-agent-sdk": "^0.3.292"
|
|
139
|
+
"@anthropic-ai/claude-agent-sdk": "^0.3.292",
|
|
140
|
+
"@xterm/headless": "6.0.0"
|
|
137
141
|
},
|
|
138
142
|
"scripts": {
|
|
139
143
|
"build": "node ../../scripts/build-workspace.mjs daemon",
|
package/src/attachments.ts
CHANGED
|
@@ -186,6 +186,16 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
186
186
|
/** Begins in flight by request key, so a repeat waits for the first. */
|
|
187
187
|
const beginning = new Map<string, Promise<unknown>>();
|
|
188
188
|
const queues = new Map<string, Promise<unknown>>();
|
|
189
|
+
// Track complete public operations, including awaits before their first queue entry.
|
|
190
|
+
const pending = new Set<Promise<unknown>>();
|
|
191
|
+
function admitted<A extends unknown[], R>(run: (...args: A) => Promise<R>) {
|
|
192
|
+
return async (...args: A): Promise<R> => {
|
|
193
|
+
usable();
|
|
194
|
+
const operation = run(...args);
|
|
195
|
+
pending.add(operation);
|
|
196
|
+
try { return await operation; } finally { pending.delete(operation); }
|
|
197
|
+
};
|
|
198
|
+
}
|
|
189
199
|
let failure: Error | undefined;
|
|
190
200
|
let sweeper: NodeJS.Timeout | undefined;
|
|
191
201
|
/** Referenced object directories whose meta could not be read (logged once). */
|
|
@@ -296,6 +306,7 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
296
306
|
}
|
|
297
307
|
|
|
298
308
|
function usable() {
|
|
309
|
+
if (closed) throw unavailable('attachment_unavailable', 'alpd attachment store is closed');
|
|
299
310
|
if (failure) throw unavailable('attachment_unavailable', 'alpd cannot use its attachment store; its log says why');
|
|
300
311
|
}
|
|
301
312
|
|
|
@@ -337,7 +348,7 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
337
348
|
|
|
338
349
|
/** Collects expired uploads, unreferenced objects past their retention and leftovers of a crash. */
|
|
339
350
|
async function sweep() {
|
|
340
|
-
if (failure) return;
|
|
351
|
+
if (failure || closed) return;
|
|
341
352
|
await withRefs(async () => {
|
|
342
353
|
const at = now();
|
|
343
354
|
const released = { ...refs.released };
|
|
@@ -438,7 +449,7 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
438
449
|
if (options.sweepMs !== 0) {
|
|
439
450
|
void recovered.then(() => {
|
|
440
451
|
if (closed || failure) return;
|
|
441
|
-
sweeper = setInterval(() => void sweep().catch(error => log?.warn('attachment collection failed', { code: 'ALPD_ATTACHMENT_SWEEP_FAILED', error })), options.sweepMs ?? Math.min(15 * 60 * 1000, Math.max(1000, Math.floor(limits.uploadTimeoutMs / 4))));
|
|
452
|
+
sweeper = setInterval(() => void admitted(sweep)().catch(error => log?.warn('attachment collection failed', { code: 'ALPD_ATTACHMENT_SWEEP_FAILED', error })), options.sweepMs ?? Math.min(15 * 60 * 1000, Math.max(1000, Math.floor(limits.uploadTimeoutMs / 4))));
|
|
442
453
|
sweeper.unref();
|
|
443
454
|
});
|
|
444
455
|
}
|
|
@@ -465,7 +476,7 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
465
476
|
}
|
|
466
477
|
}
|
|
467
478
|
|
|
468
|
-
|
|
479
|
+
const api = {
|
|
469
480
|
/** Effective limits, advertised in daemon.hello. */
|
|
470
481
|
limits,
|
|
471
482
|
/** Settles when start-up recovery is done (or failed: the methods then answer 1005). */
|
|
@@ -499,8 +510,8 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
499
510
|
}
|
|
500
511
|
// Reserved here, before anything awaits: concurrent begins see each other's reservation.
|
|
501
512
|
const at = now();
|
|
502
|
-
// Expired uploads release their reservation now, and so do this principal's uploads of
|
|
503
|
-
//
|
|
513
|
+
// Expired uploads release their reservation now, and so do this principal's uploads of
|
|
514
|
+
// another grant epoch (a reissued credential): nobody can continue or abort those any more.
|
|
504
515
|
// Their files go after any call on them.
|
|
505
516
|
for (const meta of [...objects.values()]) {
|
|
506
517
|
if (meta.state !== 'uploading') continue;
|
|
@@ -715,7 +726,8 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
715
726
|
/**
|
|
716
727
|
* Pins `attachmentIds` for `holder` durably (a prompt's receipt key; t-15b0.4's fork adds the
|
|
717
728
|
* new session's holder the same way after re-authorizing the source's attachments for it). Each
|
|
718
|
-
* must still be committed; a write failure pins nothing.
|
|
729
|
+
* must still be committed; a write failure pins nothing. If interrupted by crash before the receipt
|
|
730
|
+
* is written, the pin is held conservatively until session cleanup (releaseSessions).
|
|
719
731
|
*/
|
|
720
732
|
async pin(holder: string, sessionId: string, attachmentIds: string[], kind = 'prompt') {
|
|
721
733
|
await recovered; usable();
|
|
@@ -811,7 +823,7 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
811
823
|
const meta = id ? objects.get(id) : undefined;
|
|
812
824
|
if (!meta || meta.state !== 'committed' || !Object.values(refs.holders).some(holder => holder.sessionId === sessionId && holder.attachments.includes(meta.id))) throw notFound('attachment');
|
|
813
825
|
const { handle, info: stat } = await openPayload(meta, OPEN_READ);
|
|
814
|
-
if (stat.size !== meta.size) { await handle.close(); throw unavailable('attachment_unavailable', 'The attachment\'s bytes changed'); }
|
|
826
|
+
if (stat.size !== meta.size) { await handle.close(); throw unavailable('attachment_unavailable', 'The attachment\'s bytes changed', { attachmentId: `att_${meta.id}` }); }
|
|
815
827
|
const hash = createHash('sha256');
|
|
816
828
|
const stream = handle.createReadStream({ start: 0, ...(meta.size ? { end: meta.size - 1 } : {}), autoClose: true });
|
|
817
829
|
const verified = stream.pipe(new Transform({
|
|
@@ -828,7 +840,33 @@ export function createAttachmentStore(options: AttachmentStoreOptions) {
|
|
|
828
840
|
/** The holders of the reference index, for tests. */
|
|
829
841
|
holders: () => structuredClone(refs.holders),
|
|
830
842
|
|
|
831
|
-
close() {
|
|
843
|
+
async close() {
|
|
844
|
+
closed = true;
|
|
845
|
+
if (sweeper) {
|
|
846
|
+
clearInterval(sweeper);
|
|
847
|
+
sweeper = undefined;
|
|
848
|
+
}
|
|
849
|
+
await recovered;
|
|
850
|
+
await Promise.allSettled([...pending]);
|
|
851
|
+
await Promise.allSettled([...queues.values()]);
|
|
852
|
+
},
|
|
853
|
+
};
|
|
854
|
+
return {
|
|
855
|
+
...api,
|
|
856
|
+
sweep: admitted(api.sweep),
|
|
857
|
+
begin: admitted(api.begin),
|
|
858
|
+
chunk: admitted(api.chunk),
|
|
859
|
+
commit: admitted(api.commit),
|
|
860
|
+
abort: admitted(api.abort),
|
|
861
|
+
get: admitted(api.get),
|
|
862
|
+
remove: admitted(api.remove),
|
|
863
|
+
resolve: admitted(api.resolve),
|
|
864
|
+
pin: admitted(api.pin),
|
|
865
|
+
heldBy: admitted(api.heldBy),
|
|
866
|
+
authorize: admitted(api.authorize),
|
|
867
|
+
release: admitted(api.release),
|
|
868
|
+
releaseSessions: admitted(api.releaseSessions),
|
|
869
|
+
reader: { ...api.reader, open: admitted(api.reader.open) },
|
|
832
870
|
};
|
|
833
871
|
}
|
|
834
872
|
|
package/src/conversation.ts
CHANGED
|
@@ -165,6 +165,7 @@ function configureRefusal(error: any) {
|
|
|
165
165
|
export function createConversation(ctx: ConversationContext) {
|
|
166
166
|
const { runtime, store, journal, records } = ctx;
|
|
167
167
|
const lifecycle = createLifecycle(journal, { crashPoint: ctx.crashPoint, completed });
|
|
168
|
+
const reservedForkIds = new Set<string>();
|
|
168
169
|
|
|
169
170
|
async function completed(entry: LifecycleEntry) {
|
|
170
171
|
if (entry.state !== 'applied') return undefined;
|
|
@@ -589,6 +590,7 @@ export function createConversation(ctx: ConversationContext) {
|
|
|
589
590
|
// reopen or wake may land in between (released when it answers).
|
|
590
591
|
let release: (() => void) | undefined;
|
|
591
592
|
let releaseWakes: (() => void) | undefined;
|
|
593
|
+
let reservedId: string | undefined;
|
|
592
594
|
try {
|
|
593
595
|
const { result, duplicate } = await lifecycle.run<ForkPlan, NativeBinding, RpcMethodMap['session.fork']['result']>(
|
|
594
596
|
{ resource: sessionId, operation: 'fork', requestId, fingerprint }, {
|
|
@@ -639,8 +641,19 @@ export function createConversation(ctx: ConversationContext) {
|
|
|
639
641
|
}
|
|
640
642
|
const latestTurn = turns.at(-1)?.id;
|
|
641
643
|
const cutoff: ForkPlan['cutoff'] = kind === 'through' ? { throughTurnId: turnId! } : kind === 'before' ? { beforeTurnId: turnId! } : latestTurn ? { throughTurnId: latestTurn } : undefined;
|
|
642
|
-
|
|
643
|
-
|
|
644
|
+
// A restart loses the in-memory reservations. Unfinished native attempts still
|
|
645
|
+
// own their targets, even when no target record was durably written yet.
|
|
646
|
+
const pendingIds = new Set((await journal.list())
|
|
647
|
+
.filter(entry => entry.operation === 'fork' && ['prepared', 'applied', 'unknown'].includes(entry.state))
|
|
648
|
+
.map(entry => (entry.plan as ForkPlan).newSessionId));
|
|
649
|
+
let id = newSessionId;
|
|
650
|
+
if (id !== undefined) {
|
|
651
|
+
if (records.has(id) || runtime.snapshot(id) || reservedForkIds.has(id) || pendingIds.has(id)) throw new RpcError(ERROR.conflict, `Session ${id} already exists`, { reason: 'request_conflict' });
|
|
652
|
+
} else {
|
|
653
|
+
do { id = `ses_${randomBytes(8).toString('hex')}`; } while (records.has(id) || runtime.snapshot(id) || reservedForkIds.has(id) || pendingIds.has(id));
|
|
654
|
+
}
|
|
655
|
+
reservedForkIds.add(id);
|
|
656
|
+
reservedId = id;
|
|
644
657
|
const cwd = await destinationOf(record, workspaceId);
|
|
645
658
|
const attachmentIds = await reauthorize(sessionId, log, cut, principal);
|
|
646
659
|
// Last, after every read of prepare: held mail may wait; a turn that began anyway may not.
|
|
@@ -665,6 +678,12 @@ export function createConversation(ctx: ConversationContext) {
|
|
|
665
678
|
});
|
|
666
679
|
return { ...result, ...(duplicate ? { duplicate: true as const } : {}) };
|
|
667
680
|
} finally {
|
|
681
|
+
if (reservedId && !records.has(reservedId)) {
|
|
682
|
+
// A failed commit or unknown native outcome must keep ownership for retry.
|
|
683
|
+
// A refusal (or preparation failure before journaling) changed nothing.
|
|
684
|
+
const entry = await journal.get(sessionId, 'fork', requestId).catch(() => ({ state: 'unknown' }));
|
|
685
|
+
if (!entry || entry.state === 'failed') reservedForkIds.delete(reservedId);
|
|
686
|
+
}
|
|
668
687
|
releaseWakes?.();
|
|
669
688
|
release?.();
|
|
670
689
|
}
|
|
@@ -763,6 +782,7 @@ export function createConversation(ctx: ConversationContext) {
|
|
|
763
782
|
await store.put(record);
|
|
764
783
|
records.set(record.id, record);
|
|
765
784
|
}
|
|
785
|
+
reservedForkIds.delete(plan.newSessionId);
|
|
766
786
|
await place(plan, entry.key);
|
|
767
787
|
if (plan.attachmentIds.length) await ctx.attachments?.pin(`fork:${plan.newSessionId}`, plan.newSessionId, plan.attachmentIds, 'fork');
|
|
768
788
|
const result = { session: ctx.summary(plan.newSessionId)!, forkedFrom };
|