examples/ai/bridge.c
/* Linux extension ABI v1. Only the named Python worker runs, without a shell. */
#define _POSIX_C_SOURCE 200809L
#include "basalt_module.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
static uint64_t invoke(const BasaltAPI *api,const uint64_t *args,size_t count,
const char *action,int has_number) {
if (api->version!=1 || count!=(has_number?3u:2u)) return 0;
char *text[2]={NULL,NULL};
uint64_t result=0;
for (size_t i=0;i<2;i++) {
size_t n;
const unsigned char *p=api->view(args[i],&n);
if (n>8192 || memchr(p,0,n)) goto done;
text[i]=malloc(n+1);
if (!text[i]) goto done;
memcpy(text[i],p,n); text[i][n]=0;
}
char number[32];
if (has_number) snprintf(number,sizeof number,"%llu",(unsigned long long)args[2]);
const char *python=getenv("BASALT_AI_PYTHON"), *worker=getenv("BASALT_AI_WORKER");
if (!python || !*python) python="python3";
if (!worker || !*worker) worker="qwen_worker.py";
int fd[2];
if(pipe(fd)<0) goto done;
pid_t pid=fork();
if(pid==0){
close(fd[0]);
if(dup2(fd[1],STDOUT_FILENO)<0) _exit(126);
close(fd[1]);
execlp(python,python,worker,action,text[0],text[1],has_number?number:NULL,(char *)NULL);
_exit(127);
}
close(fd[1]);
if(pid<0){close(fd[0]);goto done;}
unsigned char output[65536], chunk[2048];
size_t used=0;
int ok=1,status=0;
for (;;) {
ssize_t n=read(fd[0],chunk,sizeof chunk);
if(n<0 && errno==EINTR) continue;
if(n<=0){if(n<0) ok=0;break;}
if((size_t)n>sizeof output-used){ok=0;continue;}
memcpy(output+used,chunk,(size_t)n); used+=(size_t)n;
}
close(fd[0]);
pid_t waited;
do {waited=waitpid(pid,&status,0);} while(waited<0 && errno==EINTR);
if(ok && waited==pid && WIFEXITED(status) && WEXITSTATUS(status)==0 && used)
result=api->copy(output,used);
done:
free(text[0]);free(text[1]);return result;
}
uint64_t QwenTrain(const BasaltAPI *a,const uint64_t *v,size_t n){return invoke(a,v,n,"train",1);}
uint64_t QwenPredict(const BasaltAPI *a,const uint64_t *v,size_t n){return invoke(a,v,n,"predict",0);}
uint64_t QwenGenerate(const BasaltAPI *a,const uint64_t *v,size_t n){return invoke(a,v,n,"generate",1);}