Repository navigation
Expand file tree
/
Copy pathchild.c
More file actions
824 lines (762 loc) · 28.9 KB
/
Copy pathchild.c
File metadata and controls
824 lines (762 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
/* child.c - child agents. A delegate is a second haid spawned by this
* one: its own address and Maildir (<mailbox>/<name>: the inbox in
* new/, its sessions as threads in cur/), the same tools, nobody to
* ask. The task goes to
* it by mail and the report comes back by mail into the parent's
* inbox, so the whole exchange is on disk and searchable. Names are
* the model's: the same name again continues that child's
* conversation. Children delegate too, down to child_maxdepth levels,
* and the names say who spawned whom: research@hai's scout is
* research.scout@hai. A child dies with its parent (PDEATHSIG) or when
* the parent starts a new conversation. A terminal agent
* (child_attend) is the same thing started for the user in a
* directory: named after it, reached over its own socket
* (child_sock), and kept across the parent's new conversations. A
* standing agent (child_service) is one more step: kept like that,
* and brought back by the parent's loop (child_exit, child_ensure)
* when it dies, on the conversation it was in.
*
* Only the root (the main haid) gives leave to start an agent. A
* parent asks it for a ticket (child_askroot: `fork ADDR` on the
* root's socket, `ok TICKET` back; the root issues itself one), forks
* the child itself with the ticket in HAI_TICKET, and the newborn's
* first act is to present it to the root (`born ADDR TICKET`), which
* checks the ticket and that the newborn's parent process is the
* agent that asked. The root keeps the registry: every agent alive,
* its parent and pid (child_ticket, child_born, child_gone,
* child_agents), and a haid started any other way dies at once. The
* processes stay with their real parents - PDEATHSIG, the reaper,
* `new` and the respawn are theirs. Knows nothing about the loop or
* the socket; the daemon points it at the mailbox and the root. */
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "hai.h"
#include "stb_ds.h"
const char *child_exe; /* NULL = this binary */
const char *child_box = ""; /* the Maildir root, absolute */
const char *child_root = ""; /* the parent's session root mid */
int child_wait = 600; /* seconds a delegate waits for the report;
0 = never: every report is an inbox turn */
int child_depth; /* 0 = the main haid, 1 = its child, ... */
int child_maxdepth = 3; /* levels of children below the main haid */
const char *child_model; /* what children run on; NULL = the same */
char *(*child_askroot)(const char *line); /* one line to the root, its
reply back; NULL = we are it */
/* room for the standing agents of hai.conf (mail and the roles of a
* company, say) and still for the delegates of a job */
#define MAXCHILDREN 16
/* a standing agent that dies is brought back: hai.conf, not a supervisor,
* keeps it now (RESPAWN_TRIES attempts, RESPAWN_DELAY seconds apart,
* then it is left down and `hai status` says so); one that stayed up
* for RESPAWN_WELL seconds and then fell over counts as a fresh crash */
#define RESPAWN_TRIES 5
#define RESPAWN_DELAY 5
#define RESPAWN_WELL 60
typedef struct {
char name[64];
char addr[256]; /* [our name.]name@domain */
char root[160]; /* its conversation: the first task's mid */
char last[160]; /* the last report's mid */
char proot[160]; /* the session of ours that conversation serves */
char dir[4096]; /* where it works; "" = the home directory */
char model[128]; /* what it runs on; "" = the same as ours */
pid_t pid; /* -1 = exited */
int attended; /* started for a terminal in dir, not by delegate */
int service; /* a standing agent from hai.conf (child_service) */
int autonomous; /* spawn it this way again (a service) */
int tries; /* times it has been brought back since it was well */
int down; /* brought back too often: left alone now */
int reported; /* the daemon has said so */
time_t started; /* when the live one was spawned */
time_t died; /* when it was seen to be gone */
} Child;
static Child *children; /* stb_ds */
/* the root's registry: every agent alive (pid) and the tickets out
* (pid 0, by = the parent that asked, t = when) */
typedef struct {
char addr[256];
char parent[256];
char ticket[24];
pid_t by;
pid_t pid;
time_t t;
} Reg;
static Reg *registry; /* stb_ds */
#define TICKET_LIFE 60 /* seconds a ticket waits for its newborn */
static char *fmt(const char *f, const char *a, const char *b) {
size_t n = strlen(f) + (a ? strlen(a) : 0) + (b ? strlen(b) : 0) + 1;
char *s = malloc(n);
snprintf(s, n, f, a ? a : "", b ? b : "");
return s;
}
static const char *domain(void) {
const char *at = strrchr(mail_from, '@');
return at ? at + 1 : "hai";
}
/* the local part of an address, into dst */
static void localpart(char *dst, size_t n, const char *addr) {
const char *at = strrchr(addr, '@');
snprintf(dst, n, "%.*s", at ? (int)(at - addr) : (int)strlen(addr), addr);
}
static Child *find(const char *name) {
ptrdiff_t i;
for (i = 0; i < arrlen(children); i++)
if (!strcmp(children[i].name, name))
return &children[i];
return NULL;
}
/* a short lowercase word (dots are ours: they join the generations),
* and not one of the mailboxes already in use (ours, the user's) */
static const char *badname(const char *n) {
char lp[128];
size_t i, len = strlen(n);
int alpha = 0;
if (!len || len > 32 || n[0] == '-')
return "a name is 1 to 32 characters";
for (i = 0; n[i]; i++) {
if (islower((unsigned char)n[i]))
alpha = 1;
else if (!isdigit((unsigned char)n[i]) && n[i] != '-')
return "a name is lowercase letters, digits and dashes";
}
if (!alpha)
return "a name needs a letter";
localpart(lp, sizeof(lp), mail_from);
if (!strcmp(n, lp))
return "that is my own address";
localpart(lp, sizeof(lp), session_user);
if (!strcmp(n, lp))
return "that is the user's address";
return NULL;
}
/* the conversation the child itself has on disk: the session in its
* Maildir written most recently (a session is written on every turn,
* so that is the one it was in); -1 = none yet */
static int child_session(const Child *c, char *id, size_t n) {
char box[4400], lp[128];
localpart(lp, sizeof(lp), c->addr);
snprintf(box, sizeof(box), "%.3900s/%s", child_box, lp);
return session_newest(box, id, n);
}
/* --- the root's registry --- */
static Reg *regfind(const char *addr) {
ptrdiff_t i;
for (i = 0; i < arrlen(registry); i++)
if (!strcmp(registry[i].addr, addr))
return ®istry[i];
return NULL;
}
static Reg *regbypid(pid_t pid) {
ptrdiff_t i;
for (i = 0; pid > 0 && i < arrlen(registry); i++)
if (registry[i].pid == pid)
return ®istry[i];
return NULL;
}
/* the parent's local part of an address: up to its last dot; "" for
* a child of the root */
static void parentof(char *dst, size_t n, const char *addr) {
char lp[128];
const char *dot;
localpart(lp, sizeof(lp), addr);
dot = strrchr(lp, '.');
snprintf(dst, n, "%.*s", dot ? (int)(dot - lp) : 0, lp);
}
/* addr and everything below it (its local part, a dot) out */
static void regdrop(const char *addr) {
char lp[128];
size_t n;
ptrdiff_t i;
localpart(lp, sizeof(lp), addr);
n = strlen(lp);
for (i = arrlen(registry) - 1; i >= 0; i--)
if (!strcmp(registry[i].addr, addr) ||
(!strncmp(registry[i].addr, lp, n) && registry[i].addr[n] == '.'))
arrdel(registry, i);
}
static void mkticket(char *t) { /* 16 hex digits */
unsigned char b[8];
int fd = open("/dev/urandom", O_RDONLY), i;
if (fd < 0 || read(fd, b, sizeof(b)) != (ssize_t)sizeof(b)) {
long x = (long)time(NULL) ^ ((long)getpid() << 20) ^ (long)clock();
memcpy(b, &x, sizeof(b));
}
if (fd >= 0)
close(fd);
for (i = 0; i < 8; i++)
sprintf(t + i * 2, "%02x", b[i]);
}
char *child_ticket(const char *addr, pid_t by, char *t, size_t n) {
char want[128], parent[256], lp[128];
const char *w;
Reg r, *p;
ptrdiff_t i;
time_t now = time(NULL);
for (i = arrlen(registry) - 1; i >= 0; i--) /* nobody came for it */
if (!registry[i].pid && now - registry[i].t > TICKET_LIFE)
arrdel(registry, i);
parentof(want, sizeof(want), addr);
if (by == getpid()) {
if (*want)
return fmt("%s is not a child of the root", addr, NULL);
snprintf(parent, sizeof(parent), "%s", mail_from);
} else if (!(p = regbypid(by)))
return fmt("only an agent may ask for a child (%s)", addr, NULL);
else {
localpart(lp, sizeof(lp), p->addr);
if (strcmp(lp, want))
return fmt("%s may start only its own children, not %s", p->addr,
addr);
snprintf(parent, sizeof(parent), "%s", p->addr);
}
w = *want ? addr + strlen(want) + 1 : addr;
if (!*w || *w == '@' ||
(int)strspn(w, "abcdefghijklmnopqrstuvwxyz"
"0123456789-") != (int)strcspn(w, "@") ||
!strchr(w, '@'))
return fmt("bad agent address: %s", addr, NULL);
if ((p = regfind(addr)) && p->pid > 0 && kill(p->pid, 0) == 0)
return fmt("%s is already running", addr, NULL);
regdrop(addr); /* a stale entry, an older ticket */
memset(&r, 0, sizeof(r));
snprintf(r.addr, sizeof(r.addr), "%s", addr);
snprintf(r.parent, sizeof(r.parent), "%s", parent);
mkticket(r.ticket);
r.by = by;
r.t = now;
arrput(registry, r);
snprintf(t, n, "%s", r.ticket);
return NULL;
}
char *child_born(const char *addr, const char *t, pid_t pid, pid_t ppid) {
Reg *r;
if ((r = regbypid(pid)) && !strcmp(r->addr, addr))
return NULL; /* the same process again: a restart */
if (!(r = regfind(addr)) || r->pid || strcmp(r->ticket, t))
return fmt("%s has no ticket", addr, NULL);
if (r->by != ppid)
return fmt("%s was not started by the agent that asked", addr, NULL);
r->pid = pid;
r->t = time(NULL);
return NULL;
}
char *child_gone(const char *addr, pid_t by) {
char want[128], lp[128];
Reg *p;
parentof(want, sizeof(want), addr);
if (by != getpid()) {
if (!(p = regbypid(by)))
return fmt("only an agent may report one gone (%s)", addr, NULL);
localpart(lp, sizeof(lp), p->addr);
if (strcmp(lp, want))
return fmt("%s is not a child of %s", addr, p->addr);
} else if (*want)
return fmt("%s is not a child of the root", addr, NULL);
regdrop(addr);
return NULL;
}
char *child_agents(void) {
char *out = NULL, line[600];
ptrdiff_t i;
const char *p;
for (i = 0; i < arrlen(registry); i++) {
if (!registry[i].pid)
continue;
snprintf(line, sizeof(line), "%s child of %s, pid %ld\n",
registry[i].addr, registry[i].parent, (long)registry[i].pid);
for (p = line; *p; p++)
arrput(out, *p);
}
if (!out)
for (p = "none\n"; *p; p++)
arrput(out, *p);
arrput(out, '\0');
{
char *r = xstrdup(out);
arrfree(out);
return r;
}
}
/* the root's registry hears that an agent of ours is gone: told by us
* when we are the root, else over the socket */
static void gone(const Child *c) {
char line[300];
if (!child_askroot) {
regdrop(c->addr);
return;
}
snprintf(line, sizeof(line), "gone %s", c->addr);
free(child_askroot(line));
}
/* --- the processes --- */
static char *spawn(Child *c, int autonomous) { /* NULL = started */
char inbox[4300], exe[4096], lp[128], sid[128], resume[160], ticket[24];
char line[300], *r, *e;
ssize_t n;
int have;
localpart(lp, sizeof(lp), c->addr);
snprintf(inbox, sizeof(inbox), "%.4000s/%s", child_box, lp);
if (mail_mkbox(inbox) < 0)
return xstrdup(strerror(errno));
if (child_exe)
snprintf(exe, sizeof(exe), "%s", child_exe);
else if ((n = readlink("/proc/self/exe", exe, sizeof(exe) - 1)) > 0)
exe[n] = '\0';
else
return xstrdup(strerror(errno));
/* the root's leave: a ticket the newborn presents */
if (!child_askroot) {
if ((e = child_ticket(c->addr, getpid(), ticket, sizeof(ticket))))
return e;
} else {
snprintf(line, sizeof(line), "fork %s", c->addr);
if (!(r = child_askroot(line)))
return xstrdup("the root does not answer");
if (strncmp(r, "ok ", 3)) {
e = fmt("the root refuses: %s", r + (strncmp(r, "err ", 4) ? 0 : 4),
NULL);
free(r);
return e;
}
snprintf(ticket, sizeof(ticket), "%.23s", r + 3);
free(r);
}
/* a service is brought back the way it was, its conversation
* resumed: `haid -y -r ID --child ADDR PARENT [DIR]` */
have = c->service && child_session(c, sid, sizeof(sid)) == 0;
if (have)
snprintf(resume, sizeof(resume), "%s", sid);
if ((c->pid = fork()) < 0)
return xstrdup(strerror(errno));
if (c->pid == 0) {
int null = open("/dev/null", O_RDONLY);
dup2(null, 0);
setenv("HAI_TICKET", ticket, 1);
if (autonomous)
setenv("HAI_AUTONOMOUS", "1", 1);
if (c->model[0]) /* the environment beats its config file */
setenv("HAI_MODEL", c->model, 1);
if (have && c->dir[0])
execl(exe, exe, "-y", "-r", resume, "--child", c->addr, mail_from,
c->dir, (char *)NULL);
else if (have)
execl(exe, exe, "-y", "-r", resume, "--child", c->addr, mail_from,
(char *)NULL);
else if (c->dir[0])
execl(exe, exe, "--child", c->addr, mail_from, c->dir,
(char *)NULL);
else
execl(exe, exe, "--child", c->addr, mail_from, (char *)NULL);
_exit(127);
}
c->started = time(NULL);
c->died = 0;
return NULL;
}
static int alive(Child *c) {
int st;
if (c->pid > 0 && waitpid(c->pid, &st, WNOHANG) > 0)
c->pid = -1;
return c->pid > 0;
}
/* a standing agent that died is brought back from the top, in its own
* directory and on its own conversation (a fresh haid may bind the
* socket an old one left behind; one that has just started cannot).
* A few tries, a pause between them; then it is left down and the
* daemon says so once. */
static void respawn(Child *c) {
char *e;
if (!c->service || c->down)
return;
if (!c->died)
c->died = time(NULL);
if (c->pid > 0)
return;
if (c->died - c->started > RESPAWN_WELL) /* it was up for a while */
c->tries = 0; /* so this is a new crash */
if (c->tries >= RESPAWN_TRIES) {
c->down = 1;
return;
}
if (time(NULL) - c->died < RESPAWN_DELAY)
return;
c->tries++;
if (!(e = spawn(c, c->autonomous)))
c->died = 0;
else
free(e);
}
/* the reaper in the daemon's loop saw PID go: st is its status, -1
* when it was never ours to wait for. A standing agent is brought
* back. */
void child_exit(pid_t pid, int st) {
ptrdiff_t i;
for (i = 0; i < arrlen(children); i++)
if (children[i].pid == pid) {
int quiet = st != -1 && WIFEXITED(st) && WEXITSTATUS(st) == 0;
children[i].pid = -1;
children[i].died = time(NULL);
gone(&children[i]);
if (!quiet) /* a clean exit is a standing agent stopping itself */
respawn(&children[i]);
return;
}
}
/* the daemon's heartbeat for its standing agents: bring back any that
* died; -1 the first time one of them cannot be started again (the
* caller says so once) */
int child_ensure(void) {
ptrdiff_t i;
int news = 0;
for (i = 0; i < arrlen(children); i++) {
Child *c = &children[i];
if (c->service && !alive(c))
respawn(c);
if (c->down && !c->reported)
c->reported = 1, news = 1;
}
return news ? -1 : 0;
}
/* the first line of the task, capped, as the subject */
static void subject(char *dst, size_t n, const char *task) {
size_t i;
for (i = 0; i + 1 < n && task[i] && task[i] != '\n'; i++)
dst[i] = task[i];
dst[i] = '\0';
if (i + 1 == n)
strcpy(dst + n - 4, "...");
}
/* the report answering mid in the parent's inbox: its path, or NULL.
* A question the child asks replies to the task too, and is not it */
static int report(const char *mid, char *path, size_t n) {
char dir[4400], lp[128], **names, *intent;
ptrdiff_t i;
int hit = 0;
localpart(lp, sizeof(lp), mail_from);
snprintf(dir, sizeof(dir), "%.4000s/%s/new", child_box, lp);
names = mail_names(dir);
for (i = 0; i < arrlen(names); i++) {
if (!hit) {
snprintf(path, n, "%s/%s", dir, names[i]);
hit = mail_answers(path, mid);
if (hit && (intent = mail_header(path, "Hai-Intent"))) {
hit = strcmp(intent, "ask") != 0;
free(intent);
}
}
free(names[i]);
}
arrfree(names);
return hit;
}
/* the working directory as the child will see it: absolute, existing */
static const char *checkdir(const char *dir, char *out, size_t n) {
struct stat st;
if (dir[0] == '~' && (dir[1] == '/' || !dir[1]))
homepath(out, n, dir + 1 + (dir[1] == '/'));
else
snprintf(out, n, "%s", dir);
if (out[0] != '/')
return "dir must be an absolute path";
if (stat(out, &st) < 0 || !S_ISDIR(st.st_mode))
return "dir is not a directory";
return NULL;
}
/* "error: cannot start NAME: WHY", the why freed */
static char *cannot(const char *name, char *e) {
char *r = fmt("error: cannot start %s: %s", name, e);
free(e);
return r;
}
char *child_delegate(Agent *a, const char *name, const char *task, int wait,
const char *dir, const char *model) {
char mid[128], refs[400], subj[80], err[256], path[4500], wd[4096] = "";
char *e;
const char *why;
Child *c;
MailHdr h;
Msg m;
time_t t0;
if (child_depth >= child_maxdepth)
return xstrdup("error: this agent is too deep in the tree to "
"delegate; do the task yourself");
if ((why = badname(name)))
return fmt("error: bad name \"%s\": %s", name, why);
if (dir && *dir && (why = checkdir(dir, wd, sizeof(wd))))
return fmt("error: %s: %s", why, dir);
if (!model || !*model)
model = child_model ? child_model : "";
if (!(c = find(name))) {
Child n;
char lp[128];
if (arrlen(children) >= MAXCHILDREN)
return xstrdup("error: too many children already");
memset(&n, 0, sizeof(n));
snprintf(n.name, sizeof(n.name), "%s", name);
localpart(lp, sizeof(lp), mail_from);
if (child_depth) /* our name first: the lineage is the address */
snprintf(n.addr, sizeof(n.addr), "%.127s.%.32s@%.64s", lp, name,
domain());
else
snprintf(n.addr, sizeof(n.addr), "%s@%s", name, domain());
n.pid = -1;
arrput(children, n);
c = &children[arrlen(children) - 1];
}
if (alive(c)) { /* what it was started with stays */
if (c->service)
return fmt("error: %s is a standing agent (hai.conf); mail it "
"instead, or use another name",
name, NULL);
if (c->attended)
return fmt("error: %s is the user's own agent for %s; use "
"another name",
name, c->dir);
if (*wd && strcmp(wd, c->dir))
return fmt("error: %s already works in %s; use another name", name,
c->dir[0] ? c->dir : "the home directory");
if (*model && strcmp(model, c->model))
return fmt("error: %s already runs on %s; use another name", name,
c->model[0] ? c->model : "the default model");
} else {
snprintf(c->dir, sizeof(c->dir), "%s", wd);
snprintf(c->model, sizeof(c->model), "%s", model);
if ((e = spawn(c, a->autonomous)))
return cannot(name, e);
}
/* the task: a new conversation for the child, or a follow-up in
* the one it has; the parent's root rides along so the report can
* be routed back into this session. A conversation serves one
* session of ours: another one (a new project) starts a new one */
if (strcmp(c->proot, child_root ? child_root : "")) {
c->root[0] = c->last[0] = '\0';
snprintf(c->proot, sizeof(c->proot), "%s",
child_root ? child_root : "");
}
mail_mid(mid, sizeof(mid));
memset(&h, 0, sizeof(h));
if (!c->root[0]) {
snprintf(c->root, sizeof(c->root), "%s", mid);
snprintf(refs, sizeof(refs), "%s", child_root);
} else {
snprintf(refs, sizeof(refs), "%s %s", c->root, child_root);
h.inreplyto = c->last[0] ? c->last : c->root;
}
subject(subj, sizeof(subj), task);
h.from = mail_from;
h.to = c->addr;
h.subject = subj;
h.mid = mid;
h.references = *refs ? refs : NULL;
h.root = c->root;
h.intent = "message";
m = msg_new("assistant", task);
if (mail_send(&h, &m, err, sizeof(err)) < 0) {
msg_free(&m);
return fmt("error: cannot mail %s: %s", c->addr, err);
}
msg_free(&m);
if (!wait || !child_wait)
return fmt("%s started; its report will arrive later as an inbox "
"turn from %s",
name, c->addr);
t0 = time(NULL);
for (;;) {
if (report(mid, path, sizeof(path))) {
char *r;
if (mail_parse(path, &m, &h) < 0)
return fmt("error: cannot read the report from %s", name, NULL);
if (h.mid)
snprintf(c->last, sizeof(c->last), "%s", h.mid);
r = fmt("%s reports:\n%s", name, m.content ? m.content : "");
msg_free(&m);
mailhdr_free(&h);
unlink(path);
return r;
}
if (!alive(c))
return fmt("error: %s exited before reporting", name, NULL);
if (time(NULL) - t0 >= child_wait) {
char secs[32];
snprintf(secs, sizeof(secs), "%d", child_wait);
return fmt("no report from %s within %s s; it is still "
"working and its report will arrive later as an "
"inbox turn",
name, secs);
}
if (a->tick && a->tick(a->ud)) {
a->cancelled = 1;
return fmt("cancelled while waiting for %s; its report will "
"arrive later as an inbox turn",
name, NULL);
}
poll(NULL, 0, 200);
}
}
/* a child kept across the parent's conversations: the user's terminal
* agents and the standing ones from hai.conf; a delegate is not */
static int kept(const Child *c) { return c->attended || c->service; }
void child_killall(int all) {
ptrdiff_t i;
for (i = 0; i < arrlen(children); i++)
if (children[i].pid > 0 && (all || !kept(&children[i])))
kill(children[i].pid, SIGTERM);
for (i = 0; i < arrlen(children); i++)
if (children[i].pid > 0 && (all || !kept(&children[i]))) {
waitpid(children[i].pid, NULL, 0);
children[i].pid = -1;
}
for (i = arrlen(children) - 1; i >= 0; i--)
if (all || !kept(&children[i])) {
gone(&children[i]);
arrdel(children, i);
}
}
void child_sock(const char *name, char *buf, size_t n) {
const char *rt = getenv("XDG_RUNTIME_DIR");
snprintf(buf, n, "%s/hai-%s.sock", rt ? rt : "/tmp", name);
}
/* a name for the agent of a directory: its base name as a name */
static void dirname_(const char *dir, char *name, size_t n) {
const char *b = strrchr(dir, '/');
size_t i = 0;
b = b && b[1] ? b + 1 : dir;
for (; *b && i + 1 < n && i < 32; b++) {
char c = (char)tolower((unsigned char)*b);
if (!islower((unsigned char)c) && !isdigit((unsigned char)c))
c = '-';
if (c == '-' && (!i || name[i - 1] == '-'))
continue;
name[i++] = c;
}
while (i && name[i - 1] == '-')
i--;
name[i] = '\0';
if (badname(name))
snprintf(name, n, "agent");
}
int child_here(const char *dir, char *name, size_t n) {
ptrdiff_t i;
for (i = 0; i < arrlen(children); i++)
if (children[i].attended && !strcmp(children[i].dir, dir) &&
alive(&children[i])) {
snprintf(name, n, "%s", children[i].name);
return 0;
}
return -1;
}
char *child_attend(int autonomous, const char *dir, char *name, size_t n) {
char wd[4096], base[64], lp[128], *e;
const char *why;
Child *c, nw;
int k;
if ((why = checkdir(dir, wd, sizeof(wd))))
return fmt("error: %s: %s", why, dir);
if (child_here(wd, name, n) == 0)
return NULL;
if (child_depth >= child_maxdepth)
return xstrdup("error: too deep in the tree for another agent");
if (arrlen(children) >= MAXCHILDREN)
return xstrdup("error: too many children already");
dirname_(wd, base, sizeof(base));
snprintf(name, n, "%s", base);
for (k = 2; (c = find(name)) && alive(c) && k < 10; k++)
snprintf(name, n, "%.28s-%d", base, k); /* another dir, same name */
if (c && alive(c))
return fmt("error: too many agents called %s", base, NULL);
if (!c) {
memset(&nw, 0, sizeof(nw));
snprintf(nw.name, sizeof(nw.name), "%s", name);
localpart(lp, sizeof(lp), mail_from);
if (child_depth)
snprintf(nw.addr, sizeof(nw.addr), "%.127s.%.32s@%.64s", lp, name,
domain());
else
snprintf(nw.addr, sizeof(nw.addr), "%s@%s", name, domain());
nw.pid = -1;
arrput(children, nw);
c = &children[arrlen(children) - 1];
}
snprintf(c->dir, sizeof(c->dir), "%s", wd);
snprintf(c->model, sizeof(c->model), "%s", child_model ? child_model : "");
c->attended = 1;
c->root[0] = c->last[0] = '\0';
return (e = spawn(c, autonomous)) ? cannot(name, e) : NULL;
}
/* a standing agent: named in hai.conf, started with the daemon and
* kept across its conversations, so mail (a trigger, say) addressed
* to NAME@domain is served by it and never displaces the parent's
* conversation. dir and model as for a delegate; "" = none */
char *child_service(int autonomous, const char *name, const char *dir,
const char *model) {
char wd[4096] = "", lp[128], *e;
const char *why;
Child *c, nw;
if ((why = badname(name)))
return fmt("error: bad agent name \"%s\": %s", name, why);
if (dir && *dir && (why = checkdir(dir, wd, sizeof(wd))))
return fmt("error: %s: %s", why, dir);
if ((c = find(name)) && alive(c))
return fmt("error: %s is already running", name, NULL);
if (arrlen(children) >= MAXCHILDREN)
return xstrdup("error: too many children already");
if (!c) {
memset(&nw, 0, sizeof(nw));
snprintf(nw.name, sizeof(nw.name), "%s", name);
localpart(lp, sizeof(lp), mail_from);
if (child_depth)
snprintf(nw.addr, sizeof(nw.addr), "%.127s.%.32s@%.64s", lp, name,
domain());
else
snprintf(nw.addr, sizeof(nw.addr), "%s@%s", name, domain());
nw.pid = -1;
arrput(children, nw);
c = &children[arrlen(children) - 1];
}
snprintf(c->dir, sizeof(c->dir), "%s", wd);
snprintf(c->model, sizeof(c->model), "%s",
model && *model ? model
: child_model ? child_model
: "");
c->service = 1;
c->root[0] = c->last[0] = '\0';
return (e = spawn(c, autonomous)) ? cannot(name, e) : NULL;
}
int child_alive(const char *addr) {
ptrdiff_t i;
for (i = 0; i < arrlen(children); i++)
if (!strcmp(children[i].addr, addr))
return alive(&children[i]);
return 0;
}
char *child_list(void) {
char *out = NULL, line[600];
ptrdiff_t i;
const char *p;
for (i = 0; i < arrlen(children); i++) {
snprintf(line, sizeof(line), "%s%s %s%s%s%.200s%s%.100s", i ? ", " : "",
children[i].addr, alive(&children[i]) ? "running" : "exited",
children[i].attended ? " (terminal)"
: children[i].service ? " (service)"
: "",
children[i].dir[0] ? " in " : "", children[i].dir,
children[i].model[0] ? " on " : "", children[i].model);
for (p = line; *p; p++)
arrput(out, *p);
}
arrput(out, '\0');
{
char *r = xstrdup(out);
arrfree(out);
return r;
}
}