interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / seed / agent / agent.om

2404 lines · 45719 bytes Raw Blame History
1note seed/agent/agent.om -- omagent: a small coding agent in seeded Omega (program mode).
2note Compose: { printf 'om2\n'; cat seed/json/json.om seed/json/jsonw.om seed/net/http.om seed/net/notls.om seed/agent/path.om seed/agent/agent.om; } | seed/out/omc > omagent
3note Design, safety model, CLI and exit codes: seed/agent/README.md. Tests: seed/agent/tests/check.py.
4note The model is untrusted: every byte it sends is parsed by json.om/http.om under fixed caps, every
5note tool call is checked against permissions the operator gave on the command line, and the API key
6note never reaches stdout, stderr, the session file or a child process (execprog passes no environment).
7
8const QUSED ulong 0
9const QIP ulong 1
10const QPORT ulong 2
11const QTMO ulong 3
12const QCTMO ulong 4
13const QROUND ulong 5
14const QWRITE ulong 6
15const QNCMD ulong 7
16const QNFET ulong 8
17const QSFD ulong 9
18const QHBL ulong 10
19const QNREC ulong 11
20const QRES ulong 12
21const QINL ulong 13
22const QINP ulong 14
23const QINEOF ulong 15
24const QMEML ulong 16
25const QHAVEK ulong 17
26const QSESS ulong 18
27const QTST ulong 19
28const QURL ulong 20
29const QMODEL ulong 21
30const SCLEN ulong 0
31const SNC ulong 1
32const SFIN ulong 3
33const SID ulong 8
34const SNM ulong 16
35const SARG ulong 24
36const IPATH ulong 0
37const IMODEL ulong 1
38const IKEY ulong 2
39const IWORK ulong 3
40const ISESS ulong 4
41const IMEM ulong 5
42const IPROMPT ulong 6
43const IKEYENV ulong 7
44const IHOST ulong 8
45const ICMD ulong 16
46const IFET ulong 32
47const QMAXC ulong 8
48const QRESC ulong 65536
49const QCONC ulong 131072
50const QMSG ulong 262144
51
52global gpool uchar 65536
53global gsof ulong 64
54global gsln ulong 64
55global gnum ulong 32
56global gst ulong 64
57global gcont uchar 131072
58global gtid uchar 2048
59global gtnm uchar 1024
60global gtarg uchar 524288
61global gres uchar 70000
62global gmem uchar 65536
63global gmb ulong 8192
64global gmr uchar 8192
65global gin uchar 65536
66
67text cpre "omagent: "
68text cnl "\n"
69text cver "omagent 0.1.0 (seeded Omega, omega-mv seed/agent)\n"
70text cusage "usage: omagent --url http://IP:PORT/PATH --model NAME [-p PROMPT] [--workdir DIR]\n [--session FILE] [--memory FILE] [--allow-cmd /ABS/PATH]... [--allow-write]\n [--allow-fetch HOST:PORT]... [--timeout S] [--cmd-timeout S] [--max-rounds N]\n [--key-env NAME] | --version | --help\nWithout -p, prompts are read from stdin, one per line. The API key is read from the\nenvironment variable OMAGENT_API_KEY (or --key-env NAME) and sent as a Bearer token.\n"
71text odurl "--url"
72text odmodel "--model"
73text odp "-p"
74text odwork "--workdir"
75text odsess "--session"
76text odmem "--memory"
77text odcmd "--allow-cmd"
78text odwrite "--allow-write"
79text odfetch "--allow-fetch"
80text odtmo "--timeout"
81text odctmo "--cmd-timeout"
82text odround "--max-rounds"
83text odkeyenv "--key-env"
84text odver "--version"
85text odhelp "--help"
86text cdefkey "OMAGENT_API_KEY"
87text chttp "http://"
88text chttps "https://"
89text clocal "localhost"
90text cpost "POST"
91text cget "GET"
92text chost "Host"
93text cctype "Content-Type"
94text cjson "application/json"
95text caccept "Accept"
96text cevst "text/event-stream"
97text cauth "Authorization"
98text cbearer "Bearer "
99text cnctype "content-type"
100text cevs "event-stream"
101text cslash "/"
102text cbody1 "{\"model\":\""
103text cbody2 "\",\"stream\":true,\"tools\":"
104text cbody3 ",\"messages\":["
105text ccomma ","
106text cbody4 "]}"
107text ctools "[{\"type\":\"function\",\"function\":{\"name\":\"read_file\",\"description\":\"Read a text file inside the workspace (at most 64 KiB).\",\"parameters\":{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"path relative to the workspace\"}},\"required\":[\"path\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"write_file\",\"description\":\"Create or replace a file inside the workspace.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"path relative to the workspace\"},\"content\":{\"type\":\"string\"}},\"required\":[\"path\",\"content\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"run_command\",\"description\":\"Run an allowlisted program in the workspace. argv[0] is its absolute path; no shell, no environment.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"argv\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"argv\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"http_fetch\",\"description\":\"GET an http:// URL on an allowlisted host:port (at most 64 KiB of body).\",\"parameters\":{\"type\":\"object\",\"properties\":{\"url\":{\"type\":\"string\"}},\"required\":[\"url\"]}}}]"
108text csys "You are omagent, a small coding agent. Answer briefly. Use the tools only when they are needed; file paths are relative to the workspace. A tool result that starts with refused: was blocked by the operator's permissions; do not retry it."
109text cmemh "\n\nMemory file:\n"
110text crole "role"
111text cuser "user"
112text cassist "assistant"
113text ctool "tool"
114text csystem "system"
115text ccontent "content"
116text ctoolc "tool_calls"
117text ctcid "tool_call_id"
118text cid "id"
119text ctype "type"
120text cfunc "function"
121text cname "name"
122text cargs "arguments"
123text cindex "index"
124text cdelta "delta"
125text cmessage "message"
126text cchoices "choices"
127text cfinish "finish_reason"
128text cerror "error"
129text cpath "path"
130text cargv "argv"
131text curl "url"
132text cdone "[DONE]"
133text ccall "call_"
134text tnread "read_file"
135text tnwrite "write_file"
136text tnrun "run_command"
137text tnfetch "http_fetch"
138text cdevnull "/dev/null"
139text ecfg "missing or bad option; see --help"
140text ekeybad "the API key holds bytes outside 0x21..0x7e; refusing it"
141text ework "cannot enter --workdir"
142text esess "cannot open or read --session file"
143text esline "session file line is not a valid message object; refusing to continue"
144text emem "cannot read --memory file"
145text econn "cannot connect to the model server"
146text ewrite "sending the request failed"
147text etmo "the model server timed out"
148text eread "reading the model response failed"
149text estat "the model server answered with status"
150text ebad "malformed model output"
151text ebig "malformed model output: a JSON reply or one SSE event is over 256 KiB"
152text eevj "malformed model output: an event is not a JSON object"
153text eserr "the model server sent an error object"
154text enodone "malformed model output: the stream ended before [DONE] or a finish_reason"
155text emany "malformed model output: more than 8 tool calls, or a bad index"
156text elong "malformed model output: a tool call field is too long"
157text econt "malformed model output: the reply is over 128 KiB"
158text emsg "a message could not be encoded (invalid UTF-8 or over 256 KiB)"
159text efull "the conversation history is full"
160text esave "cannot append to the session file"
161text eround "stopped: tool round limit reached (--max-rounds)"
162text ltool "tool "
163text lok ": ok"
164text lref ": refused"
165text lerr ": error"
166text rnoargs "error: tool arguments are not a JSON object"
167text runknown "refused: unknown tool "
168text rpatharg "error: the path argument must be a string"
169text rpath "refused: the path must be relative to the workspace, without empty, . or .. parts and without symbolic links"
170text ropen "error: cannot open the file, errno "
171text rreadf "error: reading the file failed, errno "
172text rtrunc "\n[truncated at 65536 bytes]"
173text rnowrite "refused: write_file is disabled (the operator did not pass --allow-write)"
174text rcontarg "error: the content argument must be a string under 256 KiB"
175text rwrote "ok: wrote "
176text rbytes " bytes to "
177text rwfail "error: writing the file failed, errno "
178text rnocmd "refused: run_command is disabled (the operator gave no --allow-cmd)"
179text rargv "error: argv must be an array of 1..63 strings"
180text rnotal "refused: the program is not on the --allow-cmd list: "
181text rnul "refused: an argument holds a zero byte"
182text rpack "refused: argv is over 4 KiB"
183text rpipe "error: cannot create a pipe or fork"
184text rexit "\n[exit status "
185text rsig "\n[killed by signal "
186text rtmo "\n[killed: timeout after "
187text rsec " s]"
188text rclose "]"
189text rnofet "refused: http_fetch is disabled (the operator gave no --allow-fetch)"
190text rurlarg "error: the url argument must be a string"
191text rnohttp "refused: only http:// URLs are supported by this build"
192text rurlbad "error: malformed url"
193text rnotfa "refused: the host:port is not on the --allow-fetch list: "
194text rconn "error: cannot connect"
195text rfreq "error: request failed"
196text rftmo "error: timed out"
197text rstatus "status="
198
199note ======== output and small helpers
200
201fn agwr fd int b view uchar * o ulong n ulong to bool
202p = ulong 0
203while lt p n bound 999999
204w = write fd b add o p sub n p
205if le w 0
206ret false
207end
208p = add p ulong w
209end
210ret true
211end
212
213fn agdec v ulong d edit uchar 24 to ulong
214t = new uchar 24 0
215k = ulong 0
216x = v
217for i ulong 21
218put t k uchar add 48 rem x 10
219k = add k 1
220x = div x 10
221if eq x 0
222break
223end
224end
225for j ulong k
226put d j get t sub sub k 1 j
227end
228ret k
229end
230
231fn agerr t view uchar * to void
232r = agwr 2 cpre 0 len cpre
233r = agwr 2 t 0 len t
234r = agwr 2 cnl 0 1
235end
236
237fn agerrn t view uchar * v ulong to void
238d = new uchar 24 0
239r = agwr 2 cpre 0 len cpre
240r = agwr 2 t 0 len t
241d2 = new uchar 1 32
242r = agwr 2 d2 0 1
243n = agdec v d
244r = agwr 2 d 0 n
245r = agwr 2 cnl 0 1
246end
247
248note ======== string pool for configuration (ids I*), filled once from argv and the environment
249
250fn agstash id ulong a view uchar * to bool
251u = get gnum QUSED
252n = len a
253if gt n sub 65536 u
254ret false
255end
256for i ulong n
257put gpool add u i get a i
258end
259put gsof id u
260put gsln id n
261put gnum QUSED add u n
262ret true
263end
264
265fn agsget id ulong d edit uchar * to ulong
266n = get gsln id
267if gt n len d
268ret 0
269end
270o = get gsof id
271for i ulong n
272put d i get gpool add o i
273end
274ret n
275end
276
277fn agseq id ulong a view uchar * to bool
278n = get gsln id
279if ne n len a
280ret false
281end
282o = get gsof id
283for i ulong n
284if ne get gpool add o i get a i
285ret false
286end
287end
288ret true
289end
290
291note ======== tool result buffer gres[0, QRES), status QTST 0 ok, 1 refused, 2 error
292
293fn agradd t view uchar * to void
294r = get gnum QRES
295for i ulong len t
296if ge r 69000
297break
298end
299put gres r get t i
300r = add r 1
301end
302put gnum QRES r
303end
304
305fn agrset st ulong t view uchar * to void
306put gnum QRES 0
307put gnum QTST st
308agradd t
309end
310
311fn agrnum v ulong to void
312d = new uchar 24 0
313n = agdec v d
314agradd view part d 0 n
315end
316
317fn agrerr t view uchar * e long to void
318agrset 2 t
319x = ulong 0
320if lt e 0
321x = ulong neg e
322end
323agrnum x
324end
325
326note agu8fix: replace every byte of gres that is not part of well-formed UTF-8 by '?', so the
327note JSON writer (which validates UTF-8) always accepts a tool result
328fn agu8fix to void
329n = get gnum QRES
330i = ulong 0
331while lt i n bound 999999
332c = get gres i
333if lt c 128
334i = add i 1
335continue
336end
337k = ulong 0
338lo = uchar 128
339hi = uchar 191
340if and ge c 194 le c 223
341k = 1
342end
343if and ge c 224 le c 239
344k = 2
345end
346if and ge c 240 le c 244
347k = 3
348end
349if eq c 224
350lo = 160
351end
352if eq c 237
353hi = 159
354end
355if eq c 240
356lo = 144
357end
358if eq c 244
359hi = 143
360end
361ok = and gt k 0 lt add i k n
362if ok
363b = get gres add i 1
364if or lt b lo gt b hi
365ok = false
366end
367end
368if ok
369for j ulong sub k 1
370b2 = get gres add add i 2 j
371if or lt b2 128 gt b2 191
372ok = false
373end
374end
375end
376if ok
377i = add add i k 1
378else
379put gres i 63
380i = add i 1
381end
382end
383end
384
385note ======== URLs: http://HOST[:PORT][/PATH]; HOST is a dotted IPv4 address or localhost
386note r: 0 ip, 1 port, 2 authority offset, 3 authority length, 4 path offset, 5 path length, 6 host length
387
388fn agip4 u view uchar * o ulong n ulong to long
389v = ulong 0
390part4 = ulong 0
391dig = ulong 0
392cnt = ulong 0
393for i ulong n
394c = get u add o i
395if eq c 46
396if or eq dig 0 gt part4 255
397ret -1
398end
399v = or shl v 8 part4
400cnt = add cnt 1
401part4 = 0
402dig = 0
403continue
404end
405if or lt c 48 gt c 57
406ret -1
407end
408part4 = add mul part4 10 ulong sub c 48
409dig = add dig 1
410if gt dig 3
411ret -1
412end
413end
414if or or eq dig 0 gt part4 255 ne cnt 3
415ret -1
416end
417ret long or shl v 8 part4
418end
419
420fn agurl u view uchar * r edit ulong 8 to long
421n = len u
422if and ge n 8 heq view part u 0 8 chttps
423ret -1
424end
425if or lt n 8 not heq view part u 0 7 chttp
426ret -1
427end
428a = ulong 7
429e = a
430while lt e n bound 999999
431if eq get u e 47
432break
433end
434e = add e 1
435end
436if eq e a
437ret -2
438end
439hl = sub e a
440port = ulong 80
441for i ulong sub e a
442if eq get u add a i 58
443hl = i
444pd = add add a i 1
445if or eq pd e gt sub e pd 5
446ret -2
447end
448if not hdigits view part u pd sub e pd
449ret -2
450end
451port = hdecv view part u pd sub e pd
452break
453end
454end
455if or eq port 0 gt port 65535
456ret -2
457end
458ip = long 0
459if heq view part u a hl clocal
460ip = 2130706433
461else
462ip = agip4 u a hl
463end
464if lt ip 0
465ret -2
466end
467for j ulong sub n e
468c = get u add e j
469if or le c 32 ge c 127
470ret -2
471end
472end
473put r 0 ulong ip
474put r 1 port
475put r 2 a
476put r 3 sub e a
477put r 4 e
478put r 5 sub n e
479put r 6 hl
480ret 0
481end
482
483note ======== command line
484
485fn agnamech c uchar to bool
486if and ge c 97 le c 122
487ret true
488end
489if and ge c 65 le c 90
490ret true
491end
492if and ge c 48 le c 57
493ret true
494end
495ret or or or eq c 46 eq c 95 or eq c 58 eq c 47 or or eq c 45 eq c 64 eq c 43
496end
497
498fn agsetnum ab view uchar 65536 n ulong slot ulong mul1 ulong to bool
499if not hdigits view part ab 0 n
500ret false
501end
502v = hdecv view part ab 0 n
503if or eq v 0 gt v 86400
504ret false
505end
506put gnum slot mul v mul1
507ret true
508end
509
510fn agseturl ab view uchar 65536 n ulong to bool
511r = new ulong 8 0
512rc = agurl view part ab 0 n r
513if lt rc 0
514ret false
515end
516put gnum QIP get r 0
517put gnum QPORT get r 1
518put gnum QURL 1
519if eq get r 5 0
520if not agstash IPATH cslash
521ret false
522end
523else
524if not agstash IPATH view part ab get r 4 get r 5
525ret false
526end
527end
528ret agstash IHOST view part ab get r 2 get r 3
529end
530
531fn agsetmodel ab view uchar 65536 n ulong to bool
532if or eq n 0 gt n 200
533ret false
534end
535for i ulong n
536if not agnamech get ab i
537ret false
538end
539end
540put gnum QMODEL 1
541ret agstash IMODEL view part ab 0 n
542end
543
544note agopt1: one option that takes a value; ab holds the value, n its length
545fn agopt1 op ulong ab view uchar 65536 n ulong to bool
546if eq op 1
547ret agseturl ab n
548end
549if eq op 2
550ret agsetmodel ab n
551end
552if eq op 3
553if eq n 0
554ret false
555end
556ret agstash IPROMPT view part ab 0 n
557end
558if eq op 4
559ret and gt n 0 agstash IWORK view part ab 0 n
560end
561if eq op 5
562ret and gt n 0 agstash ISESS view part ab 0 n
563end
564if eq op 6
565ret and gt n 0 agstash IMEM view part ab 0 n
566end
567if eq op 7
568k = get gnum QNCMD
569if or or ge k 16 lt n 2 ne get ab 0 47
570ret false
571end
572put gnum QNCMD add k 1
573ret agstash add ICMD k view part ab 0 n
574end
575if eq op 8
576k2 = get gnum QNFET
577if or ge k2 16 eq n 0
578ret false
579end
580put gnum QNFET add k2 1
581ret agstash add IFET k2 view part ab 0 n
582end
583if eq op 9
584ret agsetnum ab n QTMO 1000000000
585end
586if eq op 10
587ret agsetnum ab n QCTMO 1000000000
588end
589if eq op 11
590if not agsetnum ab n QROUND 1
591ret false
592end
593ret le get gnum QROUND 64
594end
595if eq op 12
596ret and gt n 0 agstash IKEYENV view part ab 0 n
597end
598ret false
599end
600
601fn agoptid ab view uchar 65536 n ulong to ulong
602if heq view part ab 0 n odurl
603ret 1
604end
605if heq view part ab 0 n odmodel
606ret 2
607end
608if heq view part ab 0 n odp
609ret 3
610end
611if heq view part ab 0 n odwork
612ret 4
613end
614if heq view part ab 0 n odsess
615ret 5
616end
617if heq view part ab 0 n odmem
618ret 6
619end
620if heq view part ab 0 n odcmd
621ret 7
622end
623if heq view part ab 0 n odfetch
624ret 8
625end
626if heq view part ab 0 n odtmo
627ret 9
628end
629if heq view part ab 0 n odctmo
630ret 10
631end
632if heq view part ab 0 n odround
633ret 11
634end
635if heq view part ab 0 n odkeyenv
636ret 12
637end
638if heq view part ab 0 n odwrite
639ret 20
640end
641if heq view part ab 0 n odver
642ret 21
643end
644if heq view part ab 0 n odhelp
645ret 22
646end
647ret 0
648end
649
650note agargs: 0 ready, 1 printed --version/--help (exit 0), 2 usage error
651fn agargs to int
652ab = new uchar 65536 0
653c = ulong argcnt
654put gnum QTMO 120000000000
655put gnum QCTMO 10000000000
656put gnum QROUND 8
657ok = agstash IKEYENV cdefkey
658i = ulong 1
659while lt i c bound 9999
660n = argread i ab 0 65536
661if lt n 0
662agerr ecfg
663ret 2
664end
665op = agoptid ab ulong n
666if eq op 0
667agerr ecfg
668ret 2
669end
670if eq op 20
671put gnum QWRITE 1
672i = add i 1
673continue
674end
675if eq op 21
676ok = agwr 1 cver 0 len cver
677ret 1
678end
679if eq op 22
680ok = agwr 1 cusage 0 len cusage
681ret 1
682end
683if ge add i 1 c
684agerr ecfg
685ret 2
686end
687n2 = argread add i 1 ab 0 65536
688if lt n2 0
689agerr ecfg
690ret 2
691end
692if not agopt1 op ab ulong n2
693agerr ecfg
694ret 2
695end
696i = add i 2
697end
698if or eq get gnum QURL 0 eq get gnum QMODEL 0
699agerr ecfg
700ok = agwr 2 cusage 0 len cusage
701ret 2
702end
703ret 0
704end
705
706fn agkeyok eb view uchar 8192 o ulong n ulong to bool
707if or eq n 0 gt n 4000
708ret false
709end
710for j ulong n
711c = get eb add o j
712if or lt c 33 gt c 126
713ret false
714end
715end
716ret true
717end
718
719note agkeyload: find KEYENV=VALUE in the environment; the value goes to the pool only
720fn agkeyload to int
721eb = new uchar 8192 0
722kn = new uchar 256 0
723k = agsget IKEYENV kn
724if eq k 0
725ret 0
726end
727rc = int 0
728for i ulong ulong envcnt
729n = envread i eb 0 8192
730if le n long k
731continue
732end
733if ne get eb k 61
734continue
735end
736if not heq view part eb 0 k view part kn 0 k
737continue
738end
739vl = sub ulong n add k 1
740if agkeyok eb add k 1 vl
741ok = agstash IKEY view part eb add k 1 vl
742put gnum QHAVEK 1
743else
744agerr ekeybad
745rc = 2
746end
747break
748end
749for z ulong 8192
750put eb z 0
751end
752ret rc
753end
754
755note agmemload: --memory FILE (read before chdir) into gmem, at most 65535 bytes, UTF-8 repaired
756fn agmemload to int
757if eq get gsln IMEM 0
758ret 0
759end
760pb = new uchar 4096 0
761pn = agsget IMEM pb
762if eq pn 0
763agerr emem
764ret 8
765end
766fd = fopen pb 0 pn 524288 0
767if lt fd 0
768agerr emem
769ret 8
770end
771got = ulong 0
772while lt got 65535 bound 999999
773r = read int fd gres got sub 65535 got
774if lt r 0
775agerr emem
776ret 8
777end
778if eq r 0
779break
780end
781got = add got ulong r
782end
783r2 = fclose int fd
784put gnum QRES got
785agu8fix
786for i ulong got
787put gmem i get gres i
788end
789put gnum QMEML got
790put gnum QRES 0
791ret 0
792end
793
794note ======== conversation history: hb holds the message objects joined by commas; gmb/gmr
795note record each object's offset and role (1 user, 2 assistant, 3 tool, 4 system, 5 assistant
796note with tool_calls). The session file holds the same objects, one per line.
797
798fn agkey src view uchar 262144 tp view uint 65536 obj ulong key view uchar * to ulong
799if ne js_type tp obj jsobj
800ret jsnone
801end
802k = js_first tp obj
803while ne k jsnone bound 999999
804if js_streq src js_off tp k key
805ret add k 1
806end
807k = js_mnext tp k
808end
809ret jsnone
810end
811
812fn agrole src view uchar 262144 tp view uint 65536 to ulong
813if ne js_type tp 0 jsobj
814ret 0
815end
816r = agkey src tp 0 crole
817if eq r jsnone
818ret 0
819end
820if ne js_type tp r jsstr
821ret 0
822end
823o = js_off tp r
824if js_streq src o cuser
825ret 1
826end
827if js_streq src o cassist
828if ne agkey src tp 0 ctoolc jsnone
829ret 5
830end
831ret 2
832end
833if js_streq src o ctool
834ret 3
835end
836if js_streq src o csystem
837ret 4
838end
839ret 0
840end
841
842note agfront: drop the records before index k (k may equal the count: drop all)
843fn agfront hb edit uchar 1048576 k ulong to void
844n = get gnum QNREC
845h = get gnum QHBL
846if eq k 0
847ret
848end
849if ge k n
850put gnum QNREC 0
851put gnum QHBL 0
852ret
853end
854off = get gmb k
855hmove hb 0 off sub h off
856for j ulong sub n k
857put gmb j sub get gmb add j k off
858put gmr j get gmr add j k
859end
860put gnum QNREC sub n k
861put gnum QHBL sub h off
862end
863
864note agtrim: an interrupted turn (history ending in user, tool, or assistant with tool_calls)
865note is dropped back to before its user message
866fn agtrim to void
867n = get gnum QNREC
868if eq n 0
869ret
870end
871last = get gmr sub n 1
872if eq last 2
873ret
874end
875u = n
876for i ulong n
877j = sub sub n 1 i
878if eq get gmr j 1
879u = j
880break
881end
882end
883if eq u n
884put gnum QNREC 0
885put gnum QHBL 0
886ret
887end
888put gnum QNREC u
889if eq u 0
890put gnum QHBL 0
891else
892put gnum QHBL sub get gmb u 1
893end
894end
895
896note agcompact: before a turn, keep the newest whole turns within 512 KiB and 4096 records
897fn agcompact hb edit uchar 1048576 to void
898n = get gnum QNREC
899h = get gnum QHBL
900if and le h 524288 le n 4096
901ret
902end
903k = n
904for i ulong n
905if eq get gmr i 1
906if le sub h get gmb i 524288
907if le sub n i 4096
908k = i
909break
910end
911end
912end
913end
914agfront hb k
915end
916
917fn agappend wb edit uchar 263184 hb edit uchar 1048576 role ulong to int
918r = js_wdone wb
919if lt r 0
920agerr emsg
921ret 9
922end
923m = ulong r
924if gt m QMSG
925agerr emsg
926ret 9
927end
928h = get gnum QHBL
929k = get gnum QNREC
930if or gt add add h m 1 1048576 ge k 8192
931agerr efull
932ret 9
933end
934if gt h 0
935put hb h 44
936h = add h 1
937end
938for i ulong m
939put hb add h i get wb add 1040 i
940end
941put gmb k h
942put gmr k uchar role
943put gnum QNREC add k 1
944put gnum QHBL add h m
945if eq get gnum QSESS 1
946fd = int get gnum QSFD
947ok = agwr fd wb 1040 m
948ok2 = agwr fd cnl 0 1
949if not and ok ok2
950agerr esave
951ret 8
952end
953end
954ret 0
955end
956
957note agsread: open --session FILE (O_RDWR|O_CREAT|O_APPEND|O_CLOEXEC, mode 0600) and read its
958note last 768 KiB into hb, starting at a line boundary; returns the byte count or -1
959fn agsread hb edit uchar 1048576 to long
960pb = new uchar 4096 0
961st = new uchar 128 0
962pn = agsget ISESS pb
963fd = fopen pb 0 pn 525378 384
964if lt fd 0
965ret -1
966end
967put gnum QSFD ulong fd
968put gnum QSESS 1
969r = fstat int fd st 0 128
970if lt r 0
971ret -1
972end
973sz = ulong 0
974for b ulong 8
975sz = or shl sz 8 ulong get st sub 55 b
976end
977start = ulong 0
978if gt sz 786432
979start = sub sz 786432
980end
981got = ulong 0
982while lt got sub sz start bound 999999
983r = pread int fd hb got sub sub sz start got long add start got
984if lt r 0
985ret -1
986end
987if eq r 0
988break
989end
990got = add got ulong r
991end
992if eq start 0
993ret long got
994end
995p = ulong 0
996while lt p got bound 999999
997if eq get hb p 10
998break
999end
1000p = add p 1
1001end
1002if ge p got
1003ret 0
1004end
1005hmove hb 0 add p 1 sub got add p 1
1006ret long sub got add p 1
1007end
1008
1009note agsrec: check one session line hb[p, p+ln) and append it at w; returns the role or 0
1010fn agsrec hb edit uchar 1048576 p ulong ln ulong w ulong to ulong
1011lb = new uchar 262144 0
1012tp = new uint 65536 0
1013if gt ln 262144
1014ret 0
1015end
1016ri = js_init tp 262144 64
1017for i ulong ln
1018put lb i get hb add p i
1019end
1020pr = js_parse lb tp ln
1021if lt pr 0
1022ret 0
1023end
1024ro = agrole lb tp
1025if ne ro 0
1026hmove hb w p ln
1027end
1028ret ro
1029end
1030
1031note agsload: rebuild hb, gmb and gmr from the session file; every line must be a message object
1032fn agsload hb edit uchar 1048576 to int
1033if eq get gsln ISESS 0
1034ret 0
1035end
1036got = agsread hb
1037if lt got 0
1038agerr esess
1039ret 8
1040end
1041n = ulong got
1042p = ulong 0
1043w = ulong 0
1044k = ulong 0
1045while lt p n bound 999999
1046e = p
1047while lt e n bound 999999
1048if eq get hb e 10
1049break
1050end
1051e = add e 1
1052end
1053if gt e p
1054if gt w 0
1055put hb w 44
1056w = add w 1
1057end
1058ro = ulong 0
1059if lt k 8192
1060ro = agsrec hb p sub e p w
1061end
1062if eq ro 0
1063agerr esline
1064ret 8
1065end
1066put gmb k w
1067put gmr k uchar ro
1068k = add k 1
1069w = add w sub e p
1070end
1071p = add e 1
1072end
1073put gnum QNREC k
1074put gnum QHBL w
1075agtrim
1076u = get gnum QNREC
1077for i ulong u
1078if eq get gmr i 1
1079u = i
1080break
1081end
1082end
1083agfront hb u
1084ret 0
1085end
1086
1087note ======== messages written with the JSON writer (wb: 1040 state bytes + 262144 text bytes)
1088
1089fn agwstr wb edit uchar 263184 t view uchar * to void
1090js_wsbuf wb t 0 len t
1091end
1092
1093fn agsysmsg wb edit uchar 263184 to long
1094r = js_winit wb
1095js_wobj wb
1096agwstr wb crole
1097agwstr wb csystem
1098agwstr wb ccontent
1099js_wsbeg wb
1100for i ulong len csys
1101js_wsb wb get csys i
1102end
1103ml = get gnum QMEML
1104if gt ml 0
1105for j ulong len cmemh
1106js_wsb wb get cmemh j
1107end
1108for k ulong ml
1109js_wsb wb get gmem k
1110end
1111end
1112js_wsend wb
1113js_wobje wb
1114ret js_wdone wb
1115end
1116
1117fn agwuser wb edit uchar 263184 ub view uchar 65536 un ulong to void
1118r = js_winit wb
1119js_wobj wb
1120agwstr wb crole
1121agwstr wb cuser
1122agwstr wb ccontent
1123js_wsbuf wb ub 0 un
1124js_wobje wb
1125end
1126
1127note agwg: write one JSON string from a global: 0 gtid, 1 gtnm, 2 gtarg, 3 gcont, 4 gres
1128fn agwg wb edit uchar 263184 sel ulong off ulong n ulong to void
1129js_wsbeg wb
1130for i ulong n
1131c = uchar 0
1132if eq sel 0
1133c = get gtid add off i
1134end
1135if eq sel 1
1136c = get gtnm add off i
1137end
1138if eq sel 2
1139c = get gtarg add off i
1140end
1141if eq sel 3
1142c = get gcont add off i
1143end
1144if eq sel 4
1145c = get gres add off i
1146end
1147js_wsb wb c
1148end
1149js_wsend wb
1150end
1151
1152fn agwcall wb edit uchar 263184 c ulong to void
1153js_wobj wb
1154agwstr wb cid
1155agwg wb 0 mul c 256 get gst add SID c
1156agwstr wb ctype
1157agwstr wb cfunc
1158agwstr wb cfunc
1159js_wobj wb
1160agwstr wb cname
1161agwg wb 1 mul c 128 get gst add SNM c
1162agwstr wb cargs
1163agwg wb 2 mul c 65536 get gst add SARG c
1164js_wobje wb
1165js_wobje wb
1166end
1167
1168fn agwasst wb edit uchar 263184 to void
1169r = js_winit wb
1170js_wobj wb
1171agwstr wb crole
1172agwstr wb cassist
1173agwstr wb ccontent
1174nc = get gst SNC
1175if and eq get gst SCLEN 0 gt nc 0
1176js_wnull wb
1177else
1178agwg wb 3 0 get gst SCLEN
1179end
1180if gt nc 0
1181agwstr wb ctoolc
1182js_warr wb
1183for c ulong nc
1184agwcall wb c
1185end
1186js_warre wb
1187end
1188js_wobje wb
1189end
1190
1191fn agwtool wb edit uchar 263184 c ulong to void
1192r = js_winit wb
1193js_wobj wb
1194agwstr wb crole
1195agwstr wb ctool
1196agwstr wb ctcid
1197agwg wb 0 mul c 256 get gst add SID c
1198agwstr wb ccontent
1199agwg wb 4 0 get gnum QRES
1200js_wobje wb
1201end
1202
1203note agfixids: a call without an id gets call_N, so its tool message can name it
1204fn agfixids to void
1205for c ulong get gst SNC
1206if eq get gst add SID c 0
1207for i ulong len ccall
1208put gtid add mul c 256 i get ccall i
1209end
1210put gtid add mul c 256 len ccall uchar add 48 c
1211put gst add SID c add len ccall 1
1212end
1213end
1214end
1215
1216note ======== model response: SSE events or one JSON body; both carry choices[0].delta|message
1217
1218note agapp: append dc[0, n) to field sel (0 id, 1 name, 2 arguments) of tool call ix
1219fn agapp sel ulong ix ulong dc view uchar 262144 n ulong to bool
1220slot = add SID ix
1221cap = ulong 255
1222if eq sel 1
1223slot = add SNM ix
1224cap = 127
1225end
1226if eq sel 2
1227slot = add SARG ix
1228cap = 65535
1229end
1230l = get gst slot
1231if gt n sub cap l
1232ret false
1233end
1234b = add mul ix add cap 1 l
1235if eq sel 0
1236for i ulong n
1237put gtid add b i get dc i
1238end
1239end
1240if eq sel 1
1241for j ulong n
1242put gtnm add b j get dc j
1243end
1244end
1245if eq sel 2
1246for k ulong n
1247put gtarg add b k get dc k
1248end
1249end
1250put gst slot add l n
1251ret true
1252end
1253
1254note agtcstr: field sel of call ix from value v (absent: nothing; a string: decoded and appended;
1255note an object as arguments: its raw JSON text appended)
1256fn agtcstr src view uchar 262144 tp view uint 65536 v ulong sel ulong ix ulong dc edit uchar 262144 to int
1257if eq v jsnone
1258ret 0
1259end
1260t = js_type tp v
1261if eq t jsnull
1262ret 0
1263end
1264if eq t jsstr
1265n = js_sget src js_off tp v dc
1266if lt n 0
1267agerr ebad
1268ret 6
1269end
1270if not agapp sel ix dc ulong n
1271agerr elong
1272ret 6
1273end
1274ret 0
1275end
1276if and eq sel 2 eq t jsobj
1277o = js_off tp v
1278sp = js_span tp v
1279for i ulong sp
1280put dc i get src add o i
1281end
1282if not agapp sel ix dc sp
1283agerr elong
1284ret 6
1285end
1286ret 0
1287end
1288agerr ebad
1289ret 6
1290end
1291
1292fn agtcix src view uchar 262144 tp view uint 65536 e ulong pos ulong to ulong
1293xi = agkey src tp e cindex
1294if eq xi jsnone
1295ret pos
1296end
1297if ne js_type tp xi jsnum
1298ret QMAXC
1299end
1300if not js_isu src js_off tp xi
1301ret QMAXC
1302end
1303ret js_tou src js_off tp xi
1304end
1305
1306fn agtcdelta src view uchar 262144 tp view uint 65536 e ulong pos ulong dc edit uchar 262144 to int
1307if ne js_type tp e jsobj
1308agerr ebad
1309ret 6
1310end
1311ix = agtcix src tp e pos
1312if ge ix QMAXC
1313agerr emany
1314ret 6
1315end
1316if ge ix get gst SNC
1317put gst SNC add ix 1
1318end
1319id = agkey src tp e cid
1320if ne id jsnone
1321put gst add SID ix 0
1322end
1323rc = agtcstr src tp id 0 ix dc
1324if ne rc 0
1325ret rc
1326end
1327fu = agkey src tp e cfunc
1328if eq fu jsnone
1329ret 0
1330end
1331if ne js_type tp fu jsobj
1332agerr ebad
1333ret 6
1334end
1335rc = agtcstr src tp agkey src tp fu cname 1 ix dc
1336if ne rc 0
1337ret rc
1338end
1339ret agtcstr src tp agkey src tp fu cargs 2 ix dc
1340end
1341
1342fn agdelta src view uchar 262144 tp view uint 65536 d ulong dc edit uchar 262144 to int
1343if ne js_type tp d jsobj
1344agerr ebad
1345ret 6
1346end
1347c = agkey src tp d ccontent
1348if and ne c jsnone eq js_type tp c jsstr
1349n = js_sget src js_off tp c dc
1350if lt n 0
1351agerr ebad
1352ret 6
1353end
1354l = get gst SCLEN
1355nn = ulong n
1356if gt nn sub QCONC l
1357agerr econt
1358ret 6
1359end
1360for i ulong nn
1361put gcont add l i get dc i
1362end
1363put gst SCLEN add l nn
1364ok = agwr 1 dc 0 nn
1365end
1366tc = agkey src tp d ctoolc
1367if eq tc jsnone
1368ret 0
1369end
1370if eq js_type tp tc jsnull
1371ret 0
1372end
1373if ne js_type tp tc jsarr
1374agerr ebad
1375ret 6
1376end
1377e = js_first tp tc
1378pos = ulong 0
1379while ne e jsnone bound 999999
1380rc = agtcdelta src tp e pos dc
1381if ne rc 0
1382ret rc
1383end
1384e = js_enext tp e
1385pos = add pos 1
1386end
1387ret 0
1388end
1389
1390note agchunk: one parsed JSON object (an SSE event or a whole body) of n bytes in src
1391fn agchunk src view uchar 262144 tp edit uint 65536 n ulong dc edit uchar 262144 to int
1392pr = js_parse src tp n
1393if lt pr 0
1394agerr eevj
1395ret 6
1396end
1397if ne js_type tp 0 jsobj
1398agerr eevj
1399ret 6
1400end
1401if ne agkey src tp 0 cerror jsnone
1402agerr eserr
1403ret 6
1404end
1405ch = agkey src tp 0 cchoices
1406if eq ch jsnone
1407ret 0
1408end
1409if ne js_type tp ch jsarr
1410agerr ebad
1411ret 6
1412end
1413c0 = js_first tp ch
1414if eq c0 jsnone
1415ret 0
1416end
1417if ne js_type tp c0 jsobj
1418agerr ebad
1419ret 6
1420end
1421fr = agkey src tp c0 cfinish
1422if ne fr jsnone
1423if eq js_type tp fr jsstr
1424put gst SFIN 1
1425end
1426end
1427d = agkey src tp c0 cdelta
1428if eq d jsnone
1429d = agkey src tp c0 cmessage
1430end
1431if eq d jsnone
1432ret 0
1433end
1434ret agdelta src tp d dc
1435end
1436
1437fn agrderr n long to int
1438if eq n HETIME
1439agerr etmo
1440ret 5
1441end
1442if eq n HEBIG
1443agerr ebig
1444ret 6
1445end
1446agerr eread
1447ret 5
1448end
1449
1450note agevent: one ready SSE event in lb; 1 at [DONE], 0 to go on, else an exit code
1451fn agevent ss edit ulong 16 lb view uchar 262400 eb edit uchar 262144 tp edit uint 65536 dc edit uchar 262144 to int
1452dl = get ss HSDLEN
1453hssenext ss
1454if eq dl 6
1455if heq view part lb 128 6 cdone
1456ret 1
1457end
1458end
1459if gt dl 262144
1460agerr ebig
1461ret 6
1462end
1463if eq dl 0
1464ret 0
1465end
1466for i ulong dl
1467put eb i get lb add 128 i
1468end
1469ret agchunk eb tp dl dc
1470end
1471
1472note agfeed: feed src[0, gst 40) to the SSE parser; 1 at [DONE], 0 to read on, else an exit code
1473fn agfeed ss edit ulong 16 lb edit uchar 262400 src view uchar 4096 eb edit uchar 262144 tp edit uint 65536 dc edit uchar 262144 to int
1474off = ulong 0
1475while lt off get gst 40 bound 999999
1476c = hssefeed ss lb view part src off sub get gst 40 off
1477if lt c 0
1478agerr ebad
1479ret 6
1480end
1481off = add off ulong c
1482if eq get ss HSRDY 0
1483if eq c 0
1484agerr ebad
1485ret 6
1486end
1487continue
1488end
1489rc = agevent ss lb eb tp dc
1490if ne rc 0
1491ret rc
1492end
1493end
1494ret 0
1495end
1496
1497note agsse: read the SSE body until [DONE] (or the end of the body after a finish_reason)
1498fn agsse cs edit ulong 320 io edit uchar 131072 eb edit uchar 262144 tp edit uint 65536 dc edit uchar 262144 to int
1499ss = new ulong 16 0
1500lb = new uchar 262400 0
1501src = new uchar 4096 0
1502r = hsseinit ss
1503for it ulong 16777216
1504n = hbodyrd cs io src
1505if lt n 0
1506ret agrderr n
1507end
1508if eq n 0
1509break
1510end
1511put gst 40 ulong n
1512rc = agfeed ss lb src eb tp dc
1513if eq rc 1
1514ret 0
1515end
1516if ne rc 0
1517ret rc
1518end
1519end
1520if eq get gst SFIN 0
1521agerr enodone
1522ret 6
1523end
1524ret 0
1525end
1526
1527fn agjsonbody cs edit ulong 320 io edit uchar 131072 eb edit uchar 262144 tp edit uint 65536 dc edit uchar 262144 to int
1528n = hbodyall cs io eb
1529if lt n 0
1530ret agrderr n
1531end
1532ret agchunk eb tp ulong n dc
1533end
1534
1535fn agresp cs edit ulong 320 io edit uchar 131072 sse bool to int
1536eb = new uchar 262144 0
1537tp = new uint 65536 0
1538dc = new uchar 262144 0
1539ri = js_init tp 262144 64
1540if sse
1541ret agsse cs io eb tp dc
1542end
1543ret agjsonbody cs io eb tp dc
1544end
1545
1546fn agissse cs edit ulong 320 io edit uchar 131072 to bool
1547i = hhfind cs io cnctype
1548if lt i 0
1549ret false
1550end
1551vo = hhvoff cs ulong i
1552vl = hhvlen cs ulong i
1553m = len cevs
1554if lt vl m
1555ret false
1556end
1557for s ulong add sub vl m 1
1558if heq view part io add vo s m cevs
1559ret true
1560end
1561end
1562ret false
1563end
1564
1565fn agstatus cs edit ulong 320 io edit uchar 131072 st long to int
1566agerrn estat ulong st
1567b = new uchar 512 0
1568n = hbodyrd cs io b
1569if gt n 0
1570for i ulong ulong n
1571c = get b i
1572if or lt c 32 gt c 126
1573put b i 32
1574end
1575end
1576ok = agwr 2 cpre 0 len cpre
1577ok = agwr 2 b 0 ulong n
1578ok = agwr 2 cnl 0 1
1579end
1580r = hclose cs
1581ret 4
1582end
1583
1584note agconn: connect to ip:port (5 s connect limit) and set idle and body deadlines t (ns)
1585fn agconn cs edit ulong 320 io edit uchar 131072 ip ulong port ulong t long to long
1586a = new uchar 16 0
1587r = haddr4 a uint ip port
1588fd = hdial a 5000000000
1589if lt fd 0
1590ret fd
1591end
1592r = hinit cs io int fd 0
1593hsettmo cs t t
1594hsetbdl cs t
1595ret 0
1596end
1597
1598note agauth: the Authorization header, built in a local that is zeroed before return
1599fn agauth cs edit ulong 320 io edit uchar 131072 r long to long
1600if eq get gnum QHAVEK 0
1601ret r
1602end
1603kb = new uchar 4200 0
1604for i ulong len cbearer
1605put kb i get cbearer i
1606end
1607ko = get gsof IKEY
1608kl = get gsln IKEY
1609for j ulong kl
1610put kb add len cbearer j get gpool add ko j
1611end
1612x = hfe r hhname cs io cauth
1613x = hfe x hhval cs io view part kb 0 add len cbearer kl
1614for z ulong 4200
1615put kb z 0
1616end
1617ret x
1618end
1619
1620fn aghead cs edit ulong 320 io edit uchar 131072 sn ulong to long
1621pb = new uchar 8192 0
1622hh = new uchar 256 0
1623pn = agsget IPATH pb
1624hl = agsget IHOST hh
1625r = hreqst cs io cpost
1626r = hfe r hreqtg cs io view part pb 0 pn
1627r = hfe r hhname cs io chost
1628r = hfe r hhval cs io view part hh 0 hl
1629r = hfe r hhname cs io cctype
1630r = hfe r hhval cs io cjson
1631r = hfe r hhname cs io caccept
1632r = hfe r hhval cs io cevst
1633r = agauth cs io r
1634c = add add len cbody1 get gsln IMODEL add len cbody2 len ctools
1635c = add c add add len cbody3 sn add 1 len cbody4
1636c = add c get gnum QHBL
1637ret hfe r hhend cs io 0 c
1638end
1639
1640fn agbody cs edit ulong 320 io edit uchar 131072 hb view uchar 1048576 wb view uchar 263184 sn ulong r long to long
1641mb = new uchar 256 0
1642mn = agsget IMODEL mb
1643r = hfe r hput cs io cbody1
1644r = hfe r hput cs io view part mb 0 mn
1645r = hfe r hput cs io cbody2
1646r = hfe r hput cs io ctools
1647r = hfe r hput cs io cbody3
1648r = hfe r hput cs io view part wb 1040 sn
1649r = hfe r hput cs io ccomma
1650r = hfe r hput cs io view part hb 0 get gnum QHBL
1651r = hfe r hput cs io cbody4
1652ret hfe r hwfin cs io
1653end
1654
1655note agreq: one chat-completions request (stream: true) over a fresh connection
1656fn agreq cs edit ulong 320 io edit uchar 131072 hb edit uchar 1048576 wb edit uchar 263184 to int
1657sr = agsysmsg wb
1658if lt sr 0
1659agerr emsg
1660ret 9
1661end
1662r = agconn cs io get gnum QIP get gnum QPORT long get gnum QTMO
1663if lt r 0
1664agerr econn
1665ret 3
1666end
1667r = aghead cs io ulong sr
1668r = agbody cs io hb wb ulong sr r
1669if lt r 0
1670x = hclose cs
1671if eq r HETIME
1672agerr etmo
1673ret 5
1674end
1675agerr ewrite
1676ret 3
1677end
1678st = hrsprd cs io
1679if lt st 0
1680x = hclose cs
1681ret agrderr st
1682end
1683if ne st 200
1684ret agstatus cs io st
1685end
1686rc = agresp cs io agissse cs io
1687x = hclose cs
1688ret rc
1689end
1690
1691note ======== tools
1692
1693fn agargstr src view uchar 262144 tp view uint 65536 key view uchar * d edit uchar * to long
1694v = agkey src tp 0 key
1695if eq v jsnone
1696ret -1
1697end
1698if ne js_type tp v jsstr
1699ret -1
1700end
1701n = js_sget src js_off tp v d
1702if lt n 0
1703ret -2
1704end
1705ret n
1706end
1707
1708note agpathok and agcomp, the workspace path rule, are in seed/agent/path.om (composed before this file).
1709
1710fn agtread ab view uchar 262144 tp view uint 65536 to void
1711pb = new uchar 4096 0
1712one = new uchar 1 0
1713n = agargstr ab tp cpath pb
1714if lt n 0
1715agrset 2 rpatharg
1716ret
1717end
1718pn = ulong n
1719if not agpathok view part pb 0 pn
1720agrset 1 rpath
1721ret
1722end
1723fd = fopen pb 0 pn 557056 0
1724if lt fd 0
1725agrerr ropen fd
1726ret
1727end
1728put gnum QTST 0
1729got = ulong 0
1730while lt got QRESC bound 999999
1731r = read int fd gres got sub QRESC got
1732if lt r 0
1733r2 = fclose int fd
1734agrerr rreadf r
1735ret
1736end
1737if eq r 0
1738break
1739end
1740got = add got ulong r
1741end
1742put gnum QRES got
1743if eq got QRESC
1744r3 = read int fd one 0 1
1745if gt r3 0
1746agradd rtrunc
1747end
1748end
1749r4 = fclose int fd
1750end
1751
1752fn agtwrite ab view uchar 262144 tp view uint 65536 to void
1753if eq get gnum QWRITE 0
1754agrset 1 rnowrite
1755ret
1756end
1757pb = new uchar 4096 0
1758cb = new uchar 262144 0
1759n = agargstr ab tp cpath pb
1760if lt n 0
1761agrset 2 rpatharg
1762ret
1763end
1764pn = ulong n
1765if not agpathok view part pb 0 pn
1766agrset 1 rpath
1767ret
1768end
1769cn = agargstr ab tp ccontent cb
1770if lt cn 0
1771agrset 2 rcontarg
1772ret
1773end
1774fd = fopen pb 0 pn 557633 420
1775if lt fd 0
1776agrerr ropen fd
1777ret
1778end
1779p = ulong 0
1780m = ulong cn
1781while lt p m bound 999999
1782w = write int fd cb p sub m p
1783if le w 0
1784r = fclose int fd
1785agrerr rwfail w
1786ret
1787end
1788p = add p ulong w
1789end
1790r2 = fclose int fd
1791agrset 0 rwrote
1792agrnum m
1793agradd rbytes
1794agradd view part pb 0 pn
1795end
1796
1797fn agallowed base ulong cnt ulong a view uchar * to bool
1798for k ulong cnt
1799if agseq add base k a
1800ret true
1801end
1802end
1803ret false
1804end
1805
1806note agspawn: fork and run the packed argv as the leader of a new process group, stdout and
1807note stderr on a close-on-exec pipe and stdin on /dev/null. Both sides call setpgid, so the group
1808note exists before either goes on (as in seed/node/auth.om au_fork). Returns the child pid (the
1809note pipe's read end in gnum 22) or a negative errno
1810fn agspawn pk view uchar 4096 pn ulong to long
1811pf = new uchar 8 0
1812r = pipefds pf 0 8 524288
1813if lt r 0
1814ret r
1815end
1816rfd = int or ulong get pf 0 shl ulong get pf 1 8
1817wfd = int or ulong get pf 4 shl ulong get pf 5 8
1818dn = fopen cdevnull 0 len cdevnull 524288 0
1819pid = fork
1820if eq pid 0
1821r = setpgid 0 0
1822r = dupfd wfd 1 0
1823r = dupfd wfd 2 0
1824if ge dn 0
1825r = dupfd int dn 0 0
1826end
1827r = execprog pk 0 pn
1828exit 127
1829end
1830r = fclose wfd
1831if ge dn 0
1832r = fclose int dn
1833end
1834if lt pid 0
1835r = fclose rfd
1836ret pid
1837end
1838r = setpgid int pid int pid
1839put gnum 22 ulong rfd
1840ret pid
1841end
1842
1843note agreap: reap the direct child without blocking; once it is gone (status in gnum 24, gnum 23
1844note = 1) SIGKILL the rest of its process group, so a grandchild cannot outlive the tool call
1845fn agreap pid int to void
1846ws = new uchar 4 0
1847if ne get gnum 23 0
1848ret
1849end
1850g = waitpid pid ws 0 4 1
1851if eq g long pid
1852put gnum 23 1
1853put gnum 24 or ulong get ws 0 shl ulong get ws 1 8
1854r = killpid neg pid 9
1855end
1856end
1857
1858note agslice: the next wait in ns, the time left to deadline dl at most 50 ms
1859fn agslice dl ulong now ulong to long
1860if gt sub dl now 50000000
1861ret 50000000
1862end
1863ret long sub dl now
1864end
1865
1866note agwaitc: end of file only means every holder closed the pipe, not that the child exited
1867note (coreutils closes stdout before it exits). Reap the direct child first (agreap), polling every
1868note 2 ms until deadline dl, so the group's SIGKILL cannot overtake a child that already finished;
1869note true when the deadline passed first
1870fn agwaitc dl ulong to bool
1871for it ulong 999999999
1872agreap int get gnum 25
1873if ne get gnum 23 0
1874ret false
1875end
1876now = ulong monons
1877if ge now dl
1878ret true
1879end
1880r = sleepns 2000000
1881end
1882ret true
1883end
1884
1885note agdrain: read the child's output into gres (at most 64 KiB kept) until end of file or the
1886note --cmd-timeout deadline; true on timeout. It waits in 50 ms slices and calls agreap between
1887note them (child pid in gnum 25), so after the child exits its group dies and end of file arrives;
1888note at end of file it waits for the child itself (agwaitc)
1889fn agdrain rfd int to bool
1890buf = new uchar 4096 0
1891put gnum QRES 0
1892put gnum 23 0
1893dl = add ulong monons get gnum QCTMO
1894for it ulong 999999
1895now = ulong monons
1896if ge now dl
1897ret true
1898end
1899wv = waitio rfd 1 agslice dl now
1900if eq wv 0
1901agreap int get gnum 25
1902continue
1903end
1904n = read rfd buf 0 4096
1905if eq n 0
1906ret agwaitc dl
1907end
1908if lt n 0
1909if or eq n -4 eq n -11
1910continue
1911end
1912ret false
1913end
1914for i ulong ulong n
1915if lt get gnum QRES QRESC
1916put gres get gnum QRES get buf i
1917put gnum QRES add get gnum QRES 1
1918end
1919end
1920end
1921ret true
1922end
1923
1924note agexec: run the packed argv, collect its output and reap it. At the --cmd-timeout deadline
1925note the child's whole process group gets SIGKILL; when the child exits first, agdrain kills the
1926note group's remaining members, so no tool grandchild outlives the call either way
1927fn agexec pk view uchar 4096 pn ulong to void
1928ws = new uchar 4 0
1929pid = agspawn pk pn
1930if lt pid 0
1931agrset 2 rpipe
1932ret
1933end
1934rfd = int get gnum 22
1935put gnum QTST 0
1936put gnum 25 ulong pid
1937tmo = agdrain rfd
1938r = killpid neg int pid 9
1939if eq get gnum 23 0
1940r = waitpid int pid ws 0 4 0
1941put gnum 24 or ulong get ws 0 shl ulong get ws 1 8
1942end
1943r = fclose rfd
1944if ge get gnum QRES QRESC
1945agradd rtrunc
1946end
1947if tmo
1948put gnum QTST 2
1949agradd rtmo
1950agrnum div get gnum QCTMO 1000000000
1951agradd rsec
1952ret
1953end
1954wst = get gnum 24
1955if ne and wst 127 0
1956put gnum QTST 2
1957agradd rsig
1958agrnum and wst 127
1959agradd rclose
1960ret
1961end
1962agradd rexit
1963agrnum and shr wst 8 255
1964agradd rclose
1965end
1966
1967fn agtrun ab view uchar 262144 tp view uint 65536 to void
1968nc = get gnum QNCMD
1969if eq nc 0
1970agrset 1 rnocmd
1971ret
1972end
1973av = agkey ab tp 0 cargv
1974if eq av jsnone
1975agrset 2 rargv
1976ret
1977end
1978if ne js_type tp av jsarr
1979agrset 2 rargv
1980ret
1981end
1982nel = js_nkids tp av
1983if or eq nel 0 gt nel 63
1984agrset 2 rargv
1985ret
1986end
1987pk = new uchar 4096 0
1988e1 = new uchar 4096 0
1989w = ulong 2
1990e = js_first tp av
1991for k ulong nel
1992if ne js_type tp e jsstr
1993agrset 2 rargv
1994ret
1995end
1996n = js_sget ab js_off tp e e1
1997if lt n 0
1998agrset 1 rpack
1999ret
2000end
2001w = agpack pk w e1 ulong n k
2002if eq w 0
2003ret
2004end
2005e = js_enext tp e
2006end
2007put pk 0 uchar nel
2008put pk 1 0
2009agexec pk w
2010end
2011
2012note agpack: append argument k (e1[0, m)) to the packed list at w; the new end, or 0 with the
2013note refusal already in gres
2014fn agpack pk edit uchar 4096 w ulong e1 view uchar 4096 m ulong k ulong to ulong
2015for z ulong m
2016if eq get e1 z 0
2017agrset 1 rnul
2018ret 0
2019end
2020end
2021if eq k 0
2022if or eq m 0 not agallowed ICMD get gnum QNCMD view part e1 0 m
2023agrset 1 rnotal
2024agradd view part e1 0 m
2025ret 0
2026end
2027end
2028if gt add add w 2 m 4096
2029agrset 1 rpack
2030ret 0
2031end
2032put pk w uchar and m 255
2033put pk add w 1 uchar shr m 8
2034b = add w 2
2035for j ulong m
2036put pk add b j get e1 j
2037end
2038ret add b m
2039end
2040
2041fn agtfetch ab view uchar 262144 tp view uint 65536 to void
2042nf = get gnum QNFET
2043if eq nf 0
2044agrset 1 rnofet
2045ret
2046end
2047ub = new uchar 4096 0
2048n = agargstr ab tp curl ub
2049if lt n 0
2050agrset 2 rurlarg
2051ret
2052end
2053un = ulong n
2054r = new ulong 8 0
2055rc = agurl view part ub 0 un r
2056if eq rc -1
2057agrset 1 rnohttp
2058ret
2059end
2060if lt rc 0
2061agrset 2 rurlbad
2062ret
2063end
2064cn = new uchar 300 0
2065cl = agcanon ub r cn
2066if not agallowed IFET nf view part cn 0 cl
2067agrset 1 rnotfa
2068agradd view part cn 0 cl
2069ret
2070end
2071agfetch1 ub r
2072end
2073
2074note agcanon: HOST:PORT of a parsed url (the port always written), for the --allow-fetch check
2075fn agcanon ub view uchar 4096 r view ulong 8 cn edit uchar 300 to ulong
2076d = new uchar 24 0
2077hl = get r 6
2078if gt hl 255
2079hl = 255
2080end
2081b = get r 2
2082for i ulong hl
2083put cn i get ub add b i
2084end
2085put cn hl 58
2086dn = agdec get r 1 d
2087b = add hl 1
2088for j ulong dn
2089put cn add b j get d j
2090end
2091ret add b dn
2092end
2093
2094note agfreq: send GET for the parsed url and read the status line and headers
2095fn agfreq cs edit ulong 320 io edit uchar 131072 ub view uchar 4096 r view ulong 8 to long
2096x = agconn cs io get r 0 get r 1 long get gnum QCTMO
2097if lt x 0
2098ret -1000
2099end
2100x = hreqst cs io cget
2101if eq get r 5 0
2102x = hfe x hreqtg cs io cslash
2103else
2104x = hfe x hreqtg cs io view part ub get r 4 get r 5
2105end
2106x = hfe x hhname cs io chost
2107x = hfe x hhval cs io view part ub get r 2 get r 3
2108x = hfe x hhend cs io 0 0
2109x = hfe x hwfin cs io
2110if lt x 0
2111ret x
2112end
2113ret hrsprd cs io
2114end
2115
2116note agfbody: append the response body to gres (64 KiB kept)
2117fn agfbody cs edit ulong 320 io edit uchar 131072 to void
2118b = new uchar 4096 0
2119for it ulong 999999
2120n = hbodyrd cs io b
2121if le n 0
2122if eq n HETIME
2123put gnum QTST 2
2124agradd rftmo
2125end
2126ret
2127end
2128for i ulong ulong n
2129if lt get gnum QRES QRESC
2130put gres get gnum QRES get b i
2131put gnum QRES add get gnum QRES 1
2132end
2133end
2134if ge get gnum QRES QRESC
2135agradd rtrunc
2136ret
2137end
2138end
2139end
2140
2141fn agfetch1 ub view uchar 4096 r view ulong 8 to void
2142cs = new ulong 320 0
2143io = new uchar 131072 0
2144st = agfreq cs io ub r
2145if eq st -1000
2146agrset 2 rconn
2147ret
2148end
2149if lt st 0
2150y = hclose cs
2151if eq st HETIME
2152agrset 2 rftmo
2153ret
2154end
2155agrset 2 rfreq
2156ret
2157end
2158agrset 0 rstatus
2159agrnum ulong st
2160agradd cnl
2161agfbody cs io
2162y = hclose cs
2163end
2164
2165fn agtoolid nm view uchar * to ulong
2166if heq nm tnread
2167ret 1
2168end
2169if heq nm tnwrite
2170ret 2
2171end
2172if heq nm tnrun
2173ret 3
2174end
2175if heq nm tnfetch
2176ret 4
2177end
2178ret 0
2179end
2180
2181note agcall: run tool call c; its result is left in gres/QRES (valid UTF-8), its status in QTST.
2182note stderr names the tool and the status only, never arguments or results.
2183fn agcall c ulong to void
2184ab = new uchar 262144 0
2185tp = new uint 65536 0
2186nm = new uchar 128 0
2187ri = js_init tp 262144 64
2188nl = get gst add SNM c
2189for j ulong nl
2190put nm j get gtnm add mul c 128 j
2191end
2192an = get gst add SARG c
2193for i ulong an
2194put ab i get gtarg add mul c 65536 i
2195end
2196put gnum QRES 0
2197which = agtoolid view part nm 0 nl
2198if eq which 0
2199agrset 1 runknown
2200agradd view part nm 0 nl
2201else
2202pr = js_parse ab tp an
2203if or lt pr 0 ne js_type tp 0 jsobj
2204agrset 2 rnoargs
2205else
2206if eq which 1
2207agtread ab tp
2208end
2209if eq which 2
2210agtwrite ab tp
2211end
2212if eq which 3
2213agtrun ab tp
2214end
2215if eq which 4
2216agtfetch ab tp
2217end
2218end
2219end
2220agu8fix
2221ok = agwr 2 cpre 0 len cpre
2222ok = agwr 2 ltool 0 len ltool
2223ok = agwr 2 nm 0 nl
2224s = get gnum QTST
2225if eq s 0
2226ok = agwr 2 lok 0 len lok
2227end
2228if eq s 1
2229ok = agwr 2 lref 0 len lref
2230end
2231if eq s 2
2232ok = agwr 2 lerr 0 len lerr
2233end
2234ok = agwr 2 cnl 0 1
2235end
2236
2237note ======== the agent loop
2238
2239fn agturn ub view uchar 65536 un ulong hb edit uchar 1048576 wb edit uchar 263184 cs edit ulong 320 io edit uchar 131072 to int
2240agtrim
2241agcompact hb
2242agwuser wb ub un
2243rc = agappend wb hb 1
2244if ne rc 0
2245ret rc
2246end
2247mr = get gnum QROUND
2248for k ulong mr
2249for i ulong 64
2250put gst i 0
2251end
2252rc = agreq cs io hb wb
2253if ne rc 0
2254if gt get gst SCLEN 0
2255ok = agwr 1 cnl 0 1
2256end
2257ret rc
2258end
2259agfixids
2260agwasst wb
2261nc = get gst SNC
2262role = ulong 2
2263if gt nc 0
2264role = 5
2265end
2266rc = agappend wb hb role
2267if ne rc 0
2268ret rc
2269end
2270if eq nc 0
2271ok2 = agwr 1 cnl 0 1
2272ret 0
2273end
2274if gt get gst SCLEN 0
2275ok3 = agwr 1 cnl 0 1
2276end
2277for c ulong nc
2278agcall c
2279agwtool wb c
2280rc = agappend wb hb 3
2281if ne rc 0
2282ret rc
2283end
2284end
2285end
2286agerr eround
2287ret 7
2288end
2289
2290note agline: the next stdin line (CR LF or LF) into ub; -1 at the end of input, -2 too long
2291fn agline ub edit uchar 65536 to long
2292for it ulong 999999
2293l = get gnum QINL
2294p = get gnum QINP
2295for i ulong sub l p
2296if eq get gin add p i 10
2297n = i
2298if and gt n 0 eq get gin add p sub n 1 13
2299n = sub n 1
2300end
2301for j ulong n
2302put ub j get gin add p j
2303end
2304put gnum QINP add add p i 1
2305ret long n
2306end
2307end
2308if eq get gnum QINEOF 1
2309if eq p l
2310ret -1
2311end
2312n2 = sub l p
2313for j2 ulong n2
2314put ub j2 get gin add p j2
2315end
2316put gnum QINP l
2317ret long n2
2318end
2319if gt p 0
2320for m ulong sub l p
2321put gin m get gin add p m
2322end
2323put gnum QINL sub l p
2324put gnum QINP 0
2325end
2326l2 = get gnum QINL
2327if ge l2 65535
2328ret -2
2329end
2330r = read 0 gin l2 sub 65535 l2
2331if le r 0
2332put gnum QINEOF 1
2333else
2334put gnum QINL add l2 ulong r
2335end
2336end
2337ret -1
2338end
2339
2340fn agchdir to int
2341if eq get gsln IWORK 0
2342ret 0
2343end
2344pb = new uchar 4096 0
2345pn = agsget IWORK pb
2346c = chdir pb 0 pn
2347if lt c 0
2348agerr ework
2349ret 2
2350end
2351ret 0
2352end
2353
2354fn main to int
2355cs = new ulong 320 0
2356io = new uchar 131072 0
2357hb = new uchar 1048576 0
2358wb = new uchar 263184 0
2359ub = new uchar 65536 0
2360r = agargs
2361if eq r 1
2362ret 0
2363end
2364if ne r 0
2365ret r
2366end
2367r = agkeyload
2368if ne r 0
2369ret r
2370end
2371r = agmemload
2372if ne r 0
2373ret r
2374end
2375r = agsload hb
2376if ne r 0
2377ret r
2378end
2379r = agchdir
2380if ne r 0
2381ret r
2382end
2383if gt get gsln IPROMPT 0
2384un = agsget IPROMPT ub
2385ret agturn ub un hb wb cs io
2386end
2387for it ulong 999999
2388n = agline ub
2389if eq n -1
2390ret 0
2391end
2392if eq n -2
2393agerr emsg
2394ret 9
2395end
2396if gt n 0
2397rc = agturn ub ulong n hb wb cs io
2398if ne rc 0
2399ret rc
2400end
2401end
2402end
2403ret 0
2404end