46 Commits

Author SHA1 Message Date
andrea.difonzo
4ba28b130b aKode 0.9.1: annunci non eseguiti alla prima persona plurale e al futuro (procediamo, proverò, creerò…)
Visto con Qwen3-Coder-30B-A3B: «Procediamo con una versione semplificata…» chiudeva il
turno senza chiamare strumenti; il sollecito unico ora lo riconosce. Test aggiunto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:01:53 +01:00
andrea.difonzo
2d933d0926 aKode 0.9.1: immagini degli strumenti in un messaggio utente, errore 500 chiamato per nome
- view_image con server llama.cpp/ik_llama.cpp: l'immagine dentro function_call_output
  faceva rispondere 500 ("Output of tool call should be 'Input text'") e chiudeva il
  turno con un errore (prove s2/s3 di Fourier). Con merge_system_messages l'output resta
  testo con un segnaposto e l'immagine segue in un messaggio utente (verificato sul
  server: 500 prima, risposta corretta dopo).
- Il messaggio per HTTP 500 non parla più di «high demand».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 01:20:19 +01:00
andrea.difonzo
a1a92535bb aKode 0.9.1: Novità nel README (escalation in sandbox, note sulla sandbox, marchio nelle approvazioni)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:55:22 +01:00
andrea.difonzo
45762fc826 aKode 0.9.1: escalation non concedibile eseguita in sandbox, avvisi di errore più leggibili
- Se la politica di approvazione non permette di chiedere l'esecuzione fuori dalla
  sandbox (per esempio nelle cartelle senza progetto), il comando gira nella sandbox
  invariata con una nota per il modello invece di essere rifiutato: nessun permesso in
  più, ma il modello non si arrende (prova di Fourier: Qwen rinunciava a creare .venv).
  Test di sicurezza adattati: verificano che il comando non esca dalla sandbox.
- Righe «✗» più leggibili per escalation non consentita, righe di patch non trovate e
  hunk non validi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 00:15:34 +01:00
andrea.difonzo
34587f89c4 aKode 0.9.1: versione, marchio aKode nelle approvazioni, indicazioni sulla sandbox al modello
- Versione 0.9.1 (snapshot della TUI aggiornate).
- Testi delle approvazioni e delle revisioni: «aKode» invece di «codex».
- Escalation rifiutata dalla politica di approvazione: il messaggio spiega cosa fare
  (installare le dipendenze nel progetto, per esempio in .venv) invece di arrendersi.
- Scrittura negata dalla sandbox ("Operation not permitted"): nota al modello su dove
  può scrivere e come installare le dipendenze in locale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:35:38 +01:00
andrea.difonzo
3df68b5842 aKode 0.9.1: correzioni dalla prova di Fourier (apply_patch, write_file, errori visibili, rete dei pacchetti)
- apply_patch tollerante: aggiunge '*** Begin Patch'/'*** End Patch' mancanti quando
  il contenuto inizia con Add/Update/Delete File, toglie i recinti ```; ogni altra
  ambiguità resta un errore; riga con il formato e un esempio negli errori di formato.
- Strumento write_file (path + contenuto) sulla pipeline di apply_patch (stesse
  verifiche, sandbox, approvazioni e hook), [tools] write_file (predefinito attivo);
  dopo la scrittura ricorda al modello di verificare il file.
- Chiamate a strumento fallite visibili nella TUI ("✗ strumento: motivo · riprovo").
- Avanzamento mentre il modello scrive una chiamata lunga ("Scrivo file · N token")
  e stato del gateway imeAI ("In coda…", "Leggo il prompt · 42%").
- write_stdin con id inesistente: elenca le sessioni aperte e indica exec_command o
  write_file; descrizione più chiara.
- Protezione dai loop: un avviso al modello prima di fermare il turno.
- Sandbox predefinita: rete attiva solo verso i registri dei pacchetti attraverso il
  proxy di rete ([features.network_proxy] nei default impacchettati); scritture
  invariate; nota al modello sugli errori di rete in sandbox.
- Testi della TUI in italiano (benvenuto, segnaposto, suggerimenti, «Errore fatale»).
- Test adattati ai nuovi default (rete del profilo :workspace, allowlist), snapshot e
  schemi rigenerati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:01:42 +01:00
andrea.difonzo
1c278642de aKode 0.9.0: versione, Novità nel README, repository rinominato in imeai-aKode, snapshot della TUI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:06:29 +01:00
andrea.difonzo
0460c74f38 aKode: robustezza dell'agente (punto 4, blocco B)
- Compattazione: prima del riassunto l'output degli strumenti più vecchi
  (tutti tranne gli ultimi 3, sopra i 400 caratteri) diventa un segnaposto
  breve; le chiamate restano. La compattazione usa sempre il provider
  configurato: verificato, con un test sulle capacità dei provider.
- Protezione dai loop in stile Gemini CLI, accanto a max_repeated_failures:
  [agent] max_identical_tool_calls (5 risposte di fila con la stessa chiamata,
  qualunque sia il risultato; esclusi write_stdin e wait_agent; le chiamate
  parallele di una risposta contano una volta) e [agent] max_repeated_text
  (lo stesso testo ripetuto 10 volte di seguito mentre arriva, nella risposta
  o nel ragionamento; esclusi blocchi di codice e separatori).
- Cancellazioni ricorsive protette (rm -r, rm -rf, find -delete): radice,
  home, radice del repository, cartella di lavoro, percorsi fuori da essa o
  calcolati a runtime ($VAR, $(...), xargs) chiedono sempre la conferma
  dell'utente, anche con regole che li permetterebbero; in accesso completo
  vengono rifiutati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:59:19 +01:00
andrea.difonzo
4e1f551b84 aKode: cache del prompt più stabile e attese lunghe dei server locali (punto 4, blocco A)
- Ordine fisso dei blocchi di contesto: le sezioni uguali in ogni sessione
  (skill, permessi) vengono prima, quelle delle estensioni (<code_map>,
  riepilogo della memoria) dopo; prima <code_map> stava subito dopo le
  istruzioni di sistema e cambiava da un repository all'altro.
- Strumenti in ordine stabile (per nome, namespace dopo); nella sessione resta
  l'ordine della prima richiesta e i nuovi strumenti vanno in coda, mai in mezzo.
- La prima richiesta aspetta fino a 5 s (prima 1 s) i server MCP in avvio.
- Ogni byte ricevuto azzera il timer di inattività: commenti SSE ed eventi
  imeai.queue/imeai.prefill compresi. Il timeout vale anche per l'attesa delle
  intestazioni ed è di 30 minuti per i server locali (5 per gli altri).
- Niente keepalive TCP nel client HTTP: reqwest sonda dopo 15 s e chiude dopo
  3 sonde senza risposta; attraverso NetBird le sonde non passano e ogni
  risposta partita dopo 60 s veniva tagliata e richiesta da capo.
- Test adattati al nuovo ordine degli strumenti (snapshot con soli riordini) e
  alla nuova attesa dei server MCP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 17:59:12 +01:00
andrea.difonzo
437c6b7f5a aKode 0.8.0: paragrafo code_graph nelle istruzioni di sistema (approvato dall'utente), note nel README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:05:19 +01:00
andrea.difonzo
83959bccd0 aKode 0.8.0: grafo del codice locale (tree-sitter + git) e strumento code_graph, memorie ancorate ai simboli con stato stale, client MCP akode-mcp-client
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:14:42 +01:00
andrea.difonzo
b87057603d aKode 0.7.0: header di sessione solo ai provider locali, frase d'identità precisata
- session-id, thread-id e x-client-request-id (HTTP e handshake WebSocket) vanno solo ai provider
  locali o in LAN, come client_metadata; test client_tests::session_headers_are_sent_only_to_local_providers.
- Istruzioni di sistema (default.md e models-manager/prompt.md, identici): solo la frase d'identità,
  ora «fork privato dell'utente di un agente di coding open source, sul suo server imeAI»; nessuna
  attribuzione a imeAI o ad aziende (5/5).
- Versione 0.7.0, Novità nel README, snapshot della TUI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 05:42:46 +01:00
andrea.difonzo
42f6ee7d5a aKode 0.6.0: versione, Novità nel README, snapshot della TUI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:49:51 +01:00
andrea.difonzo
6d4c830805 aKode: consegna delle sessioni al server memoria (memory_ingest_session)
- ext/memoria: trascrizione compatta e cumulativa del thread (utente, risposte
  finali senza commentary, comandi con output troncato a ~1500 caratteri,
  file modificati, ricerche web, altri server MCP; le chiamate al server
  memoria sono ignorate), limite di ~150k caratteri tenendo il primo
  messaggio e i turni più recenti, external_context (web, other_mcp).
- Consegna con reason "idle" dopo `[memoria] deliver_idle_minutes` minuti di
  inattività (predefinito 10, il timer si annulla a ogni nuovo turno) e con
  reason "end" alla chiusura del thread (al massimo 5 s, poi rinuncia).
  Solo se ci sono turni nuovi dall'ultima consegna accettata (queued,
  duplicate, skipped); `[memoria] deliver_sessions = false` la spegne. Solo
  thread dell'utente, con il plugin memoria attivo e il server pronto.
- akode-mcp: McpResourceClient::call_tool e McpConnectionSet::call_host_tool
  per le chiamate dell'host a strumenti non elencati e fuori dal filtro
  enabled_tools (il filtro resta per il modello).
- extension-api: on_thread_closing, chiamato a inizio chiusura quando i server
  MCP sono ancora connessi (on_thread_stop arriva dopo il loro arresto).
- Test sul modello di ext/memoria/src/tests.rs: ruoli, compattazione,
  esclusione del server memoria, external_context, nessuna consegna senza
  turni nuovi, errori, timer di inattività; test del percorso host in
  akode-mcp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:49:51 +01:00
andrea.difonzo
854c7a66c9 aKode: rimossa la memoria nativa di Codex e le funzioni senza codice; meno chiamate al modello
Memoria nativa (memories) rimossa del tutto:
- features: memories, memory_tool, external_agent_memory_import, chronicle
  (alias telepathy) diventano Removed; le chiavi restano accettate e
  memories/memory_tool/[memories] producono un solo avviso senza link
  («La sezione [memories] e la chiave memory_tool non sono più usate da
  aKode: la memoria a lungo termine è il plugin memoria di imeAI.»).
- Tolti i crate memories/read, memories/write ed ext/memories, l'avvio
  della pipeline a ogni turno (app-server), l'estensione, /memories e la
  richiesta di attivazione nella TUI, `akode debug clear-memories`,
  l'importazione delle memorie da altri agenti (memory_import.rs,
  detect/memory.rs; il resto di /import resta).
- core: niente più MemoriesConfig, citazioni delle memorie, metriche e
  marcatura «polluted» dei thread; [memories] (MemoriesToml) resta solo
  come sezione accettata e ignorata.
- state: memories_1.sqlite e memories_v2_1.sqlite non vengono più aperti né
  cancellati; la colonna threads.memory_mode resta, nessuna migrazione.
- Protocollo app-server invariato per compatibilità col daemon:
  memory/reset risponde «non supportato» senza cancellare nulla,
  memory/status non è mai pronto, thread/memory/read non ha riassunto.

Altre rimozioni:
- I 14 flag dell'app desktop di OpenAI senza codice (tool_suggest,
  in_app_*, browser_use*, computer_use, bedrock_setup_wizard,
  workspace_dependencies) e analytics_plan_history: Removed, chiavi
  accettate; analytics_plan_history esce da /experimental.
- Skill: tolto l'esperimento «shadow selection» e i selettori collegati.

Meno chiamate al modello non richieste:
- Titoli dei thread: il primo messaggio dell'utente su una riga, troncato a
  36 caratteri; `[tui] auto_title = true` riattiva i titoli generati.
- `[tui] auto_recap` predefinito false; `goals` spento di default.

Privacy: installation_id e gli id di sessione/thread/finestra (e il blocco
dei metadati del turno che li ripete) vanno in client_metadata e negli
header di compatibilità solo ai provider locali (loopback, IP privati
10/8, 172.16/12, 192.168/16, host .local/.lan).

Domini OpenAI: tolti i link visibili (avviso dei flag deprecati, profili,
bubblewrap), l'attribuzione Codex nei commit (sempre spenta), la
riscrittura dell'URL della documentazione OpenAI via MCP e la
registrazione remota dell'exec-server verso host OpenAI (ora solo
loopback); il riconoscimento delle destinazioni OpenAI confronta i domini
etichetta per etichetta. Il binario non contiene più «openai.com» né
«chatgpt.com».

Test adattati (sicurezza compresa: guardian, ruolo ostile, exec-server
ora più restrittivo); rimossi solo quelli del codice tolto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:49:41 +01:00
andrea.difonzo
0da982206c aKode: identità esplicita nelle istruzioni di sistema
Aggiunta in cima a default.md e models-manager/prompt.md (identici) la frase
che chiede al modello di presentarsi come aKode, agente privato sul server
imeAI dell'utente, senza attribuirsi altri prodotti o aziende.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 23:02:38 +01:00
andrea.difonzo
95f4ddcd72 aKode 0.5.0: riepilogo della memoria a inizio sessione, sollecito alle azioni annunciate, daemon allineato al CLI
- ext/memoria: legge una volta per sessione la risorsa memoria://briefing
  (file di git status, budget di token, timeout breve), accetta solo un
  blocco <memoria_briefing> chiuso e limitato, lo inserisce dopo le istruzioni
  del plugin e lo tiene in cache per il thread (prefisso del prompt stabile).
  Impostazioni [memoria] briefing, briefing_timeout_ms, briefing_max_tokens.
- Turno: se il modello chiude con un messaggio che annuncia un'azione senza
  chiamare strumenti, un solo sollecito per turno ([agent] announce_nudges,
  predefinito 1, 0 lo disattiva), con avviso visibile e test sui messaggi
  osservati con Qwen.
- Daemon: sync_with_cli confronta l'eseguibile del CLI con il pacchetto del
  daemon e, se diverso, lo seleziona e riavvia solo quando non ci sono
  sessioni caricate; altrimenti avviso. Usato all'avvio della TUI, da
  `akode update`, da install.sh e da `akode app-server daemon update
  --from-cli --if-idle`. Prima un daemon preparato una volta restava alla
  versione vecchia (CLI 0.4.0 con app server 0.3.1).
- Test: snapshot del doctor indipendenti dalla versione; snapshot della TUI
  aggiornati alla 0.5.0 e allo schema dei tool appiattiti della 0.4.0.
- Versione 0.5.0 e sezione Novità nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:49:51 +01:00
andrea.difonzo
546bd1da18 aKode 0.4.0: plugin memoria di imeAI
Versione 0.4.0 e voce nel README (plugin memoria, project_header,
pollutes_memory, token MCP dal portachiavi, tool namespace appiattiti,
avviso per server MCP irraggiungibili).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:17:42 +01:00
andrea.difonzo
c82e09f0ff aKode: tolti dai suggerimenti della TUI i link a community.openai.com e developers.openai.com
Visto nel test end-to-end (suggerimento all'avvio «Visit the Codex community
forum»): erano rimasti due suggerimenti con link a siti OpenAI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:11:19 +01:00
andrea.difonzo
ea5eef634a aKode: avviso chiaro per i server MCP irraggiungibili in exec e login mcp:<server> senza avviso fuorviante
Trovati nel test end-to-end del plugin memoria con imeAI:
- `akode exec` ignorava mcpServer/startupStatus/updated: se il server MCP non
  rispondeva restavano solo le righe ERROR di rmcp. Ora l'uscita testuale
  stampa «warning: MCP server `memoria` is not reachable (...); aKode continues
  without its tools.» e quella JSON un elemento error; il filtro di exec lascia
  passare gli aggiornamenti del thread principale (o senza thread).
- `akode login --provider mcp:<server> --with-api-key` avvisava che il
  provider di modelli `mcp:<server>` non era in config.toml e suggeriva una
  sezione [model_providers.mcp:<server>] sbagliata; ora spiega che la chiave è
  il Bearer del server MCP. Gli avvisi per i provider di modelli restano.
- prove: messaggio e silenzio per gli altri stati, filtro per thread,
  avvisi di login per mcp: e per provider sconosciuti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:56:48 +01:00
andrea.difonzo
a005236bcb aKode: integrazione della memoria di imeAI (plugin memoria)
- nuovo crate ext/memoria: aggiunge le istruzioni del plugin (instructions.md)
  come developer policy solo se il plugin memoria è abilitato e il suo server
  MCP è pronto; nessuna modifica alle istruzioni di base, [features] memories
  resta spento
- pollutes_memory configurabile per server MCP (predefinito true)
- project_header per i server HTTP: progetto ricavato dalla cartella della
  sessione (origin come host/owner/repo, altrimenti la cartella), connessioni
  separate per progetto
- token Bearer dei server MCP anche dal portachiavi di aKode, solo sotto
  mcp:<server> (mai le chiavi dei provider dei modelli)
- tool namespace (MCP, multi-agente) appiattiti in <namespace>__<tool> per i
  server compatibili OpenAI che accettano solo function tool (llama.cpp,
  ik_llama.cpp, vLLM li scartavano); capacità del provider tool_namespaces
- prove: parsing e propagazione, intestazione del progetto, iniezione solo se
  attivo e connesso, appiattimento e mappatura delle chiamate, chiavi dei
  provider mai consegnate ai server MCP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:55:21 +01:00
andrea.difonzo
2743e4c383 aKode 0.3.2: istruzioni di sistema aggiornate ed etichetta akode in exec
- Istruzioni di sistema: aggiunta una frase sul formato di apply_patch
  (*** Begin Patch / *** End Patch), in default.md e prompt.md.
- Output leggibile di `akode exec`: i messaggi dell'agente sono etichettati
  «akode» invece di «codex».
- Snapshot core rigenerato con le nuove istruzioni.
- Versione 0.3.2 e voce nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:59:22 +01:00
andrea.difonzo
10ede7393f aKode: nuove istruzioni di sistema (circa 1000 parole, identità aKode, agisci senza annunciare, risposta nella lingua dell'utente); originali di Codex salvate in codex-original.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:31:25 +01:00
andrea.difonzo
973acc59c9 aKode 0.3.1: Shift+Tab a tre modalità e topic di Telegram più puliti
- Shift+Tab: default, plan, accesso completo (preset di /permissions,
  saltato se i requisiti non lo permettono; uscendo tornano i permessi
  di prima). Modalità sotto il riquadro di scrittura, a sinistra, e in
  /stato su Telegram.
- Telegram: topic creato al primo turno; sessioni chiuse senza turni
  perdono il topic, le altre diventano «(chiusa)» con nuovi tentativi;
  topic di «Nuova chat» assegnati con i pulsanti, i comandi lì ricevono
  risposta nella chat principale; pulizia all'avvio.
- Versione 0.3.1 e novità nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:46:19 +01:00
andrea.difonzo
b04b36fa53 aKode 0.3.0: controllo da Telegram
- Versione del workspace a 0.3.0 (Cargo.lock compreso).
- README: sezione «Controllo da Telegram» con la configurazione
  (BotFather, Threaded Mode, /telegram) e novità della 0.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:33:29 +01:00
andrea.difonzo
2b8d77593d Telegram: un topic per sessione, streaming, pulsanti e impostazioni
- Menu comandi (setMyCommands, chat private): /sessioni /nuova /stato /stop
  /impostazioni /aiuto; /usa rimosso.
- Un topic per sessione (createForumTopic in chat privata), nome
  "<cartella> · <modello>", rinominato al cambio di modello e "(chiusa)" alla
  chiusura; mappa salvata in AKODE_HOME/telegram-topics.json. Senza topic:
  prefisso [cartella · modello] e scelta della sessione con pulsanti.
- /sessioni con Apri (link al topic), Stato e Stop; il messaggio si aggiorna
  modificandolo.
- Streaming con sendMessageDraft (can_stop, al massimo 1/s, stop = interrompe
  il turno), messaggio finale con piede "ctx · t/s · durata".
- Approvazioni con pulsanti colorati, poi un pulsante disattivato con l'esito.
- Piano come elenco modificato; reazioni ricevuto/fatto configurabili.
- /impostazioni con interruttori Sì/No salvati in [telegram]
  (streaming, reactions nuovi).
- Messaggi modificati: un comando modificato riparte, il testo no.
- Pulsanti con token opachi lato server; allowlist anche sui pulsanti.
- Nessuna emoji nei testi in uscita (test dedicato).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:12:01 +01:00
andrea.difonzo
466ed04fba aKode: controllo delle sessioni da Telegram (completo e verificato)
Il contenuto è nel commit 28bddb1b (salvato come WIP durante la pausa):
- crate akode-telegram: Bot API (solo api.telegram.org, errori senza URL/token),
  [telegram] in config.toml, token nell'archivio chiavi (id telegram-bot),
  lucchetto telegram.lock (un solo lettore per bot), abbinamento con codice
  a 6 cifre, testi in italiano, bridge client JSON-RPC dell'app-server;
- app-server: il bridge è una connessione interna nel daemon (tutte le
  sessioni) e nell'app-server in-process delle sessioni --no-daemon;
- TUI: /telegram (token mascherato con getMe, abbinamento, attiva/disattiva,
  stato) con snapshot a 80 e 120 colonne;
- test: allowlist, abbinamento, prima risposta vince da entrambe le parti,
  instradamento delle risposte, divisione dei messaggi, token mai in config o
  errori, nessun polling se disattivato; test app-server sull'instradamento.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:32:16 +01:00
andrea.difonzo
28bddb1b0c WIP Telegram: modulo akode-telegram (API e impostazioni), in pausa
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 08:21:25 +01:00
andrea.difonzo
9636b74c7d aKode 0.2.0: protezione dai loop, errori del server chiari, pulizia
- Protezione dai loop: se il modello ripete lo stesso comando con lo stesso
  errore 3 volte di fila il turno si ferma con un messaggio chiaro (e un
  suggerimento su /permissions per i blocchi della sandbox); configurabile
  con [agent] max_repeated_failures (0 = disattivata).
- Errori dello stream: si mostra il messaggio del server invece di
  "stream closed before response.completed"; il contesto superato
  (llama.cpp, vLLM) diventa un messaggio in italiano; avviso una volta se il
  prompt iniziale supera la finestra del modello.
- Pulizia: tolta la logica morta per le chiavi OpenAI nel credential broker
  (prefisso "sk-", watermark, prefissi ignorati); link alla documentazione
  OpenAI nella TUI sostituiti con il README del repository; test dello
  snapshot del broker adattato al token GitHub.
- Versione 0.2.0 e sezione Novità nel README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:47:47 +01:00
andrea.difonzo
0043e15ebb aKode v0.2: pannello /endpoint e impostazioni per modello
- /endpoint: tre colonne (endpoint, modelli, impostazioni), una alla volta sotto
  100 colonne con il percorso in alto. Aggiunta e modifica con il modulo
  dell'endpoint di /setup (chiave mascherata e mantenuta se vuota), prova della
  connessione, eliminazione con conferma e rimozione della chiave, «u» per usare
  endpoint e modello con una nuova chat.
- [model_providers.<id>.models."<modello>"]: context_window, temperature, top_p,
  max_output_tokens, reasoning_effort, display_name. Il valore del modello vince
  su quello globale; temperature/top_p/max_output_tokens vanno nella richiesta
  Responses; il contesto entra nel calcolo di ctx % e dell'auto-compattazione.
  Le modifiche al modello attivo valgono dal turno successivo, senza riavvio.
- Nomi dei modelli: gli id che sono percorsi mostrano solo il nome del file senza
  estensione; display_name ha la precedenza. L'API riceve sempre l'id completo.
- /setup: se [web_search] è configurato, l'URL di SearXNG è precompilato e
  «Mantieni» è preselezionato.
- Schema della configurazione rigenerato; test per precedenze, richiesta,
  snapshot a 80/120/160 colonne e assenza delle chiavi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:01:14 +01:00
andrea.difonzo
4da5b66563 WIP v0.2.0: pannello /endpoint e nomi abbreviati dei modelli (in pausa, non compilato)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:27:36 +01:00
andrea.difonzo
1a3ab89277 aKode 0.1.0: installatore install.sh e istruzioni nel README
- install.sh scarica l'ultima release da git.difonzo.net, verifica lo
  SHA-256 e installa in ~/.local/share/akode/package con il comando
  ~/.local/bin/akode, senza sudo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:40:27 +01:00
andrea.difonzo
a3a8c7398a aKode: daemon con code-mode-host e rg facoltativi nel pacchetto
- La verifica del pacchetto locale richiede solo akode-package.json e
  l'eseguibile; code-mode-host e rg in akode-path, se presenti, devono
  essere eseguibili.
- Test del daemon corretti dopo la rinomina (binario akode, non codex).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:40:27 +01:00
andrea.difonzo
03524f0272 aKode: rimossi i link a OpenAI dagli avvisi della TUI
- Avvisi di sicurezza, buffering e catalogo plugin senza link a
  help.openai.com e chatgpt.com; snapshot aggiornati.
- Rimossi il riesporto e la funzione per i link sottolineati rimasti
  senza utilizzi (nessun avviso nella build release).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:40:27 +01:00
andrea.difonzo
24a3cfe2f4 aKode: eliminato chatgpt_base_url ormai inutilizzato
- La chiave è ancora accettata nei file di configurazione ma ignorata.
- Schemi JSON e TypeScript dell'app-server rigenerati; i bundle ora si
  chiamano akode_app_server_protocol*.schemas.json, come produce il
  generatore.
- app-server: niente più avviso unused_mut nella build release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:40:27 +01:00
andrea.difonzo
f366db7f29 aKode: rimosso il provider OpenAI dal credential broker
- Il broker delle credenziali del proxy di rete non conosce più OpenAI:
  restano GitHub e i provider configurati dall'utente.
- Test del loader adattati: le protezioni di sicurezza restano, ora
  verificate con GitHub e con un provider personalizzato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:40:26 +01:00
andrea.difonzo
e1ce139a80 aKode update: il ripristino del binario non sovrascrive mai il file in uso
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:00:00 +01:00
andrea.difonzo
9494b768dd aKode: comando akode update e avviso di nuova versione
- Nuovo crate akode-update: legge l'ultima release dal repository Gitea
  configurato ([update] repo_url, predefinito git.difonzo.net/andrea/aKode;
  404 = nessun aggiornamento), confronta la semver, scarica
  akode-<versione>-<target>.tar.gz solo dallo stesso host, verifica lo
  SHA-256 e sostituisce il binario in modo atomico tenendo akode.old
  (nel layout a pacchetto aggiorna anche akode-package.json o l'intero
  pacchetto).
- `akode update [--check]` con messaggi in italiano; mai installazioni
  automatiche.
- TUI: controllo in background all'avvio al massimo ogni 24 h
  (update-check.json in AKODE_HOME), avviso su una riga, disattivabile con
  [update] check_on_startup = false.
- Rimossi il prompt di aggiornamento e le azioni npm/brew/installer di
  OpenAI ormai inutilizzati; il doctor mostra sorgente e ultimo controllo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:56:25 +01:00
andrea.difonzo
25de1e70dc aKode: rimossi /app e i controlli dell'app Desktop
L'app Desktop di OpenAI non esiste per aKode: eliminati il comando /app
(variante, descrizione, dispatch, composer, evento OpenDesktopThread e
apertura codex:// / OpenAI.Codex), i controlli desktop di `akode doctor`
con i relativi test e snapshot. Le esclusioni antivirus indicate dal
doctor ora citano il binario akode invece della Codex app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:56:17 +01:00
andrea.difonzo
ac3f65985d aKode: niente logo centrale nelle sessioni (solo intestazione); il logo resta nel primo avvio, riattivabile con [tui.effects] welcome = true
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:13:35 +01:00
andrea.difonzo
85dc979c55 aKode: ripristina il .pending-snap modificato per errore dall'esecuzione dei test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:39:24 +01:00
andrea.difonzo
08b2c098b8 aKode setup: scelta di dove salvare la chiave API (portachiavi o file protetto)
- nuovo passo «Dove salvo la chiave?» dopo il campo Chiave API (solo se inserita),
  preselezionato secondo provider_api_key_store; senza portachiavi solo il file
- la scelta scrive provider_api_key_store (impostazione globale: file oppure auto),
  salva la chiave solo nel backend scelto, rimuove la copia nell'altro e sposta
  le chiavi degli altri provider
- akode-login: save_provider_api_key_to(_with_keyring), sonda del portachiavi
- test: file 0600 e nessuna chiave in config.toml, portachiavi senza file,
  cambio con rimozione della vecchia copia; snapshot 60/80/120 senza la chiave

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:39:19 +01:00
andrea.difonzo
9df212cf5e aKode: test compute_store_key allineato a ~/.akode (hash rimasto quello di ~/.codex dopo la rinomina)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:39:18 +01:00
andrea.difonzo
ad43f9281a aKode fase 5: test e snapshot adeguati alla rinomina, 429 distinto (ProviderRateLimited), cargo fmt dopo il cambio dei prefissi
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 12:47:01 +01:00
andrea.difonzo
8b73331037 aKode fase 5: 429 con Retry-After/X-RateLimit-Reset e messaggi in italiano, filtro modelli nel primo avvio, correzioni della rinomina
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:41:54 +01:00
andrea.difonzo
86e7c72e5f aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 11:06:46 +01:00
10740 changed files with 829146 additions and 833187 deletions

View File

@@ -1,4 +1,4 @@
# Without this, Bazel will consider BUILD.bazel files in # Without this, Bazel will consider BUILD.bazel files in
# .git/sl/origbackups (which can be populated by Sapling SCM). # .git/sl/origbackups (which can be populated by Sapling SCM).
.git .git
codex-rs/target akode-rs/target

View File

@@ -24,7 +24,7 @@ build --host_features=static_link_msvcrt
build --workspace_status_command=./scripts/workspace-status.sh build --workspace_status_command=./scripts/workspace-status.sh
build:windows --workspace_status_command=./scripts/workspace-status.cmd build:windows --workspace_status_command=./scripts/workspace-status.cmd
# Runfiles strategy rationale: codex-rs/utils/cargo-bin/README.md # Runfiles strategy rationale: akode-rs/utils/cargo-bin/README.md
common --noenable_runfiles common --noenable_runfiles
common --enable_platform_specific_config common --enable_platform_specific_config
@@ -127,8 +127,8 @@ common:ci-bazel --build_metadata=TAG_workflow=bazel
# Shared config for Bazel-backed Rust linting. # Shared config for Bazel-backed Rust linting.
build:clippy --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect build:clippy --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect
build:clippy --output_groups=+clippy_checks build:clippy --output_groups=+clippy_checks
build:clippy --@rules_rust//rust/settings:clippy.toml=//codex-rs:clippy.toml build:clippy --@rules_rust//rust/settings:clippy.toml=//akode-rs:clippy.toml
# Keep this deny-list in sync with `codex-rs/Cargo.toml` `[workspace.lints.clippy]`. # Keep this deny-list in sync with `akode-rs/Cargo.toml` `[workspace.lints.clippy]`.
# Cargo applies those lint levels to member crates that opt into `[lints] workspace = true` # Cargo applies those lint levels to member crates that opt into `[lints] workspace = true`
# in their own `Cargo.toml`, but `rules_rust` Bazel clippy does not read Cargo lint levels. # in their own `Cargo.toml`, but `rules_rust` Bazel clippy does not read Cargo lint levels.
# `clippy.toml` can configure lint behavior, but it cannot set allow/warn/deny/forbid levels. # `clippy.toml` can configure lint behavior, but it cannot set allow/warn/deny/forbid levels.
@@ -181,7 +181,7 @@ common:ci-windows --build_metadata=TAG_os=windows
common:ci-windows --repo_contents_cache=D:/a/.cache/bazel-repo-contents-cache common:ci-windows --repo_contents_cache=D:/a/.cache/bazel-repo-contents-cache
# The hidden dynamic-tool callback currently times out on Windows, and ConPTY # The hidden dynamic-tool callback currently times out on Windows, and ConPTY
# cannot reliably interrupt foreground processes on Windows Bazel runners. # cannot reliably interrupt foreground processes on Windows Bazel runners.
common:ci-windows --test_env=CODEX_BAZEL_TEST_SKIP_FILTERS=suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child common:ci-windows --test_env=AKODE_BAZEL_TEST_SKIP_FILTERS=suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child
# We prefer to run the build actions entirely remotely so we can dial up the concurrency. # We prefer to run the build actions entirely remotely so we can dial up the concurrency.
# We have platform-specific tests, so we want to execute the tests on all platforms using the strongest sandboxing available on each platform. # We have platform-specific tests, so we want to execute the tests on all platforms using the strongest sandboxing available on each platform.
@@ -212,7 +212,7 @@ common:ci-windows-cross --test_env=RUST_TEST_THREADS=1
# Native Windows CI still covers the PowerShell parser-process tests. The # Native Windows CI still covers the PowerShell parser-process tests. The
# cross-built gnullvm binaries currently hang in those tests when run on the # cross-built gnullvm binaries currently hang in those tests when run on the
# Windows runner. This replaces the Windows skip list, so retain its exclusions. # Windows runner. This replaces the Windows skip list, so retain its exclusions.
common:ci-windows-cross --test_env=CODEX_BAZEL_TEST_SKIP_FILTERS=command_safety::powershell_parser::tests::,suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child common:ci-windows-cross --test_env=AKODE_BAZEL_TEST_SKIP_FILTERS=command_safety::powershell_parser::tests::,suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child
common:ci-windows-cross --platforms=//:windows_x86_64_gnullvm common:ci-windows-cross --platforms=//:windows_x86_64_gnullvm
common:ci-windows-cross --extra_execution_platforms=//:rbe,//:windows_x86_64_msvc common:ci-windows-cross --extra_execution_platforms=//:rbe,//:windows_x86_64_msvc
common:ci-windows-cross --extra_toolchains=//:windows_gnullvm_tests_on_msvc_host_toolchain common:ci-windows-cross --extra_toolchains=//:windows_gnullvm_tests_on_msvc_host_toolchain
@@ -245,7 +245,7 @@ build:ci-windows-msvc --host_action_env=WindowsSdkDir
build:ci-windows-msvc --action_env=VCINSTALLDIR build:ci-windows-msvc --action_env=VCINSTALLDIR
build:ci-windows-msvc --host_action_env=VCINSTALLDIR build:ci-windows-msvc --host_action_env=VCINSTALLDIR
# Release profile settings are also defined in codex-rs/Cargo.toml. # Release profile settings are also defined in akode-rs/Cargo.toml.
# runtime_package.bzl applies this profile to archive dependencies automatically. # runtime_package.bzl applies this profile to archive dependencies automatically.
# Packaging extracts symbols before stripping; the Rust toolchains retain # Packaging extracts symbols before stripping; the Rust toolchains retain
# line tables and use split-debuginfo=off. opt mode selects Rust opt-level=3, # line tables and use split-debuginfo=off. opt mode selects Rust opt-level=3,

4
.gitattributes vendored
View File

@@ -1,4 +1,4 @@
codex-rs/app-server-protocol/schema/** linguist-generated akode-rs/app-server-protocol/schema/** linguist-generated
codex-rs/hooks/schema/generated/** linguist-generated akode-rs/hooks/schema/generated/** linguist-generated
third_party/voice/sources.json text eol=lf third_party/voice/sources.json text eol=lf
patches/v8_array_sort_elements_kind.patch text eol=lf patches/v8_array_sort_elements_kind.patch text eol=lf

2
.gitignore vendored
View File

@@ -16,7 +16,7 @@ out/
storybook-static/ storybook-static/
# ignore README for publishing # ignore README for publishing
codex-cli/README.md akode-cli/README.md
# ignore Nix derivation results # ignore Nix derivation results
result result

View File

@@ -347,8 +347,8 @@ register_toolchains("//bazel/toolchains/prost:toolchain")
crate = use_extension("@rules_rs//rs:extensions.bzl", "crate") crate = use_extension("@rules_rs//rs:extensions.bzl", "crate")
crate.from_cargo( crate.from_cargo(
cargo_lock = "//codex-rs:Cargo.lock", cargo_lock = "//akode-rs:Cargo.lock",
cargo_toml = "//codex-rs:Cargo.toml", cargo_toml = "//akode-rs:Cargo.toml",
platform_triples = [ platform_triples = [
"aarch64-unknown-linux-gnu", "aarch64-unknown-linux-gnu",
"aarch64-unknown-linux-musl", "aarch64-unknown-linux-musl",
@@ -386,7 +386,7 @@ crate.from_cargo(
bazel_dep(name = "zstd", version = "1.5.7.bcr.2") bazel_dep(name = "zstd", version = "1.5.7.bcr.2")
crate.annotation( crate.annotation(
# Keep Windows proxy authentication aligned with codex-rs/.cargo/config.toml. # Keep Windows proxy authentication aligned with akode-rs/.cargo/config.toml.
build_script_env = {"CFLAGS": "-DCURL_ENABLE_NTLM"}, build_script_env = {"CFLAGS": "-DCURL_ENABLE_NTLM"},
crate = "curl-sys", crate = "curl-sys",
) )
@@ -660,7 +660,7 @@ crate.annotation(
"CMAKE": "$${pwd}/$(CMAKE)", "CMAKE": "$${pwd}/$(CMAKE)",
"CMAKE_GENERATOR": "Ninja", "CMAKE_GENERATOR": "Ninja",
"CMAKE_TOOLCHAIN_FILE": "$(execpath @@//third_party/voice:opus-toolchain.cmake)", "CMAKE_TOOLCHAIN_FILE": "$(execpath @@//third_party/voice:opus-toolchain.cmake)",
"CODEX_VOICE_NINJA": "$${pwd}/$(NINJA)", "AKODE_VOICE_NINJA": "$${pwd}/$(NINJA)",
}, },
build_script_toolchains = [ build_script_toolchains = [
"@rules_foreign_cc//toolchains:current_cmake_toolchain", "@rules_foreign_cc//toolchains:current_cmake_toolchain",

187
README.md
View File

@@ -4,7 +4,7 @@
È un fork di [OpenAI Codex CLI](https://github.com/openai/codex) (Apache-2.0). Da Codex eredita l'interfaccia a terminale, l'esecuzione dei comandi in sandbox, la modifica dei file con patch, MCP, skill, plugin locali e la modalità non interattiva `exec`. Ha però tolto tutto ciò che dipende dai servizi di OpenAI. È un fork di [OpenAI Codex CLI](https://github.com/openai/codex) (Apache-2.0). Da Codex eredita l'interfaccia a terminale, l'esecuzione dei comandi in sandbox, la modifica dei file con patch, MCP, skill, plugin locali e la modalità non interattiva `exec`. Ha però tolto tutto ciò che dipende dai servizi di OpenAI.
> **Uso privato.** Questo repository (`git.difonzo.net/andrea/aKode`) non è distribuito né pubblicato. > **Uso privato.** Questo repository (`git.difonzo.net/andrea/imeai-aKode`) non è distribuito né pubblicato.
--- ---
@@ -19,39 +19,56 @@
| 2b-2 | Login ChatGPT/OAuth, identità agente, token personali: resta solo l'autenticazione con chiave API. Rimossi anche generazione immagini, plugin remoti, cyber/daybreak, configurazione dal cloud, attestation, app e connettori ChatGPT | ✅ | | 2b-2 | Login ChatGPT/OAuth, identità agente, token personali: resta solo l'autenticazione con chiave API. Rimossi anche generazione immagini, plugin remoti, cyber/daybreak, configurazione dal cloud, attestation, app e connettori ChatGPT | ✅ |
| 3 | Provider: nessun default OpenAI; Ollama, LM Studio ed endpoint personalizzati; elenco modelli letto dal server; unione dei messaggi di sistema per i modelli locali; chiave per provider nel portachiavi; ricerca web con SearXNG | ✅ | | 3 | Provider: nessun default OpenAI; Ollama, LM Studio ed endpoint personalizzati; elenco modelli letto dal server; unione dei messaggi di sistema per i modelli locali; chiave per provider nel portachiavi; ricerca web con SearXNG | ✅ |
| 4 | Primo avvio guidato (tema con anteprima, provider, endpoint con chiave nel portachiavi, modello dal server, prova di connessione, SearXNG); temi /theme; barra di stato con server, modello, contesto e tok/s | ✅ | | 4 | Primo avvio guidato (tema con anteprima, provider, endpoint con chiave nel portachiavi, modello dal server, prova di connessione, SearXNG); temi /theme; barra di stato con server, modello, contesto e tok/s | ✅ |
| 5 | Rebranding completo: comando `akode`, `~/.akode`, variabili `AKODE_*`, crate `akode-*` | ⏳ | | 5 | Rebranding completo: comando `akode`, `~/.akode`, variabili `AKODE_*`, crate `akode-*`; gestione dei 429; filtro modelli nel primo avvio | ✅ |
| 6 | Verifica finale e installatore locale | ⏳ | | 6 | Verifica finale, release 0.1.0 e installatore `install.sh` | ✅ |
| Grafo | Grafo del codice locale (tree-sitter + git), strumento `code_graph`, memorie ancorate ai simboli con stato stale (0.8.0) | ✅ |
Finché la fase 5 non è completa, il binario, la cartella di configurazione e le variabili d'ambiente usano ancora i nomi di Codex: `codex`, `~/.codex`, `CODEX_*`. Il comando è `akode`, la configurazione sta in `~/.akode` (oppure nella cartella indicata da `AKODE_HOME`) e le variabili d'ambiente usano il prefisso `AKODE_*`. aKode **non** legge `~/.codex` né le variabili `CODEX_*`: può convivere con un'installazione di OpenAI Codex. La configurazione di progetto sta in `.akode/`; `AGENTS.md` resta invariato.
--- ---
## Installazione (macOS Apple Silicon)
```bash
curl -fsSL https://git.difonzo.net/andrea/imeai-aKode/raw/branch/main/install.sh | sh
```
Variante più prudente: scarica lo script, leggilo e poi eseguilo.
```bash
curl -fsSLO https://git.difonzo.net/andrea/imeai-aKode/raw/branch/main/install.sh
less install.sh
sh install.sh
```
Lo script scarica l'ultima release da `git.difonzo.net` (nessun altro host), ne verifica lo SHA-256 e la installa in `~/.local/share/akode/package`, con il comando `~/.local/bin/akode` (niente `sudo`). Si può rieseguire senza danni; `AKODE_VERSION=0.1.0 sh install.sh` installa una versione precisa. Gli aggiornamenti successivi si fanno con `akode update`. Su Linux o su Mac Intel compila da sorgente (vedi sotto). La ricerca nei file usa `rg` (ripgrep) se è nel `PATH`.
## Requisiti ## Requisiti
- macOS (Apple Silicon) o Linux. - macOS (Apple Silicon) o Linux.
- Rust tramite `rustup`: la toolchain richiesta (`codex-rs/rust-toolchain.toml`) viene installata automaticamente. - Rust tramite `rustup`: la toolchain richiesta (`akode-rs/rust-toolchain.toml`) viene installata automaticamente.
- `git`. - `git`.
- Un endpoint LLM che supporti la **Responses API** (`POST /v1/responses`). Codex/aKode non usa più `/chat/completions`. - Un endpoint LLM che supporti la **Responses API** (`POST /v1/responses`). Codex/aKode non usa più `/chat/completions`.
## Compilazione ## Compilazione
```bash ```bash
cd codex-rs cd akode-rs
# build leggera: meno spazio su disco, niente debuginfo # build leggera: meno spazio su disco, niente debuginfo
export CARGO_NET_GIT_FETCH_WITH_CLI=true export CARGO_NET_GIT_FETCH_WITH_CLI=true
export CARGO_PROFILE_DEV_DEBUG=0 export CARGO_PROFILE_DEV_DEBUG=0
export CARGO_INCREMENTAL=0 export CARGO_INCREMENTAL=0
cargo build -p codex-cli --bin codex # debug cargo build -p akode-cli --bin akode # debug
cargo build -p codex-cli --bin codex --release # release cargo build -p akode-cli --bin akode --release # release
``` ```
Per i test serve uno stack più grande: `export RUST_MIN_STACK=8388608`. Testa un crate alla volta (`cargo test -p <crate> --lib`). La cartella `codex-rs/target` può superare i 50 GB: cancellala quando non serve. Per i test serve uno stack più grande: `export RUST_MIN_STACK=8388608`. Testa un crate alla volta (`cargo test -p <crate> --lib`). La cartella `akode-rs/target` può superare i 50 GB: cancellala quando non serve.
## Configurazione di un modello ## Configurazione di un modello
In `~/.codex/config.toml` (dopo la fase 5 diventerà `~/.akode/config.toml`): In `~/.akode/config.toml`:
```toml ```toml
model_provider = "imeai" model_provider = "imeai"
@@ -67,12 +84,38 @@ wire_api = "responses"
```bash ```bash
export IMEAI_API_KEY="..." # chiave del server export IMEAI_API_KEY="..." # chiave del server
codex exec "descrivi questo progetto" akode exec "descrivi questo progetto"
``` ```
**Server llama.cpp / ik_llama.cpp con Qwen3.x:** aKode invia più messaggi di sistema/developer. Il template originale di Qwen li rifiuta ("System message must be at the beginning"), quindi va usato un template che li accetti (`--chat-template-file`). Il server imeAI usa `/etc/llama/qwen36-multisys.jinja`. Con la fase 3 aKode li unirà da solo. **Server llama.cpp / ik_llama.cpp con Qwen3.x:** aKode invia più messaggi di sistema/developer. Il template originale di Qwen li rifiuta ("System message must be at the beginning"), quindi va usato un template che li accetti (`--chat-template-file`). Il server imeAI usa `/etc/llama/qwen36-multisys.jinja`. Con la fase 3 aKode li unirà da solo.
**Interfaccia interattiva:** in questa fase la TUI richiede un'installazione impacchettata. Lanciata da `target/` funziona solo `codex exec`, oppure `codex --no-daemon`. L'installatore locale arriva con la fase 6. **Interfaccia interattiva:** in questa fase la TUI richiede un'installazione impacchettata. Lanciata da `target/` funziona solo `akode exec`, oppure `akode --no-daemon`. L'installatore locale arriva con la fase 6.
## Controllo da Telegram
Le sessioni di aKode aperte si possono seguire e comandare dal proprio bot Telegram: un topic per ogni sessione, risposte in streaming, approvazioni con pulsanti.
1. Crea un bot con @BotFather (`/newbot`) e copia il token.
2. In @BotFather: **Bot Settings → Threaded Mode → attiva**, così ogni sessione ha il suo topic nella chat privata col bot (senza, i messaggi hanno il prefisso `[cartella · modello]`).
3. In aKode: `/telegram` → «Imposta il token» (incolla, viene verificato con `getMe`).
4. «Abbina una chat»: invia al bot il codice di 6 cifre mostrato.
5. «Attiva».
```toml
[telegram]
enabled = true
allowed_chat_ids = [123456789]
[telegram.notify] # tutti attivi se omessi
approvals = true
turn_end = true
errors = true
loops = true
```
Il token sta nell'archivio delle chiavi (`provider_api_key_store`, id `telegram-bot`), mai in `config.toml`. Il bot serve solo le chat in `allowed_chat_ids` e ignora tutte le altre senza rispondere. Comandi (nel menu del bot): `/sessioni`, `/nuova`, `/stato`, `/stop`, `/impostazioni`, `/aiuto`; scrivendo nel topic di una sessione le si scrive (se è al lavoro il testo si aggiunge al turno o va in coda). Le approvazioni arrivano sia nella TUI sia su Telegram: vale la prima risposta e l'altra parte la vede risolta.
**Dove gira:** nel server dell'app condiviso (il daemon, avviato dalla prima sessione `akode`), quindi tutte le sessioni sono raggiungibili insieme. Telegram ammette un solo lettore per bot: chi legge tiene il lucchetto `~/.akode/telegram.lock`. Una sessione `--no-daemon` serve solo le proprie conversazioni e legge solo se il lucchetto è libero; altrimenti riprova ogni pochi secondi e subentra quando l'altro processo termina. Con `enabled = false` nessun processo contatta Telegram (l'abbinamento da `/telegram` lo contatta solo mentre è aperto). Solo `https://api.telegram.org`, long polling, nessuna porta in ingresso.
--- ---
@@ -83,6 +126,126 @@ codex exec "descrivi questo progetto"
- **Rete in automatico:** nessun controllo aggiornamenti, annuncio, download di asset o sincronizzazione di plugin all'avvio. - **Rete in automatico:** nessun controllo aggiornamenti, annuncio, download di asset o sincronizzazione di plugin all'avvio.
- **Feedback:** nessun upload a Sentry; resta solo il salvataggio locale. - **Feedback:** nessun upload a Sentry; resta solo il salvataggio locale.
## Novità
### 0.9.1
- **Rete della sandbox verso i registri dei pacchetti** (decisione dell'utente, opzione «C»): nella sandbox predefinita (`:workspace`: scrittura solo nella cartella del progetto e in `/tmp`, come prima) la rete ora è attiva ma passa dal proxy di rete locale di aKode, che lascia passare solo i registri dei pacchetti; le altre destinazioni ricevono `403 Domain not in allowlist` e la rete diretta resta bloccata da Seatbelt. Le scritture non cambiano, e chi ha scelto esplicitamente `sandbox_mode` o un profilo `default_permissions` resta com'era. Domini predefiniti: `pypi.org`, `files.pythonhosted.org`, `registry.npmjs.org`, `registry.yarnpkg.com`, `pub.dev`, `storage.googleapis.com`, `crates.io`, `static.crates.io`, `index.crates.io`, `github.com`, `codeload.github.com`, `objects.githubusercontent.com`. Si cambiano in `~/.akode/config.toml`:
```toml
[features.network_proxy.domains]
"gitlab.com" = "allow" # aggiunge un dominio
"pub.dev" = "deny" # ne toglie uno
```
Per tornare alla sandbox senza rete delle versioni precedenti:
```toml
[sandbox_workspace_write]
network_access = false
```
I valori predefiniti stanno in `akode-rs/config/defaults.toml`.
- **apply_patch tollerante**: se mancano `*** Begin Patch` o `*** End Patch` ma il contenuto è un patch valido (inizia con `*** Add File:`, `*** Update File:` o `*** Delete File:`), aKode li aggiunge; toglie anche un recinto ```` ``` ```` attorno al patch. Ogni altra ambiguità resta un errore, e il patch passa sempre dalle stesse verifiche, sandbox e approvazioni. Agli errori di formato segue una riga con il formato esatto e un esempio minimo.
- **Strumento `write_file`** (percorso + contenuto intero): crea un file o lo riscrive tutto. Passa dalla stessa pipeline di `apply_patch` (verifica, sandbox, approvazioni, hook, eventi), quindi non permette niente di più. Serve ai modelli che conoscono solo il function calling JSON e cercano uno strumento «write» (Qwen chiamava `write_stdin` con un id inventato). Si spegne con `[tools] write_file = false`.
- **Protezione dai loop più paziente**: quando il modello ripete la stessa chiamata fallita, aKode prima lo avvisa una volta (con l'errore da leggere e gli strumenti giusti) e ferma il turno solo se continua.
- **Coda e lettura del prompt visibili**: con il gateway imeAI la riga di stato mostra `In coda · 2 richieste davanti · ~40 s` e `Leggo il prompt · 42% · ~1 min 20 s` (eventi `imeai.queue` e `imeai.prefill`); prima un primo turno a cache fredda restava minuti su «Working».
- **Ogni chiamata a strumento fallita si vede nella TUI** con una riga compatta, per esempio `✗ apply_patch: manca '*** Begin Patch' · riprovo`.
- **Avanzamento delle chiamate lunghe**: mentre il modello scrive gli argomenti di uno strumento (un file intero dentro `apply_patch`, un `cat > file`), la riga di stato mostra `Scrivo fourier.py · 1.240 token`.
- **`write_stdin` con una sessione inesistente**: l'errore elenca le sessioni aperte (o «none») e indica di usare `exec_command`; descrizione dello strumento più chiara.
- **Errori di rete dentro la sandbox**: se un comando fallisce per la rete (pip, npm, curl, git…), all'output si aggiunge una nota per il modello: è la sandbox, non la connessione; quali host sono raggiungibili; come chiedere all'utente di eseguire fuori dalla sandbox (`require_escalated`), oppure, se la politica di approvazione non lo permette, di dirlo all'utente.
- **Escalation non concedibile eseguita nella sandbox**: se la politica di approvazione non permette di chiedere l'esecuzione fuori dalla sandbox (per esempio in una cartella senza progetto), il comando gira nella sandbox invariata con una nota per il modello, invece di essere rifiutato; nessun permesso in più. Prima Qwen, dopo il rifiuto, rinunciava a installare le dipendenze.
- **Note sulla sandbox per il modello**: dopo una scrittura negata (`Operation not permitted`, per esempio `pip install` nel Python di sistema) aKode spiega dove può scrivere e suggerisce un ambiente virtuale nel progetto; dopo `write_file` ricorda di verificare il file.
- **Immagini degli strumenti nei messaggi utente**: llama.cpp/ik_llama.cpp accettano immagini solo nei messaggi utente; un'immagine dentro l'output di `view_image` faceva rispondere il server con HTTP 500 e il turno finiva con un errore. Con `merge_system_messages` (attivo di default) l'output dello strumento resta testo e l'immagine segue in un messaggio utente. L'errore 500 ora si chiama per nome invece di «high demand».
- **Testi della TUI in italiano**: messaggio di benvenuto e comandi suggeriti, «Chiedi ad aKode qualsiasi cosa», «per gli agenti», «per le scorciatoie», «Errore fatale»; nelle approvazioni «aKode» invece di «codex».
### 0.9.0
- **Cache del prompt più stabile** (misure sul server imeAI):
- ordine fisso dei blocchi di contesto: prima le sezioni uguali in ogni sessione (`<skills_instructions>`, permessi), poi quelle che dipendono dal repository o dalla sessione (`<code_map>`, riepilogo della memoria). Prima `<code_map>` stava subito dopo le istruzioni di sistema: c'era o mancava a seconda che l'indice fosse pronto, e cambiava da un repository all'altro, invalidando tutto il resto;
- strumenti in ordine stabile: prima quelli di aKode, poi quelli con namespace (server MCP, sotto-agenti), ciascuno per nome; nella sessione resta l'ordine della prima richiesta e gli strumenti che arrivano dopo finiscono in coda, mai in mezzo;
- server MCP: la prima richiesta di una sessione aspetta fino a 5 s (prima 1 s) i server ancora in avvio, così l'elenco degli strumenti è completo dall'inizio (`mcp_optional_startup_grace_ms`).
- **Attese lunghe dei server locali**: ogni byte ricevuto conta come segno di vita, compresi i commenti SSE e gli eventi `imeai.queue` e `imeai.prefill` del gateway (prima i commenti non azzeravano il timer). Il timeout di inattività vale anche per l'attesa della prima risposta (prima illimitata) ed è di 30 minuti per i server locali (loopback, rete privata, `.local`, `.lan`), 5 minuti per gli altri; si cambia con `stream_idle_timeout_ms` del provider. Niente più keepalive TCP: reqwest chiudeva dopo 60 s una connessione muta quando le sonde non tornavano indietro (succede attraverso NetBird), e una lettura del prompt più lunga di un minuto ripartiva da capo; misurato sul server: prima richiesta a freddo di 82 s arrivata alla fine senza ripetizioni.
- **Repository rinominato** in `git.difonzo.net/andrea/imeai-aKode`: installatore, `akode update` e link aggiornati; il vecchio indirizzo risponde con un redirect.
- **Compattazione più leggera**: prima del riassunto, l'output degli strumenti più vecchi (tutti tranne gli ultimi 3, sopra i 400 caratteri) diventa un segnaposto breve; le chiamate restano visibili. Il prompt del riassunto si accorcia di molto, e su CPU ogni token in meno è tempo in meno. La compattazione usa sempre il provider configurato (verificato, con un test).
- **Protezione dai loop, in stile Gemini CLI**, insieme a `[agent] max_repeated_failures`:
- `[agent] max_identical_tool_calls` (5): stessa chiamata con gli stessi argomenti per 5 volte di fila, qualunque sia il risultato; esclusi gli strumenti di attesa (`write_stdin`, `wait_agent`);
- `[agent] max_repeated_text` (10): lo stesso pezzo di testo ripetuto 10 volte di seguito mentre arriva, nella risposta o nel ragionamento; esclusi i blocchi di codice e i separatori. La risposta si ferma subito invece di andare avanti fino al limite di token.
- **Cancellazioni ricorsive protette**: `rm -r`/`rm -rf` e `find … -delete` della radice, della home, della radice del repository, della cartella di lavoro, di percorsi fuori dalla cartella di lavoro o calcolati a runtime (`$VAR`, `$(…)`, `xargs`) chiedono sempre la conferma dell'utente, anche con regole che li permetterebbero; in accesso completo, dove nessuno può confermare, vengono rifiutati.
### 0.8.0
- **Grafo del codice** (memoria di imeAI, fase 4): aKode indicizza in locale il repository della cartella di lavoro con tree-sitter e git, senza modello e senza mandare il codice da nessuna parte. Linguaggi: Rust, TypeScript/TSX/JavaScript, Python, Go, Swift, Bash; di TOML, JSON e YAML solo la struttura (sezioni e chiavi). Indice SQLite per repository in `~/.akode/code-graph/`, fuori dal checkout; aggiornamento incrementale da `git diff` rispetto all'ultimo commit indicizzato più `git status` (su akode-rs: prima indicizzazione 4,2 s, aggiornamenti 57-150 ms).
- Strumento in sola lettura **`code_graph`** per il modello: `search`, `definition` (file:riga e prime righe), `callers`, `callees`, `related`, `module_map`, `overview`; risposte compatte con `path:line` e un budget di token. I riferimenti sono per nome: con nomi comuni la risposta dice quante definizioni li condividono. `akode code-graph index|search|definition|callers|callees|related|map|summary` fa le stesse domande dal terminale. `[code_graph] enabled`, `repo_map` (mappa breve del repository nel contesto iniziale, spenta), `max_output_tokens`.
- Istruzioni di sistema (approvato dall'utente): un paragrafo `## code_graph` chiede di usare lo strumento per trovare dove sta il codice prima di cercare con la shell. Prova con Qwen su 8 compiti di navigazione e modifica: 7/8 riusciti contro 5/8 con lo strumento disponibile ma senza la riga, tempo medio 65 s contro 99 s, token in ingresso 36k contro 37k.
- **Memorie legate al codice**: quando una memoria del progetto cita file o simboli, aKode salva sul server gli ancoraggi (percorso, nome del simbolo, tipo, riga e hash del testo del simbolo; mai il codice). A inizio sessione e a ogni `memory_recall` li verifica sul working tree: se il simbolo è cambiato o sparito la memoria compare come `status="stale"` con il motivo (nel riepilogo `STALE: code changed`) e l'esito va al server. `[memoria] anchors = false` lo spegne. Serve il plugin `memoria` 0.5.0.
- Marchio: il client MCP si presenta come `akode-mcp-client` (titolo «aKode», User-Agent `akode-mcp-client/…`), il nome del client OAuth MCP è «aKode», l'originator predefinito è `akode_cli_rs` e i commit di baseline sono firmati «aKode» (prima «Codex» con un indirizzo openai.com).
### 0.7.0
- Privacy: anche gli header HTTP `session-id`, `thread-id` e `x-client-request-id` (richieste HTTP e handshake WebSocket) vanno solo ai provider locali (loopback, IP privati, host `.local`/`.lan`), come già `client_metadata`. OpenRouter e gli altri servizi remoti non ricevono più identificativi della sessione.
- Identità: alla domanda «chi ti ha creato» il modello risponde che aKode è il fork privato dell'utente di un agente di coding open source e che gira sul suo server imeAI, senza attribuirsi a imeAI o a un'azienda (prova: 5 risposte su 5 senza «creato da imeAI»).
- Compatibile con la memoria di imeAI, fase 5 (consolidamento, scadenza per uso, grafo delle entità). Plugin `memoria` 0.3.1: le risposte di `memory_recall` possono contenere una riga `Entities:` e la skill spiega come usarla per il secondo passo di una ricerca.
### 0.6.0
- Memoria di imeAI, fase 3: a fine sessione aKode consegna al server memoria una trascrizione compatta del thread (messaggi dell'utente, risposte finali, comandi e file modificati, ricerche web e altri server MCP con output troncati; mai le chiamate al server memoria stesso). La consegna avviene dopo `[memoria] deliver_idle_minutes` minuti di inattività (predefinito 10, annullata da un nuovo turno) e alla chiusura del thread (al massimo 5 secondi, poi rinuncia senza bloccare), solo se ci sono turni nuovi. Lo strumento `memory_ingest_session` lo chiama aKode, il modello non lo vede. `[memoria] deliver_sessions = false` la spegne; serve il plugin `memoria` attivo.
- Rimossa la memoria nativa ereditata da Codex (`memories`, `/memories`, importazione delle memorie da altri agenti, `akode debug clear-memories`): niente più riassunti e consolidamenti in sottofondo sullo slot del modello. `[memories]`, `memories` e `memory_tool` sono ancora accettati ma ignorati, con un solo avviso; i file `memories_*` in `~/.akode` non vengono più aperti né cancellati.
- Meno chiamate al modello non richieste: il titolo dei thread nuovi è il primo messaggio troncato (`[tui] auto_title = true` per farlo generare al modello), il riepilogo automatico è spento (`[tui] auto_recap = true` per riaccenderlo, `/recap` resta), `goals` è spento di default.
- Privacy: `installation_id` e gli id di sessione, thread e finestra vanno nei metadati delle richieste solo ai provider locali (loopback, IP privati, host `.local`/`.lan`), non a OpenRouter o ad altri servizi remoti.
- Tolti i flag senza codice dell'app desktop di OpenAI, l'esperimento «shadow selection» delle skill, `chronicle` e gli ultimi link a siti OpenAI (il binario non contiene più `openai.com`). Le chiavi vecchie in `[features]` restano accettate.
- Istruzioni di sistema: il modello si presenta come aKode, agente privato sul server imeAI dell'utente.
### 0.5.0
- Memoria di imeAI, fase 2: a inizio sessione aKode legge dal server il riepilogo `memoria://briefing` (preferenze dell'utente, memorie più usate del progetto, memorie legate ai file in `git status`, bozze proprie marcate come non approvate) e lo inserisce una sola volta nel prompt come blocco di dati, in posizione fissa (la cache del prompt resta valida). Budget di token, timeout breve e niente riepilogo se il server non risponde: la sessione parte lo stesso. Impostazioni in `[memoria]` (`briefing`, `briefing_timeout_ms`, `briefing_max_tokens`). Serve il plugin `memoria` 0.2.0.
- Se il modello chiude il turno annunciando un'azione senza eseguirla («Correggo il file.»), aKode lo sollecita una volta (`[agent] announce_nudges`, predefinito 1, `0` lo disattiva).
- Il server in background (daemon) si allinea al CLI: all'avvio della TUI, se il daemon gira con un eseguibile diverso da quello del CLI, aKode ne seleziona il pacchetto e lo riavvia quando non ha sessioni aperte, altrimenti mostra un avviso; `akode update` e `install.sh` fanno lo stesso (`akode app-server daemon update --from-cli --if-idle`). Prima un daemon preparato una volta restava alla versione vecchia.
### 0.4.0
- Memoria a lungo termine di imeAI con il plugin `memoria` (nel repository imeai-console): aKode richiama le preferenze e le convenzioni del progetto prima di agire e propone i fatti da ricordare; le istruzioni del plugin entrano nel prompt solo se il plugin è attivo e il server risponde. Attivazione:
```sh
akode plugin marketplace add /percorso/di/imeai-console
akode plugin add memoria@imeai
printf %s "$CHIAVE_IMEAI" | akode login --provider mcp:memoria --with-api-key
akode mcp list
```
Funziona con qualunque provider del modello: il server MCP è separato.
- Server MCP: `project_header` (progetto ricavato dal remote `origin` della cartella, connessioni separate per progetto), `pollutes_memory`, token Bearer anche dal portachiavi di aKode sotto `mcp:<server>` (mai le chiavi dei provider dei modelli).
- I tool con namespace (MCP, multi-agente) vengono inviati come `<namespace>__<tool>`, perché llama.cpp, ik_llama.cpp e vLLM accettano solo function tool; `capabilities.tool_namespaces = true` li lascia com'erano.
- `akode exec` avvisa se un server MCP non risponde e continua senza i suoi strumenti; `akode login --provider mcp:<server>` non mostra più l'avviso dei provider di modelli; tolti dai suggerimenti della TUI gli ultimi link a siti OpenAI.
### 0.3.2
- Nuove istruzioni di sistema: identità aKode, agisce senza annunciare cosa sta per fare, risponde nella lingua dell'utente, circa 1000 parole; gli originali di Codex restano in `protocol/src/prompts/base_instructions/codex-original.md`. Nell'output leggibile di `akode exec` i messaggi dell'agente sono etichettati «akode».
### 0.3.1
- Shift+Tab come in Claude Code: default, plan, accesso completo (senza approvazioni, saltato se i requisiti non lo permettono; uscendo tornano i permessi di prima). La modalità si vede sotto il riquadro di scrittura e in `/stato` su Telegram.
- Telegram: il topic di una sessione nasce al primo turno; le sessioni chiuse senza turni perdono il topic, le altre diventano «(chiusa)» con nuovi tentativi se il rinomina fallisce; i topic creati con «Nuova chat» chiedono a quale sessione appartengono (un comando riceve risposta nella chat principale e il topic sparisce); pulizia dei topic orfani all'avvio.
### 0.3.0
- Controllo da Telegram: configurazione con **/telegram** (token, abbinamento della chat, attivazione).
- Un topic per sessione (Threaded Mode), con nome «cartella · modello».
- Menu dei comandi del bot: /sessioni, /nuova, /stato, /stop, /impostazioni, /aiuto.
- Pulsanti per aprire, controllare e fermare le sessioni.
- Risposte in streaming, con contesto, token/s e durata alla fine del turno.
- Approvazioni dal Mac o da Telegram: vale la prima risposta.
- Impostazioni del bot (/impostazioni): streaming, reazioni e notifiche.
### 0.2.0
- Nuovo pannello **/endpoint** (Endpoint │ Modelli │ Impostazioni) con impostazioni per modello, tra cui la lunghezza del contesto; `/model` serve solo a scegliere il modello.
- Nomi dei modelli abbreviati: se l'id è un percorso si mostra solo il nome del file senza estensione (all'API va sempre l'id completo).
- Primo avvio con l'indirizzo di SearXNG già proposto.
- Protezione dai loop: se il modello ripete lo stesso comando con lo stesso errore 3 volte di fila il turno si ferma, con un suggerimento su /permissions quando l'errore viene dalla sandbox (`[agent] max_repeated_failures`, 0 = disattivata).
- Errori del server chiari: si mostra il messaggio del server (per esempio il contesto superato di llama.cpp) invece di «stream closed before response.completed», e un avviso se il prompt iniziale supera la finestra del modello.
- Pulizia: tolta la logica morta per le chiavi OpenAI nel proxy di rete e i link alla documentazione OpenAI nella TUI.
### 0.1.0
- Prima release: installatore `install.sh` e `akode update`.
## Licenza ## Licenza
aKode deriva da OpenAI Codex CLI ed è rilasciato sotto la stessa [licenza Apache-2.0](LICENSE); vedi anche [NOTICE](NOTICE). Il codice è stato modificato in modo esteso: la cronologia git del repository documenta ogni modifica rispetto al commit di base `7874033`. "OpenAI" e "Codex" sono marchi dei rispettivi proprietari. aKode non è affiliato né approvato da OpenAI. aKode deriva da OpenAI Codex CLI ed è rilasciato sotto la stessa [licenza Apache-2.0](LICENSE); vedi anche [NOTICE](NOTICE). Il codice è stato modificato in modo esteso: la cronologia git del repository documenta ogni modifica rispetto al commit di base `7874033`. "OpenAI" e "Codex" sono marchi dei rispettivi proprietari. aKode non è affiliato né approvato da OpenAI.

302
akode-cli/bin/akode.js Executable file
View File

@@ -0,0 +1,302 @@
#!/usr/bin/env node
// Unified entry point for the Codex CLI.
import { spawn } from "node:child_process";
import { existsSync, readFileSync, realpathSync } from "fs";
import { createRequire } from "node:module";
import { constants } from "node:os";
import path from "path";
import { fileURLToPath } from "url";
// __dirname equivalent in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const require = createRequire(import.meta.url);
const codexPackageRoot = realpathSync(path.join(__dirname, ".."));
const PLATFORM_PACKAGE_BY_TARGET = {
"x86_64-unknown-linux-musl": "@openai/codex-linux-x64",
"aarch64-unknown-linux-musl": "@openai/codex-linux-arm64",
"x86_64-apple-darwin": "@openai/codex-darwin-x64",
"aarch64-apple-darwin": "@openai/codex-darwin-arm64",
"x86_64-pc-windows-msvc": "@openai/codex-win32-x64",
"aarch64-pc-windows-msvc": "@openai/codex-win32-arm64",
};
const { platform, arch } = process;
let targetTriple = null;
switch (platform) {
case "linux":
case "android":
switch (arch) {
case "x64":
targetTriple = "x86_64-unknown-linux-musl";
break;
case "arm64":
targetTriple = "aarch64-unknown-linux-musl";
break;
default:
break;
}
break;
case "darwin":
switch (arch) {
case "x64":
targetTriple = "x86_64-apple-darwin";
break;
case "arm64":
targetTriple = "aarch64-apple-darwin";
break;
default:
break;
}
break;
case "win32":
switch (arch) {
case "x64":
targetTriple = "x86_64-pc-windows-msvc";
break;
case "arm64":
targetTriple = "aarch64-pc-windows-msvc";
break;
default:
break;
}
break;
default:
break;
}
if (!targetTriple) {
throw new Error(`Unsupported platform: ${platform} (${arch})`);
}
const platformPackage = PLATFORM_PACKAGE_BY_TARGET[targetTriple];
if (!platformPackage) {
throw new Error(`Unsupported target triple: ${targetTriple}`);
}
function findCodexExecutable() {
let vendorRoot;
try {
const packageJsonPath = require.resolve(`${platformPackage}/package.json`);
vendorRoot = path.join(path.dirname(packageJsonPath), "vendor");
} catch {
vendorRoot = path.join(__dirname, "..", "vendor");
}
const codexExecutable = path.join(
vendorRoot,
targetTriple,
"bin",
process.platform === "win32" ? "akode.exe" : "akode",
);
if (existsSync(codexExecutable)) {
return codexExecutable;
}
const packageManager = detectPackageManager();
const updateCommand =
packageManager === "bun"
? "bun install -g @openai/codex@latest"
: packageManager === "pnpm"
? "pnpm add -g @openai/codex@latest"
: packageManager === "vite-plus"
? "vp install -g @openai/codex@latest"
: "npm install -g @openai/codex@latest";
throw new Error(
`Missing optional dependency ${platformPackage}. Reinstall Codex: ${updateCommand}`,
);
}
const binaryPath = findCodexExecutable();
function isPnpmOwnedCodexInstall(nodeModulesDir) {
if (!existsSync(path.join(nodeModulesDir, ".modules.yaml"))) {
return false;
}
try {
return (
realpathSync(path.join(nodeModulesDir, "@openai", "codex")) ===
codexPackageRoot
);
} catch {
return false;
}
}
function isVitePlusOwnedCodexInstall(packagesDir) {
if (path.basename(packagesDir) !== "packages") {
return false;
}
try {
const metadata = JSON.parse(
readFileSync(path.join(packagesDir, "@openai", "codex.json"), "utf8"),
);
if (metadata.name !== "@openai/codex") {
return false;
}
// Vite+ records the active global installation in packages/@openai/codex.json.
// Older installs have no ID or append a #-prefixed ID to the package name;
// newer installs put the ID in a subdirectory of the package prefix.
const installId = metadata.installId || "";
const installDir = installId.startsWith("#")
? path.join(packagesDir, `@openai/codex${installId}`)
: path.join(packagesDir, "@openai/codex", installId);
for (const nodeModulesDir of [
path.join(installDir, "lib", "node_modules"),
path.join(installDir, "node_modules"),
]) {
const packageRoot = path.join(nodeModulesDir, "@openai", "codex");
if (
existsSync(packageRoot) &&
realpathSync(packageRoot) === codexPackageRoot
) {
return true;
}
}
} catch {
// Missing or unreadable ownership metadata must not prevent Codex starting.
}
return false;
}
/**
* Use heuristics to detect the package manager that was used to install Codex
* in order to give the user a hint about how to update it.
*/
function detectPackageManager() {
// Package-manager ownership metadata can be several parents above the package.
// Search ancestors of both the canonical package root and lexical entrypoint
// because the package manager may link either path.
const entrypointDir = path.dirname(path.resolve(process.argv[1]));
for (const startDir of new Set([codexPackageRoot, entrypointDir])) {
const filesystemRoot = path.parse(startDir).root;
for (
let currentDir = startDir;
currentDir !== filesystemRoot;
currentDir = path.dirname(currentDir)
) {
if (isVitePlusOwnedCodexInstall(currentDir)) {
return "vite-plus";
}
if (isPnpmOwnedCodexInstall(path.join(currentDir, "node_modules"))) {
return "pnpm";
}
}
if (isPnpmOwnedCodexInstall(path.join(filesystemRoot, "node_modules"))) {
return "pnpm";
}
}
const userAgent = process.env.npm_config_user_agent || "";
if (/\bbun\//.test(userAgent)) {
return "bun";
}
const execPath = process.env.npm_execpath || "";
if (execPath.includes("bun")) {
return "bun";
}
if (
__dirname.includes(".bun/install/global") ||
__dirname.includes(".bun\\install\\global")
) {
return "bun";
}
return userAgent ? "npm" : null;
}
const packageManager = detectPackageManager();
const packageManagerEnvVar =
packageManager === "bun"
? "AKODE_MANAGED_BY_BUN"
: packageManager === "pnpm"
? "AKODE_MANAGED_BY_PNPM"
: packageManager === "vite-plus"
? "AKODE_MANAGED_BY_VITE_PLUS"
: "AKODE_MANAGED_BY_NPM";
const env = {
...process.env,
AKODE_MANAGED_PACKAGE_ROOT: codexPackageRoot,
};
delete env.AKODE_MANAGED_BY_NPM;
delete env.AKODE_MANAGED_BY_BUN;
delete env.AKODE_MANAGED_BY_PNPM;
delete env.AKODE_MANAGED_BY_VITE_PLUS;
env[packageManagerEnvVar] = "1";
// Replace Node so the native binary receives signals and exits directly.
// Node exposes execve on Windows too, but calling it there is unsupported.
if (process.platform !== "win32" && typeof process.execve === "function") {
// Node ignores SIGXFSZ, and ignored signals survive execve. Installing a
// handler lets execve restore the default disposition in the native binary.
process.on("SIGXFSZ", () => {});
process.execve(binaryPath, [binaryPath, ...process.argv.slice(2)], env);
}
// Older Node versions and Windows need a child process. Spawn asynchronously
// so Node can forward signals while the native binary is executing.
const child = spawn(binaryPath, process.argv.slice(2), {
stdio: "inherit",
env,
});
child.on("error", (err) => {
// Typically triggered when the binary is missing or not executable.
// Re-throwing here will terminate the parent with a non-zero exit code
// while still printing a helpful stack trace.
// eslint-disable-next-line no-console
console.error(err);
process.exit(1);
});
// Forward common termination signals to the child so that it shuts down
// gracefully. In the handler we temporarily disable the default behavior of
// exiting immediately; once the child has been signaled we simply wait for
// its exit event which will in turn terminate the parent (see below).
const forwardSignal = (signal) => {
if (child.killed) {
return;
}
try {
child.kill(signal);
} catch {
/* ignore */
}
};
["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => {
process.on(sig, () => forwardSignal(sig));
});
// When the child exits, mirror its termination reason in the parent so that
// shell scripts and other tooling observe the correct exit status.
// Wrap the lifetime of the child process in a Promise so that we can await
// its termination in a structured way. The Promise resolves with an object
// describing how the child exited: either via exit code or due to a signal.
const childResult = await new Promise((resolve) => {
child.on("exit", (code, signal) => {
if (signal) {
resolve({ type: "signal", signal });
} else {
resolve({ type: "code", exitCode: code ?? 1 });
}
});
});
if (childResult.type === "signal") {
// Preserve a failure exit code even if Node ignores the re-emitted signal.
process.exitCode = 128 + constants.signals[childResult.signal];
process.removeAllListeners(childResult.signal);
process.kill(process.pid, childResult.signal);
} else {
process.exit(childResult.exitCode);
}

23
akode-cli/package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "akode",
"private": true,
"version": "0.0.0-dev",
"description": "aKode: local coding agent (derived from OpenAI Codex CLI).",
"license": "Apache-2.0",
"bin": {
"akode": "bin/akode.js"
},
"type": "module",
"engines": {
"node": ">=16"
},
"files": [
"bin/akode.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/openai/codex.git",
"directory": "akode-cli"
},
"packageManager": "pnpm@10.34.5+sha512.a4ee05f2f73658255bd6a89859c065a45c28a57daefae2c893a168ee2b73168c37b91e83e57ea67654ad03f03031746430e8bce38e362e042605fb8abc80192e"
}

View File

@@ -0,0 +1,29 @@
# npm releases
Use the staging helper in the repo root to generate npm tarballs for a release. For
example, to stage the CLI, responses proxy, and SDK packages for version `0.6.0`:
```bash
./scripts/stage_npm_packages.py \
--release-version 0.6.0 \
--package codex \
--package codex-responses-api-proxy \
--package codex-sdk
```
This downloads the required native package archive artifacts, hydrates `vendor/` for
each package, and writes tarballs to `dist/npm/`.
When `--package codex` is provided, the staging helper builds the lightweight
`@openai/codex` meta package plus all platform-native `@openai/codex` variants
that are later published under platform-specific dist-tags.
The npm variants omit the standalone `akode-exec-server` executable and its
`execServer` manifest entry to keep uploads within npm's package size limit.
They retain `codex exec-server` through the CLI, the code-mode host, and the
platform sandbox helpers. Canonical release archives retain the standalone
executor; npm staging changes only the package copy.
Direct `build_npm_package.py` invocations are still useful for package-specific
debugging, but native packages expect `--vendor-src` to point at a prehydrated
`vendor/` tree. Release packaging should use `scripts/stage_npm_packages.py`

View File

@@ -3,7 +3,7 @@ set -euo pipefail # Exit on error, undefined vars, and pipeline failures
IFS=$'\n\t' # Stricter word splitting IFS=$'\n\t' # Stricter word splitting
# Read allowed domains from file # Read allowed domains from file
ALLOWED_DOMAINS_FILE="/etc/codex/allowed_domains.txt" ALLOWED_DOMAINS_FILE="/etc/akode/allowed_domains.txt"
if [ -f "$ALLOWED_DOMAINS_FILE" ]; then if [ -f "$ALLOWED_DOMAINS_FILE" ]; then
ALLOWED_DOMAINS=() ALLOWED_DOMAINS=()
while IFS= read -r domain; do while IFS= read -r domain; do

View File

@@ -62,22 +62,22 @@ docker run --name "$CONTAINER_NAME" -d \
--cap-add=NET_ADMIN \ --cap-add=NET_ADMIN \
--cap-add=NET_RAW \ --cap-add=NET_RAW \
-v "$WORK_DIR:/app$WORK_DIR" \ -v "$WORK_DIR:/app$WORK_DIR" \
codex \ akode \
sleep infinity sleep infinity
# Write the allowed domains to a file in the container # Write the allowed domains to a file in the container
docker exec --user root "$CONTAINER_NAME" bash -c "mkdir -p /etc/codex" docker exec --user root "$CONTAINER_NAME" bash -c "mkdir -p /etc/akode"
for domain in $OPENAI_ALLOWED_DOMAINS; do for domain in $OPENAI_ALLOWED_DOMAINS; do
# Validate domain format to prevent injection # Validate domain format to prevent injection
if [[ ! "$domain" =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then if [[ ! "$domain" =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "Error: Invalid domain format: $domain" echo "Error: Invalid domain format: $domain"
exit 1 exit 1
fi fi
echo "$domain" | docker exec --user root -i "$CONTAINER_NAME" bash -c "cat >> /etc/codex/allowed_domains.txt" echo "$domain" | docker exec --user root -i "$CONTAINER_NAME" bash -c "cat >> /etc/akode/allowed_domains.txt"
done done
# Set proper permissions on the domains file # Set proper permissions on the domains file
docker exec --user root "$CONTAINER_NAME" bash -c "chmod 444 /etc/codex/allowed_domains.txt && chown root:root /etc/codex/allowed_domains.txt" docker exec --user root "$CONTAINER_NAME" bash -c "chmod 444 /etc/akode/allowed_domains.txt && chown root:root /etc/akode/allowed_domains.txt"
# Initialize the firewall inside the container as root user # Initialize the firewall inside the container as root user
docker exec --user root "$CONTAINER_NAME" bash -c "/usr/local/bin/init_firewall.sh" docker exec --user root "$CONTAINER_NAME" bash -c "/usr/local/bin/init_firewall.sh"
@@ -92,4 +92,4 @@ quoted_args=""
for arg in "$@"; do for arg in "$@"; do
quoted_args+=" $(printf '%q' "$arg")" quoted_args+=" $(printf '%q' "$arg")"
done done
docker exec -it "$CONTAINER_NAME" bash -c "cd \"/app$WORK_DIR\" && codex --sandbox workspace-write --ask-for-approval on-request ${quoted_args}" docker exec -it "$CONTAINER_NAME" bash -c "cd \"/app$WORK_DIR\" && akode --sandbox workspace-write --ask-for-approval on-request ${quoted_args}"

View File

@@ -1,4 +1,4 @@
// Run with CODEX_TEST_BINARY=/absolute/path/to/codex node --test codex-cli/tests/exit-status.test.mjs. // Run with AKODE_TEST_BINARY=/absolute/path/to/codex node --test akode-cli/tests/exit-status.test.mjs.
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { execFileSync, spawn, spawnSync } from "node:child_process"; import { execFileSync, spawn, spawnSync } from "node:child_process";
import { once } from "node:events"; import { once } from "node:events";
@@ -22,8 +22,8 @@ test(
}, },
async () => { async () => {
assert.ok( assert.ok(
process.env.CODEX_TEST_BINARY, process.env.AKODE_TEST_BINARY,
"Set CODEX_TEST_BINARY to a built Codex binary", "Set AKODE_TEST_BINARY to a built Codex binary",
); );
const directory = await mkdtemp(path.join(tmpdir(), "codex-npm-exit-")); const directory = await mkdtemp(path.join(tmpdir(), "codex-npm-exit-"));
let child; let child;
@@ -43,10 +43,10 @@ test(
const wrapper = path.join(directory, "bin", "codex.js"); const wrapper = path.join(directory, "bin", "codex.js");
await copyFile(new URL("../bin/codex.js", import.meta.url), wrapper); await copyFile(new URL("../bin/codex.js", import.meta.url), wrapper);
await symlink( await symlink(
path.resolve(process.env.CODEX_TEST_BINARY), path.resolve(process.env.AKODE_TEST_BINARY),
path.join(bin, "codex"), path.join(bin, "codex"),
); );
const env = { ...process.env, CODEX_HOME: home, CODEX_SQLITE_HOME: home }; const env = { ...process.env, AKODE_HOME: home, AKODE_SQLITE_HOME: home };
// A normal CLI argument error must retain its numeric exit status. // A normal CLI argument error must retain its numeric exit status.
const invalid = spawnSync( const invalid = spawnSync(

View File

@@ -16,7 +16,7 @@ ignore = [
"RUSTSEC-2026-0371", # zbus_names 3.0.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates "RUSTSEC-2026-0371", # zbus_names 3.0.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates
"RUSTSEC-2026-0372", # zvariant_derive 4.2.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates "RUSTSEC-2026-0372", # zvariant_derive 4.2.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates
# Reviewed 2026-10-20. # Reviewed 2026-10-20.
"RUSTSEC-2026-0374", # basic-toml 0.1.10 via i18n-config/i18n-embed-fl under age 0.12.1 in codex-secrets; no patched release; remove when age's localization dependencies migrate off basic-toml "RUSTSEC-2026-0374", # basic-toml 0.1.10 via i18n-config/i18n-embed-fl under age 0.12.1 in akode-secrets; no patched release; remove when age's localization dependencies migrate off basic-toml
"RUSTSEC-2026-0387", # crypto-bigint 0.5.5 via elliptic-curve 0.13.8 is used by age, AWS login, user verification, and WebRTC; timing leakage can affect private-key or session-secret operations; remove when these dependency paths use crypto-bigint >=0.7.6 "RUSTSEC-2026-0387", # crypto-bigint 0.5.5 via elliptic-curve 0.13.8 is used by age, AWS login, user verification, and WebRTC; timing leakage can affect private-key or session-secret operations; remove when these dependency paths use crypto-bigint >=0.7.6
# Reviewed 2026-10-26. # Reviewed 2026-10-26.
"RUSTSEC-2026-0391", # Codex, tonic and zip use zstd 0.13.3 without reusing borrowed contexts across streams. Remove when all paths use zstd >=0.14.3. "RUSTSEC-2026-0391", # Codex, tonic and zip use zstd 0.13.3 without reusing borrowed contexts across streams. Remove when all paths use zstd >=0.14.3.
@@ -24,7 +24,7 @@ ignore = [
"RUSTSEC-2026-0403", # zstd 0.13.3 pulls in zstd-safe 7.2.4. Codex, tonic and zip use read decoders or initialized output buffers and discard output on error. Remove when all paths use zstd-safe >=8.2.0. "RUSTSEC-2026-0403", # zstd 0.13.3 pulls in zstd-safe 7.2.4. Codex, tonic and zip use read decoders or initialized output buffers and discard output on error. Remove when all paths use zstd-safe >=8.2.0.
"RUSTSEC-2026-0410", # zstd-safe 7.2.4 pulls in zstd-sys 2.0.16. Its allocator bug only affects wasm32, and Codex ships native binaries. Remove when the lockfile uses zstd-sys >=2.1.2. "RUSTSEC-2026-0410", # zstd-safe 7.2.4 pulls in zstd-sys 2.0.16. Its allocator bug only affects wasm32, and Codex ships native binaries. Remove when the lockfile uses zstd-sys >=2.1.2.
# Reviewed 2026-10-29. # Reviewed 2026-10-29.
"RUSTSEC-2026-0418", # libz-sys 1.1.29 via curl-sys/curl in codex-http-client is Windows-only and skips the affected probe; cc is locked to 1.2.55 (<1.6.0). Remove when libz-sys >=1.1.31; reassess if used on Unix with cc >=1.6.0. "RUSTSEC-2026-0418", # libz-sys 1.1.29 via curl-sys/curl in akode-http-client is Windows-only and skips the affected probe; cc is locked to 1.2.55 (<1.6.0). Remove when libz-sys >=1.1.31; reassess if used on Unix with cc >=1.6.0.
# Reviewed 2026-11-05. # Reviewed 2026-11-05.
"RUSTSEC-2026-0441", # pin-utils 0.1.0 via AWS Smithy and loom under tokio-graceful; unmaintained with no patched release; remove when these paths drop pin-utils "RUSTSEC-2026-0441", # pin-utils 0.1.0 via AWS Smithy and loom under tokio-graceful; unmaintained with no patched release; remove when these paths drop pin-utils
] ]

View File

@@ -7,18 +7,18 @@ retries = 1
[[profile.default.overrides]] [[profile.default.overrides]]
# These cases cold-start a daemon before confirming a second launch with new settings. # These cases cold-start a daemon before confirming a second launch with new settings.
filter = 'package(codex-cli) & binary(daemon_startup) & test(requires_confirmation_to_disable_)' filter = 'package(akode-cli) & binary(daemon_startup) & test(requires_confirmation_to_disable_)'
slow-timeout = { period = "1m", terminate-after = 2 } slow-timeout = { period = "1m", terminate-after = 2 }
[[profile.default.overrides]] [[profile.default.overrides]]
# This case validates and copies both the initial and replacement debug package. # This case validates and copies both the initial and replacement debug package.
filter = 'package(codex-cli) & binary(=app_server_daemon_package) & test(=packaged_daemon_start_and_explicit_replacement)' filter = 'package(akode-cli) & binary(=app_server_daemon_package) & test(=packaged_daemon_start_and_explicit_replacement)'
slow-timeout = { period = "1m", terminate-after = 3 } slow-timeout = { period = "1m", terminate-after = 3 }
threads-required = "num-test-threads" threads-required = "num-test-threads"
[[profile.default.overrides]] [[profile.default.overrides]]
# These copies must not compete with other tests on the same runner. # These copies must not compete with other tests on the same runner.
filter = 'package(codex-cli) & binary(=app_server_daemon_package)' filter = 'package(akode-cli) & binary(=app_server_daemon_package)'
slow-timeout = { period = "1m", terminate-after = 2 } slow-timeout = { period = "1m", terminate-after = 2 }
threads-required = "num-test-threads" threads-required = "num-test-threads"
@@ -58,7 +58,7 @@ slow-timeout = { period = "1m", terminate-after = 4 }
[[profile.default.overrides]] [[profile.default.overrides]]
# This end-to-end case launches several CLI subprocesses and checks cloud policy. # This end-to-end case launches several CLI subprocesses and checks cloud policy.
filter = 'package(codex-exec) & test(worktree_start_and_fork_use_host_pool_and_preserve_legacy_resume)' filter = 'package(akode-exec) & test(worktree_start_and_fork_use_host_pool_and_preserve_legacy_resume)'
slow-timeout = { period = "30s", terminate-after = 4 } slow-timeout = { period = "30s", terminate-after = 4 }
[[profile.default.overrides]] [[profile.default.overrides]]
@@ -66,25 +66,25 @@ filter = 'test(approval_matrix_covers_all_modes)'
slow-timeout = { period = "30s", terminate-after = 2 } slow-timeout = { period = "30s", terminate-after = 2 }
[[profile.default.overrides]] [[profile.default.overrides]]
filter = 'package(codex-app-server-protocol) & (test(typescript_schema_fixtures_match_generated) | test(json_schema_fixtures_match_generated) | test(generate_ts_with_experimental_api_retains_experimental_entries) | test(generated_ts_optional_nullable_fields_only_in_params) | test(generate_json_filters_experimental_fields_and_methods))' filter = 'package(akode-app-server-protocol) & (test(typescript_schema_fixtures_match_generated) | test(json_schema_fixtures_match_generated) | test(generate_ts_with_experimental_api_retains_experimental_entries) | test(generated_ts_optional_nullable_fields_only_in_params) | test(generate_json_filters_experimental_fields_and_methods))'
test-group = 'app_server_protocol_codegen' test-group = 'app_server_protocol_codegen'
[[profile.default.overrides]] [[profile.default.overrides]]
# These integration tests spawn a fresh app-server subprocess per case. # These integration tests spawn a fresh app-server subprocess per case.
# Keep the library unit tests parallel. # Keep the library unit tests parallel.
filter = 'package(codex-app-server) & kind(test)' filter = 'package(akode-app-server) & kind(test)'
test-group = 'app_server_integration' test-group = 'app_server_integration'
[[profile.local.overrides]] [[profile.local.overrides]]
# Use up to four app-server subprocesses locally. The global nextest pool still # Use up to four app-server subprocesses locally. The global nextest pool still
# limits this to the machine's logical CPU count. # limits this to the machine's logical CPU count.
filter = 'package(codex-app-server) & kind(test)' filter = 'package(akode-app-server) & kind(test)'
test-group = 'app_server_integration_local' test-group = 'app_server_integration_local'
[[profile.default.overrides]] [[profile.default.overrides]]
# These tests exercise full Codex turns and apply_patch execution, and they are # These tests exercise full Codex turns and apply_patch execution, and they are
# sensitive to Windows runner process-startup stalls when many cases launch at once. # sensitive to Windows runner process-startup stalls when many cases launch at once.
filter = 'package(codex-core) & kind(test) & test(apply_patch_cli)' filter = 'package(akode-core) & kind(test) & test(apply_patch_cli)'
test-group = 'core_apply_patch_cli_integration' test-group = 'core_apply_patch_cli_integration'
[[profile.default.overrides]] [[profile.default.overrides]]
@@ -92,16 +92,16 @@ test-group = 'core_apply_patch_cli_integration'
# starting their timeout; their file lock still coordinates other test processes. # starting their timeout; their file lock still coordinates other test processes.
platform = 'cfg(windows)' platform = 'cfg(windows)'
filter = ''' filter = '''
(package(codex-core) & binary(windows_sandbox)) | (package(akode-core) & binary(windows_sandbox)) |
(package(codex-exec-server) & test(file_system_elevated_relative_read_denial_uses_policy_cwd)) | (package(akode-exec-server) & test(file_system_elevated_relative_read_denial_uses_policy_cwd)) |
(package(codex-windows-sandbox) & test(elevated_non_tty_cmd_forwards_env_output_and_exit)) (package(akode-windows-sandbox) & test(elevated_non_tty_cmd_forwards_env_output_and_exit))
''' '''
test-group = 'windows_sandbox_accounts' test-group = 'windows_sandbox_accounts'
[[profile.default.overrides]] [[profile.default.overrides]]
# These tests create restricted-token Windows child processes and private desktops. # These tests create restricted-token Windows child processes and private desktops.
# Serialize them to avoid exhausting Windows session/global desktop resources in CI. # Serialize them to avoid exhausting Windows session/global desktop resources in CI.
filter = 'package(codex-windows-sandbox) & test(legacy_)' filter = 'package(akode-windows-sandbox) & test(legacy_)'
test-group = 'windows_sandbox_legacy_sessions' test-group = 'windows_sandbox_legacy_sessions'
[[profile.default.overrides]] [[profile.default.overrides]]

107
akode-rs/BUILD.bazel Normal file
View File

@@ -0,0 +1,107 @@
load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
load("//bazel/rules:runtime_package.bzl", "runtime_archive")
exports_files([
"clippy.toml",
])
filegroup(
name = "workspace-files",
srcs = glob(
[
"*",
".cargo/**",
],
exclude = [
"BUILD.bazel",
],
),
visibility = ["//visibility:public"],
)
test_suite(
name = "e2e-benchmarks",
tags = ["manual"],
tests = [
"//akode-rs/cli:codex-help-bench",
],
visibility = ["//visibility:public"],
)
string_flag(
name = "runtime_package_build_mode",
build_setting_default = "release",
values = [
"release",
"debug",
],
visibility = ["//visibility:public"],
)
alias(
name = "runtime_package",
actual = ":runtime_package_combined",
tags = ["manual"],
visibility = ["//visibility:public"],
)
# These targets produce flat staging archives for the existing signing and
# packaging steps. Release builds retain their binaries and debug symbols.
runtime_archive(
name = "runtime_package_combined",
srcs = [
"//akode-rs/app-server:release_files",
"//akode-rs/cli:release_files",
"//akode-rs/code-mode-host:release_files",
"//akode-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//akode-rs/bwrap:release_files"],
"@platforms//os:windows": [
"//akode-rs/windows-sandbox-rs:command-runner-release_files",
"//akode-rs/windows-sandbox-rs:sandbox-setup-release_files",
],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_primary",
srcs = [
"//akode-rs/cli:release_files",
"//akode-rs/code-mode-host:release_files",
"//akode-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//akode-rs/bwrap:release_files"],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_app-server",
srcs = [
"//akode-rs/app-server:release_files",
"//akode-rs/code-mode-host:release_files",
"//akode-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//akode-rs/bwrap:release_files"],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_helpers",
srcs = [
"//akode-rs/windows-sandbox-rs:command-runner-release_files",
"//akode-rs/windows-sandbox-rs:sandbox-setup-release_files",
"//akode-rs/windows-sandbox-service:release_files",
],
tags = ["manual"],
target_compatible_with = ["@platforms//os:windows"],
visibility = ["//visibility:public"],
)

File diff suppressed because it is too large Load Diff

662
akode-rs/Cargo.toml Normal file
View File

@@ -0,0 +1,662 @@
[workspace]
members = [
"aws-auth",
"agent-graph-store",
"agent-message-board-client",
"agent-message-board-host",
"agent-roles",
"bwrap",
"build-info",
"ansi-escape",
"attachment-store",
"async-utils",
"app-server",
"app-server-transport",
"app-server-daemon",
"app-server-client",
"app-server-protocol",
"app-server-protocol-noop-macros",
"app-server-test-client",
"apply-patch",
"arg0",
"feedback",
"features",
"install-context",
"update",
"telegram",
"code-mode",
"code-mode-host",
"code-mode-protocol",
"code-mode-runtime",
"plugin-host",
"akode-home",
"cli",
"collaboration-mode-templates",
"config",
"config-schema",
"context-fragments",
"shell-command",
"skills",
"core",
"core-api",
"core-plugin-common",
"core-plugins",
"diagnostics",
"direct-tool-timing",
"guardian-context",
"hooks",
"history",
"http-client",
"secrets",
"exec",
"file-system",
"exec-server-protocol",
"exec-server",
"exec-server-cli",
"exec-server/tests/support",
"execpolicy",
"ext/agent",
"ext/agent-message-board",
"ext/extension-api",
"ext/multi-env-copy-file",
"ext/goal",
"ext/git-attribution",
"ext/guardian-reviewer",
"ext/guardian-v2",
"ext/guardian-v3",
"ext/items",
"code-graph",
"ext/code-graph",
"ext/memoria",
"ext/mcp",
"ext/queue",
"ext/skills",
"ext/web-search",
"external-agent-migration",
"keyring-store",
"file-search",
"file-watcher",
"linux-sandbox",
"lmstudio",
"login",
"akode-mcp",
"mermaid",
"message-board",
"message-board-mcp",
"model-provider-info",
"mxc-sandbox",
"models-manager",
"network-proxy",
"ollama",
"process-hardening",
"realtime-webrtc",
"voice-host",
"protocol",
"protocol/tests/support",
"prompts",
"rollout",
"rollout-trace",
"rmcp-client",
"response-debug-context",
"sandboxing",
"stdio-to-uds",
"otel",
"tcp-tunnel",
"tui",
"user-verification",
"tools",
"v8-poc",
"websocket-auth",
"websocket-client",
"windows-sandbox-rs/tests/support",
"windows-sandbox-service",
"worktree",
"utils/absolute-path",
"utils/audio",
"utils/path-uri",
"utils/cargo-bin",
"git-utils",
"utils/cache",
"utils/critical-path",
"utils/git-discovery",
"utils/head-tail-buffer",
"utils/image",
"utils/json-to-toml",
"utils/home-dir",
"utils/process",
"utils/pty",
"utils/readiness",
"utils/redacted-string",
"utils/rustls-provider",
"utils/string",
"web-tools",
"utils/cli",
"utils/elapsed",
"utils/sandbox-summary",
"utils/model-facing-id",
"utils/sleep-inhibitor",
"utils/approval-presets",
"utils/oss",
"utils/output-truncation",
"utils/path-utils",
"utils/plugins",
"utils/fuzzy-match",
"utils/stream-parser",
"utils/template",
"akode-client",
"akode-api",
"state",
"terminal-detection",
"test-binary-support",
"thread-manager-sample",
"thread-store",
"uds",
"akode-experimental-api-macros",
"plugin",
"model-provider",
]
resolver = "2"
[workspace.package]
version = "0.9.1"
# Track the edition for all workspace crates in one place. Individual
# crates can still override this value, but keeping it here means new
# crates created with `cargo new -w ...` automatically inherit the 2024
# edition.
edition = "2024"
license = "Apache-2.0"
[workspace.dependencies]
# Internal
akode-realtime-webrtc = { path = "realtime-webrtc" }
app_test_support = { path = "app-server/tests/common" }
akode-agent-graph-store = { path = "agent-graph-store" }
akode-agent-roles = { path = "agent-roles" }
akode-ansi-escape = { path = "ansi-escape" }
akode-api = { path = "akode-api" }
akode-attachment-store = { path = "attachment-store" }
akode-aws-auth = { path = "aws-auth" }
akode-app-server = { path = "app-server" }
akode-app-server-transport = { path = "app-server-transport" }
akode-app-server-daemon = { path = "app-server-daemon" }
akode-app-server-client = { path = "app-server-client" }
akode-app-server-protocol = { path = "app-server-protocol" }
akode-app-server-protocol-noop-macros = { path = "app-server-protocol-noop-macros" }
akode-app-server-test-client = { path = "app-server-test-client" }
akode-apply-patch = { path = "apply-patch" }
akode-arg0 = { path = "arg0" }
akode-async-utils = { path = "async-utils" }
akode-build-info = { path = "build-info" }
akode-client = { path = "akode-client" }
akode-collaboration-mode-templates = { path = "collaboration-mode-templates" }
akode-code-mode = { path = "code-mode" }
akode-code-mode-protocol = { path = "code-mode-protocol" }
akode-code-mode-runtime = { path = "code-mode-runtime" }
akode-plugin-host = { path = "plugin-host" }
akode-home = { path = "akode-home" }
akode-http-client = { path = "http-client" }
akode-websocket-auth = { path = "websocket-auth" }
akode-websocket-client = { path = "websocket-client" }
akode-config = { path = "config" }
akode-agent-message-board-client = { path = "agent-message-board-client" }
akode-agent-message-board-extension = { path = "ext/agent-message-board" }
akode-agent-message-board-host = { path = "agent-message-board-host" }
akode-message-board = { path = "message-board" }
akode-message-board-mcp = { path = "message-board-mcp" }
akode-context-fragments = { path = "context-fragments" }
akode-core = { path = "core" }
akode-core-api = { path = "core-api" }
akode-core-plugin-common = { path = "core-plugin-common" }
akode-core-plugins = { path = "core-plugins" }
akode-diagnostics = { path = "diagnostics" }
akode-direct-tool-timing = { path = "direct-tool-timing" }
akode-exec = { path = "exec" }
akode-file-system = { path = "file-system" }
akode-exec-server-protocol = { path = "exec-server-protocol" }
akode-exec-server = { path = "exec-server" }
akode-exec-server-cli = { path = "exec-server-cli" }
akode-exec-server-test-support = { path = "exec-server/tests/support" }
akode-execpolicy = { path = "execpolicy" }
akode-extension-api = { path = "ext/extension-api" }
akode-extension-items = { path = "ext/items" }
akode-multi-env-copy-file = { path = "ext/multi-env-copy-file" }
akode-goal-extension = { path = "ext/goal" }
akode-git-attribution = { path = "ext/git-attribution" }
akode-guardian-reviewer = { path = "ext/guardian-reviewer" }
akode-guardian-v2 = { path = "ext/guardian-v2" }
akode-guardian-v3 = { path = "ext/guardian-v3" }
akode-external-agent-migration = { path = "external-agent-migration" }
akode-experimental-api-macros = { path = "akode-experimental-api-macros" }
akode-features = { path = "features" }
akode-feedback = { path = "feedback" }
akode-install-context = { path = "install-context" }
akode-update = { path = "update" }
akode-telegram = { path = "telegram" }
akode-file-search = { path = "file-search" }
akode-file-watcher = { path = "file-watcher" }
akode-git-utils = { path = "git-utils" }
akode-guardian-context = { path = "guardian-context" }
akode-hooks = { path = "hooks" }
akode-history = { path = "history" }
akode-keyring-store = { path = "keyring-store" }
akode-linux-sandbox = { path = "linux-sandbox" }
akode-lmstudio = { path = "lmstudio" }
akode-login = { path = "login" }
akode-mermaid = { path = "mermaid" }
akode-message-history = { path = "message-history" }
akode-code-graph = { path = "code-graph" }
akode-code-graph-extension = { path = "ext/code-graph" }
akode-memoria-extension = { path = "ext/memoria" }
akode-web-search-extension = { path = "ext/web-search" }
akode-web-tools = { path = "web-tools" }
akode-mcp = { path = "akode-mcp" }
akode-mcp-extension = { path = "ext/mcp" }
akode-model-provider-info = { path = "model-provider-info" }
akode-models-manager = { path = "models-manager" }
akode-mxc-sandbox = { path = "mxc-sandbox" }
akode-network-proxy = { path = "network-proxy" }
akode-ollama = { path = "ollama" }
akode-otel = { path = "otel" }
akode-plugin = { path = "plugin" }
akode-model-provider = { path = "model-provider" }
akode-process-hardening = { path = "process-hardening" }
akode-protocol = { path = "protocol" }
akode-protocol-test-support = { path = "protocol/tests/support" }
akode-prompts = { path = "prompts" }
akode-queue-extension = { path = "ext/queue" }
akode-response-debug-context = { path = "response-debug-context" }
akode-rmcp-client = { path = "rmcp-client" }
akode-rollout = { path = "rollout" }
akode-rollout-trace = { path = "rollout-trace" }
akode-sandboxing = { path = "sandboxing" }
akode-secrets = { path = "secrets" }
akode-shell-command = { path = "shell-command" }
akode-skills-extension = { path = "ext/skills" }
akode-skills = { path = "skills" }
akode-state = { path = "state" }
akode-stdio-to-uds = { path = "stdio-to-uds" }
akode-terminal-detection = { path = "terminal-detection" }
akode-test-binary-support = { path = "test-binary-support" }
akode-thread-store = { path = "thread-store" }
akode-tools = { path = "tools" }
akode-tcp-tunnel = { path = "tcp-tunnel" }
akode-tui = { path = "tui" }
akode-uds = { path = "uds" }
akode-utils-absolute-path = { path = "utils/absolute-path" }
akode-utils-approval-presets = { path = "utils/approval-presets" }
akode-utils-audio = { path = "utils/audio" }
akode-utils-cache = { path = "utils/cache" }
akode-utils-cargo-bin = { path = "utils/cargo-bin" }
akode-utils-cli = { path = "utils/cli" }
akode-utils-critical-path = { path = "utils/critical-path" }
akode-utils-elapsed = { path = "utils/elapsed" }
akode-utils-fuzzy-match = { path = "utils/fuzzy-match" }
akode-utils-git-discovery = { path = "utils/git-discovery" }
akode-utils-head-tail-buffer = { path = "utils/head-tail-buffer" }
akode-utils-home-dir = { path = "utils/home-dir" }
akode-utils-image = { path = "utils/image" }
akode-utils-json-to-toml = { path = "utils/json-to-toml" }
akode-utils-oss = { path = "utils/oss" }
akode-utils-output-truncation = { path = "utils/output-truncation" }
akode-utils-path = { path = "utils/path-utils" }
akode-utils-path-uri = { path = "utils/path-uri" }
akode-utils-plugins = { path = "utils/plugins" }
akode-utils-process = { path = "utils/process" }
akode-utils-pty = { path = "utils/pty" }
akode-utils-redacted-string = { path = "utils/redacted-string" }
akode-utils-rustls-provider = { path = "utils/rustls-provider" }
akode-utils-sandbox-summary = { path = "utils/sandbox-summary" }
akode-worktree = { path = "worktree" }
akode-utils-sleep-inhibitor = { path = "utils/sleep-inhibitor" }
akode-utils-stream-parser = { path = "utils/stream-parser" }
akode-utils-string = { path = "utils/string" }
akode-utils-template = { path = "utils/template" }
akode-user-verification = { path = "user-verification" }
akode-v8-poc = { path = "v8-poc" }
akode-windows-sandbox = { path = "windows-sandbox-rs" }
akode-windows-sandbox-test-support = { path = "windows-sandbox-rs/tests/support" }
core_test_support = { path = "core/tests/common" }
# External
age = "0.12.1"
ansi-to-tui = "8.0.1"
anyhow = "1"
arboard = { version = "3", features = ["wayland-data-control"] }
arc-swap = "1.9.0"
assert_cmd = "2"
assert_matches = "1.5.0"
async-channel = "2.3.1"
async-io = "2.6.0"
async-stream = "0.3.6"
aws-config = "1"
aws-credential-types = "1"
aws-sigv4 = "1"
aws-smithy-runtime-api = { version = "1", features = ["client", "http-1x"] }
aws-smithy-types = { version = "1", features = ["http-body-1-x"] }
aws-types = "1"
axum = { version = "0.8", default-features = false }
base64 = "0.22.1"
bitflags = "2.13.1"
blake3 = "1.8.2"
bm25 = "2.3.2"
bytes = "1.10.1"
caseless = "0.2.2"
chardetng = "0.1.17"
chrono = "0.4.43"
clap = "4"
clap_complete = "4"
clatter = { version = "2.2.0", default-features = false, features = [
"alloc",
"getrandom",
"use-25519",
"use-aes-gcm",
"use-rust-crypto-ml-kem",
"use-sha",
] }
color-eyre = "0.6.3"
constant_time_eq = "0.3.1"
crossbeam-channel = "0.5.15"
crypto_box = { version = "0.9.1", features = ["seal"] }
crossterm = "0.29.0"
ctor = "0.6.3"
deno_core_icudata = "0.78.0"
derive_more = "2"
diffy = "0.4.2"
dirs = "6"
divan = "0.1.21"
dns-lookup = "3.0.1"
dotenvy = "0.15.7"
dunce = "1.0.4"
ed25519-dalek = { version = "2.2.0", features = ["pkcs8"] }
encoding_rs = "0.8.35"
eventsource-stream = "0.2.3"
file-id = "0.2.3"
flatbuffers = "25"
flate2 = "1.1.8"
futures = { version = "0.3", default-features = false }
gethostname = "1.1.0"
gix = { version = "0.89.0", default-features = false, features = ["sha1"] }
gix-url = "0.40.0"
glob = "0.3"
globset = "0.4"
hmac = "0.12.1"
http = "1.3.1"
httpdate = "1.0.3"
hyper-util = { version = "0.1.20", features = ["tokio"] }
iana-time-zone = "0.1.64"
icu_decimal = "2.1"
icu_locale_core = "2.1"
icu_provider = { version = "2.1", features = ["sync"] }
ignore = "0.4.30"
image = { version = "^0.25.9", default-features = false }
include_dir = "0.7.4"
indexmap = "2.12.0"
insta = "1.46.3"
inventory = "0.3.19"
itertools = "0.14.0"
jsonptr = { version = "0.7.1", default-features = false }
jsonwebtoken = "9.3.1"
keyring = { version = "3.6", default-features = false }
landlock = "0.4.4"
lazy_static = "1"
libc = "0.2.182"
# Keep SQLx's bundled SQLite on a version containing the WAL-reset corruption fix:
# https://www.sqlite.org/wal.html#the_wal_reset_bug
libsqlite3-sys = { version = "0.37", default-features = false }
linkify = "0.11"
log = "0.4"
lru = "0.18.2"
maplit = "1.0.2"
memchr = "2.7.6"
mime_guess = "2.0.5"
multimap = "0.10.0"
mxc-sdk = { git = "https://github.com/microsoft/mxc", rev = "b21120168d70befe12356411423266bfef168446" }
notify = "8.2.0"
nucleo = { git = "https://github.com/helix-editor/nucleo.git", rev = "4253de9faabb4e5c6d81d946a5e35a90f87347ee" }
once_cell = "1.20.2"
openssl-sys = "*"
opentelemetry = "0.31.0"
opentelemetry-semantic-conventions = "0.31.0"
opentelemetry_sdk = "0.31.0"
os_info = "3.12.0"
owo-colors = "4.3.0"
pathdiff = "0.2"
portable-pty = "0.9.0"
predicates = "3"
pretty_assertions = "1.4.1"
pulldown-cmark = { version = "0.10", default-features = false }
quick-xml = "0.41.0"
rand = "0.9"
rand_regex = "0.18.1"
ratatui = { version = "0.30.2", default-features = false, features = [
"crossterm",
"layout-cache",
"underline-color",
] }
ratatui-macros = "0.7.2"
rcgen = { version = "0.14.7", default-features = false, features = [
"aws_lc_rs",
"pem",
] }
regex = "1.12.3"
regex-automata = { version = "0.4.13", default-features = false, features = ["std", "syntax", "unicode", "nfa-pikevm"] }
regex-lite = "0.1.8"
regex-syntax = "0.8.8"
reqwest = { version = "0.12", features = ["cookies"] }
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", rev = "98a54789b80110ad210495c4ad845c89e1980471", version = "=3.5.1", default-features = false }
runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" }
rustix = { version = "1.1.4", features = ["net"] }
rustls = { version = "0.23.46", default-features = false, features = [
"aws_lc_rs",
"std",
] }
rustls-native-certs = "0.8.3"
rustls-pki-types = "1.14.0"
schemars = "0.8.22"
seccompiler = "0.5.0"
semver = "1.0"
serde = { version = "1", features = ["rc"] }
serde_ignored = "0.1.14"
serde_json = "1"
serde_path_to_error = "0.1.20"
serde_with = "3.17"
serde_yaml = "0.9"
serial_test = "3.2.0"
sha1 = "0.10.6"
scopeguard = "1.2.0"
sha2 = "0.10"
shlex = "1.3.0"
signal-hook = "0.3.18"
similar = "2.7.0"
symphonia = { version = "0.6.0", default-features = false, features = [
"isomp4",
"mkv",
"mp3",
"ogg",
"wav",
] }
# Keep SQLx versions in sync; when bumping, audit the SQLite constructor deny list in clippy.toml.
sqlx = { version = "=0.9.0", default-features = false, features = [
"chrono",
"json",
"migrate",
"runtime-tokio",
"tls-rustls",
"sqlite-bundled",
"time",
"uuid",
] }
# Derives and migration embedding do not need query macros or a host SQLite driver.
sqlx-macros = { version = "=0.9.0", default-features = false, features = ["derive", "migrate"] }
# Preserve the target driver's query-description support without building it on the host.
sqlx-sqlite = { version = "=0.9.0", default-features = false, features = ["offline"] }
starlark = { version = "0.14.2", default-features = false }
strum = "0.27.2"
strum_macros = "0.28.0"
supports-color = "3.0.2"
syntect = "5"
sys-locale = "0.3.2"
system-configuration = "0.7"
tar = { version = "=0.4.45", default-features = false }
tempfile = "3.23.0"
test-log = "0.2.19"
textwrap = "0.16.2"
thiserror = "2.0.17"
tikv-jemallocator = "=0.7.0"
time = "0.3.47"
tiny_http = "0.12"
tokio = "1"
tokio-rustls = "0.26.4"
tokio-stream = "0.1.18"
tokio-test = "0.4"
tokio-tungstenite = { version = "0.28.0", features = [
"proxy",
"rustls-tls-native-roots",
] }
tokio-util = "0.7.18"
toml = "0.9.5"
toml_edit = "0.24.0"
tracing = "0.1.44"
tracing-appender = "0.2.3"
tracing-opentelemetry = "0.32.0"
tracing-subscriber = "0.3.22"
tracing-test = "0.2.5"
tonic = { version = "0.14.3", default-features = false, features = ["channel", "codegen"] }
tonic-prost = "0.14.3"
tree-sitter = "0.25.10"
tree-sitter-bash = "0.25"
tree-sitter-powershell = "=0.26.4"
ts-rs = "11"
tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] }
uds_windows = "1.1.0"
unicode-linebreak = "0.1.5"
unicode-normalization = "0.1.25"
unicode-segmentation = "1.12.0"
unicode-width = "0.2"
url = "2"
urlencoding = "2.1"
uuid = "1"
v8 = "=152.2.0"
vt100 = "0.16.2"
vtparse = "0.6.2"
walkdir = "2.5.0"
webbrowser = "1.2.2"
which = "8"
whoami = "1.6.1"
wildmatch = "2.6.1"
winapi-util = "0.1.11"
windows-sys = "0.61.2"
winreg = "0.55.0"
# Keep the zip 2.x feature set. In zip 9, `bzip2-rs` selects the bzip2-sys
# backend we already build; the default selects libbz2-rs-sys instead.
zip = { version = "9.0.0", default-features = false, features = [
"aes-crypto",
"bzip2-rs",
"deflate",
"deflate64",
"lzma",
"time",
"xz",
"zstd",
] }
zstd = "0.13"
wiremock = "0.6"
zeroize = "1.8.2"
[workspace.lints]
rust = {}
[workspace.lints.clippy]
await_holding_invalid_type = "deny"
await_holding_lock = "deny"
disallowed_methods = "deny"
expect_used = "deny"
identity_op = "deny"
manual_clamp = "deny"
manual_filter = "deny"
manual_find = "deny"
manual_flatten = "deny"
manual_map = "deny"
manual_memcpy = "deny"
manual_non_exhaustive = "deny"
manual_ok_or = "deny"
manual_range_contains = "deny"
manual_retain = "deny"
manual_strip = "deny"
manual_try_fold = "deny"
manual_unwrap_or = "deny"
needless_borrow = "deny"
needless_borrowed_reference = "deny"
needless_collect = "deny"
needless_late_init = "deny"
needless_option_as_deref = "deny"
needless_question_mark = "deny"
needless_update = "deny"
redundant_clone = "deny"
redundant_closure = "deny"
redundant_closure_for_method_calls = "deny"
redundant_static_lifetimes = "deny"
trivially_copy_pass_by_ref = "deny"
uninlined_format_args = "deny"
unnecessary_filter_map = "deny"
unnecessary_lazy_evaluations = "deny"
unnecessary_sort_by = "deny"
unnecessary_to_owned = "deny"
unwrap_used = "deny"
# cargo-shear cannot see the platform-specific openssl-sys usage, so we
# silence the false positive here instead of deleting a real dependency.
[workspace.metadata.cargo-shear]
ignored = [
"icu_provider",
"openssl-sys",
"akode-v8-poc",
]
[profile.dev]
# The test profile inherits dev. Keep source locations in ordinary builds;
# use CARGO_PROFILE_DEV_DEBUG=full (or CARGO_PROFILE_TEST_DEBUG=full) for locals.
debug = "line-tables-only"
[profile.dev-small]
inherits = "dev"
opt-level = 0
debug = "none"
strip = "symbols"
[profile.release]
lto = "thin"
debug = "line-tables-only"
split-debuginfo = "off"
# Keep release binaries symbolicateable until packaging has archived the
# sidecar symbols and stripped the binaries.
strip = false
# Balance parallel release code generation against binary size.
codegen-units = 4
[profile.profiling]
inherits = "release"
debug = "full"
lto = false
strip = false
[profile.ci-test]
# Reduce binary size to reduce disk pressure.
inherits = "test"
opt-level = 0
[patch.crates-io]
# Uncomment to debug local changes.
# ratatui = { path = "../../ratatui" }
crossterm = { git = "https://github.com/openai-oss-forks/crossterm", rev = "ed1cdab335221515706178d68495bba2aed1924f" }
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "02cb49fa827411e9279e3688d19ab9e82661b0e8" }
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "db4be399bc1b8b5de2edb46c7187834edabf7e30" }
v8 = { git = "https://github.com/openai-oss-forks/rusty_v8.git", rev = "90a65f887a0c0f048f3784afbcb320b373c8a2e0" }
# Uncomment to debug local changes.
# rmcp = { path = "../../rust-sdk/crates/rmcp" }
[patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"]
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "db4be399bc1b8b5de2edb46c7187834edabf7e30" }

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-graph-store",
crate_name = "akode_agent_graph_store",
)

View File

@@ -0,0 +1,26 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-agent-graph-store"
version.workspace = true
[lib]
name = "akode_agent_graph_store"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
akode-protocol = { workspace = true }
akode-state = { workspace = true }
serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
[dev-dependencies]
akode-utils-absolute-path = { workspace = true }
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync"] }

View File

@@ -0,0 +1,344 @@
use akode_protocol::ThreadId;
use akode_state::StateRuntime;
use std::sync::Arc;
use crate::AgentGraphStore;
use crate::AgentGraphStoreError;
use crate::AgentGraphStoreFuture;
use crate::ThreadSpawnEdgeStatus;
/// SQLite-backed implementation of [`AgentGraphStore`] using an existing state runtime.
#[derive(Clone)]
pub struct LocalAgentGraphStore {
state_db: Arc<StateRuntime>,
}
impl std::fmt::Debug for LocalAgentGraphStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LocalAgentGraphStore")
.field("sqlite", self.state_db.sqlite())
.finish_non_exhaustive()
}
}
impl LocalAgentGraphStore {
/// Create a local graph store from an already-initialized state runtime.
pub fn new(state_db: Arc<StateRuntime>) -> Self {
Self { state_db }
}
}
impl AgentGraphStore for LocalAgentGraphStore {
fn upsert_thread_spawn_edge(
&self,
parent_thread_id: ThreadId,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
Box::pin(async move {
self.state_db
.upsert_thread_spawn_edge(
parent_thread_id,
child_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error)
})
}
fn set_thread_spawn_edge_status(
&self,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
Box::pin(async move {
self.state_db
.set_thread_spawn_edge_status(child_thread_id, to_state_status(status))
.await
.map_err(internal_error)
})
}
fn list_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
Box::pin(async move {
if let Some(status) = status_filter {
return self
.state_db
.list_thread_spawn_children_with_status(
parent_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error);
}
self.state_db
.list_thread_spawn_children(parent_thread_id)
.await
.map_err(internal_error)
})
}
fn list_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
Box::pin(async move {
match status_filter {
Some(status) => self
.state_db
.list_thread_spawn_descendants_with_status(
root_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error),
None => self
.state_db
.list_thread_spawn_descendants(root_thread_id)
.await
.map_err(internal_error),
}
})
}
}
fn to_state_status(status: ThreadSpawnEdgeStatus) -> akode_state::DirectionalThreadSpawnEdgeStatus {
match status {
ThreadSpawnEdgeStatus::Open => akode_state::DirectionalThreadSpawnEdgeStatus::Open,
ThreadSpawnEdgeStatus::Closed => akode_state::DirectionalThreadSpawnEdgeStatus::Closed,
}
}
fn internal_error(err: impl std::fmt::Display) -> AgentGraphStoreError {
AgentGraphStoreError::Internal {
message: err.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use akode_state::DirectionalThreadSpawnEdgeStatus;
use akode_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
struct TestRuntime {
state_db: Arc<StateRuntime>,
_codex_home: TempDir,
}
fn thread_id(suffix: u128) -> ThreadId {
ThreadId::from_string(&format!("00000000-0000-0000-0000-{suffix:012}"))
.expect("valid thread id")
}
async fn state_runtime() -> TestRuntime {
let codex_home = TempDir::new().expect("tempdir should be created");
let state_db = StateRuntime::init(
akode_state::SqliteConfig::new_for_testing(codex_home.path().abs()),
"test-provider".to_string(),
)
.await
.expect("state db should initialize");
TestRuntime {
state_db,
_codex_home: codex_home,
}
}
#[tokio::test]
async fn local_store_upserts_and_lists_direct_children_with_status_filters() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db.clone());
let parent_thread_id = thread_id(/*suffix*/ 1);
let first_child_thread_id = thread_id(/*suffix*/ 2);
let second_child_thread_id = thread_id(/*suffix*/ 3);
store
.upsert_thread_spawn_edge(
parent_thread_id,
second_child_thread_id,
ThreadSpawnEdgeStatus::Closed,
)
.await
.expect("closed child edge should insert");
store
.upsert_thread_spawn_edge(
parent_thread_id,
first_child_thread_id,
ThreadSpawnEdgeStatus::Open,
)
.await
.expect("open child edge should insert");
let all_children = store
.list_thread_spawn_children(parent_thread_id, /*status_filter*/ None)
.await
.expect("all children should load");
assert_eq!(
all_children,
vec![first_child_thread_id, second_child_thread_id]
);
let open_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open children should load");
let state_open_children = state_db
.list_thread_spawn_children_with_status(
parent_thread_id,
DirectionalThreadSpawnEdgeStatus::Open,
)
.await
.expect("state open children should load");
assert_eq!(open_children, state_open_children);
assert_eq!(open_children, vec![first_child_thread_id]);
let closed_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed children should load");
assert_eq!(closed_children, vec![second_child_thread_id]);
}
#[tokio::test]
async fn local_store_updates_edge_status() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db);
let parent_thread_id = thread_id(/*suffix*/ 10);
let child_thread_id = thread_id(/*suffix*/ 11);
store
.upsert_thread_spawn_edge(
parent_thread_id,
child_thread_id,
ThreadSpawnEdgeStatus::Open,
)
.await
.expect("child edge should insert");
store
.set_thread_spawn_edge_status(child_thread_id, ThreadSpawnEdgeStatus::Closed)
.await
.expect("child edge should close");
let open_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open children should load");
assert_eq!(open_children, Vec::<ThreadId>::new());
let closed_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed children should load");
assert_eq!(closed_children, vec![child_thread_id]);
}
#[tokio::test]
async fn local_store_lists_descendants_breadth_first_with_status_filters() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db.clone());
let root_thread_id = thread_id(/*suffix*/ 20);
let later_child_thread_id = thread_id(/*suffix*/ 22);
let earlier_child_thread_id = thread_id(/*suffix*/ 21);
let closed_grandchild_thread_id = thread_id(/*suffix*/ 23);
let open_grandchild_thread_id = thread_id(/*suffix*/ 24);
let closed_child_thread_id = thread_id(/*suffix*/ 25);
let closed_great_grandchild_thread_id = thread_id(/*suffix*/ 26);
for (parent_thread_id, child_thread_id, status) in [
(
root_thread_id,
later_child_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
root_thread_id,
earlier_child_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
earlier_child_thread_id,
open_grandchild_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
later_child_thread_id,
closed_grandchild_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
(
root_thread_id,
closed_child_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
(
closed_child_thread_id,
closed_great_grandchild_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
] {
store
.upsert_thread_spawn_edge(parent_thread_id, child_thread_id, status)
.await
.expect("edge should insert");
}
let all_descendants = store
.list_thread_spawn_descendants(root_thread_id, /*status_filter*/ None)
.await
.expect("all descendants should load");
assert_eq!(
all_descendants,
vec![
earlier_child_thread_id,
later_child_thread_id,
closed_child_thread_id,
closed_grandchild_thread_id,
open_grandchild_thread_id,
closed_great_grandchild_thread_id,
]
);
let open_descendants = store
.list_thread_spawn_descendants(root_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open descendants should load");
let state_open_descendants = state_db
.list_thread_spawn_descendants_with_status(
root_thread_id,
DirectionalThreadSpawnEdgeStatus::Open,
)
.await
.expect("state open descendants should load");
assert_eq!(open_descendants, state_open_descendants);
assert_eq!(
open_descendants,
vec![
earlier_child_thread_id,
later_child_thread_id,
open_grandchild_thread_id,
]
);
let closed_descendants = store
.list_thread_spawn_descendants(root_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed descendants should load");
assert_eq!(
closed_descendants,
vec![closed_child_thread_id, closed_great_grandchild_thread_id]
);
}
}

View File

@@ -0,0 +1,62 @@
use std::future::Future;
use std::pin::Pin;
use akode_protocol::ThreadId;
use crate::AgentGraphStoreResult;
use crate::ThreadSpawnEdgeStatus;
/// Future returned by [`AgentGraphStore`] operations.
pub type AgentGraphStoreFuture<'a, T> =
Pin<Box<dyn Future<Output = AgentGraphStoreResult<T>> + Send + 'a>>;
/// Storage-neutral boundary for persisted thread-spawn parent/child topology.
///
/// Implementations are expected to return stable ordering for list methods so callers can merge
/// persisted graph state with live in-memory state without introducing nondeterministic output.
pub trait AgentGraphStore: Send + Sync {
/// Insert or replace the directional parent/child edge for a spawned thread.
///
/// `child_thread_id` has at most one persisted parent. Re-inserting the same child should
/// update both the parent and status to match the supplied values.
/// The edge may be published before the child's metadata or history exists. A successful
/// write must make the child discoverable through the list methods.
fn upsert_thread_spawn_edge(
&self,
parent_thread_id: ThreadId,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()>;
/// Update the persisted lifecycle status of a spawned thread's incoming edge.
///
/// Implementations should treat missing children as a successful no-op.
fn set_thread_spawn_edge_status(
&self,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()>;
/// List direct spawned children of a parent thread.
///
/// When `status_filter` is `Some`, only child edges with that exact status are returned. When
/// it is `None`, all direct child edges are returned regardless of status, including statuses
/// that may be added by a future store implementation.
fn list_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>>;
/// List spawned descendants breadth-first by depth, then by thread id.
///
/// `status_filter` is applied to every traversed edge, not just to the returned descendants.
/// For example, `Some(Open)` walks only open edges, so descendants under a closed edge are not
/// included even if their own incoming edge is open. `None` walks and returns every persisted
/// edge regardless of status.
fn list_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>>;
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board-client",
crate_name = "akode_agent_message_board_client",
)

View File

@@ -0,0 +1,34 @@
[package]
name = "akode-agent-message-board-client"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
test = false
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
akode-message-board = { workspace = true }
akode-extension-api = { workspace = true }
akode-http-client = { workspace = true }
akode-protocol = { workspace = true }
eventsource-stream = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["rt", "time"] }
tokio-util = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,437 @@
//! Typed remote implementation of the board contract. HTTP policy is supplied
//! by the caller; reads and writes never fall back to a private local board.
//! Live notification frames are bounded before SSE parsing.
use crate::protocol::AccessToken;
use crate::protocol::BoardNotification;
use crate::protocol::Call;
use crate::protocol::Failure;
use crate::protocol::MAX_BODY;
use crate::protocol::MAX_RESPONSE;
use crate::protocol::Operation;
use crate::protocol::PermissionDeniedDetails;
use crate::protocol::Registration;
use crate::protocol::Watch;
use akode_http_client::HttpClient;
use akode_http_client::HttpResponse;
use akode_message_board::AgentMessageBoard;
use akode_message_board::AppendRequest;
use akode_message_board::ChannelPage;
use akode_message_board::ChannelQuery;
use akode_message_board::ChannelSummary;
use akode_message_board::CreateChannelRequest;
use akode_message_board::Page;
use akode_message_board::PermissionDenied;
use akode_message_board::PostContent;
use akode_message_board::PostMetadata;
use akode_message_board::PostPreview;
use akode_message_board::PostQuery;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::ReadThreadRequest;
use akode_message_board::SubscriptionRequest;
use akode_message_board::SubscriptionState;
use akode_message_board::ThreadPage;
use akode_message_board::ThreadQuery;
use akode_message_board::ThreadSummary;
use akode_message_board::UpsertChannelRequest;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use anyhow::Context;
use chrono::DateTime;
use chrono::Utc;
use eventsource_stream::Eventsource;
use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::error::Error;
use std::sync::Arc;
use std::task::Poll;
use std::time::Duration;
use url::Url;
/// A client for one session's board. Use the shared HTTP client's configured
/// proxy and CA policy.
#[derive(Clone)]
pub struct RemoteAgentMessageBoard {
http: HttpClient,
board_url: Url,
board: SessionId,
token: AccessToken,
clock: Arc<dyn Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync>,
}
impl RemoteAgentMessageBoard {
/// Validate the HTTP(S) endpoint and append the board path to its optional path prefix.
pub fn new(
http: HttpClient,
endpoint: &str,
board: SessionId,
token: AccessToken,
) -> anyhow::Result<Self> {
let mut board_url = Url::parse(endpoint).context("invalid message-board endpoint")?;
anyhow::ensure!(
matches!(board_url.scheme(), "http" | "https") && board_url.host_str().is_some(),
"message-board endpoint must be an HTTP(S) URL"
);
anyhow::ensure!(
board_url.query().is_none() && board_url.fragment().is_none(),
"message-board endpoint must not contain a query or fragment"
);
board_url.set_path(&format!(
"{}/v1/boards/{board}",
board_url.path().trim_end_matches('/')
));
Ok(Self {
http,
board_url,
board,
token,
clock: Arc::new(|_| Box::pin(async { Ok(Utc::now()) })),
})
}
/// Supply the runtime's configured clock for research's simulated time.
pub fn with_clock(
mut self,
clock: impl Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync + 'static,
) -> Self {
self.clock = Arc::new(clock);
self
}
pub async fn create_board(&self) -> Result<SessionId> {
let response = self
.http
.request(http::Method::PUT, self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
pub async fn delete_board(&self) -> Result<()> {
let response = self
.http
.delete(self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
if response.status().is_success() {
Ok(())
} else {
decode(response).await
}
}
/// Register the session's agents. The returned session token is stable on retry.
pub async fn register_members(
&self,
members: HashMap<ThreadId, AgentPath>,
) -> Result<AccessToken> {
let response = self
.http
.post(self.url("/members"))
.bearer_auth(&self.token.0)
.json(&Registration { members })
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
/// Opens a live receiver and waits until the service has registered it.
/// Setup, including readiness or an error body, has a 30-second deadline.
/// Drop it when the turn ends. Reopening does not replay earlier previews.
pub async fn notifications(
&self,
caller: ThreadId,
turn_id: String,
) -> Result<BoardNotifications> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 30);
let response = tokio::time::timeout_at(
deadline,
self.http
.post(self.url("/notifications"))
.bearer_auth(&self.token.0)
.json(&Watch {
caller,
turn_id: turn_id.clone(),
})
.send(),
)
.await
.map_err(transport_error)?
.map_err(transport_error)?;
if !response.status().is_success() {
tracing::warn!(
%caller, %turn_id,
http_status = response.status().as_u16(),
"Remote board notification request rejected"
);
tokio::time::timeout_at(deadline, decode::<()>(response))
.await
.map_err(transport_error)??;
return Err(transport_error("unexpected notification response"));
}
// Count wire bytes before the parser buffers them, resetting at blank lines.
// Defer CR handling so CRLF counts as one line ending even across chunks.
let mut frame_bytes = 0;
let mut line_empty = true;
let mut previous_cr = false;
// Validate before the SSE decoder can retain malformed UTF-8 indefinitely.
// Only an incomplete code point (at most three bytes) carries across chunks.
let mut utf8 = [0; 4];
let mut utf8_len = 0;
let mut chunks = Some(response.bytes_stream());
let mut events = futures::stream::poll_fn(move |cx| {
let Some(source) = chunks.as_mut() else {
return Poll::Ready(None);
};
let Some(chunk) = std::task::ready!(source.poll_next_unpin(cx)) else {
chunks = None;
return Poll::Ready(None);
};
let result = chunk.map_err(transport_error).and_then(|chunk| {
for &byte in chunk.iter() {
if !byte.is_ascii() || utf8_len > 0 {
utf8[utf8_len] = byte;
utf8_len += 1;
match std::str::from_utf8(&utf8[..utf8_len]) {
Ok(_) => utf8_len = 0,
Err(error) if error.error_len().is_some() => {
return Err(transport_error(error));
}
Err(_) => {}
}
}
if previous_cr && byte != b'\n' {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
frame_bytes += 1;
if frame_bytes > MAX_BODY {
return Err(transport_error("board SSE frame exceeds the service limit"));
}
match byte {
b'\n' => {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
b'\r' => {}
_ => line_empty = false,
}
previous_cr = byte == b'\r';
}
Ok(chunk)
});
if result.is_err() {
chunks = None;
}
Poll::Ready(Some(result))
})
.eventsource();
let ready = tokio::time::timeout_at(deadline, events.next())
.await
.map_err(transport_error)?
.ok_or_else(|| transport_error("notification stream closed before readiness"))?
.map_err(transport_error)?;
if ready.event != "ready" {
return Err(transport_error(
"notification stream did not acknowledge readiness",
));
}
let stream = events.map(|event| event.map_err(transport_error)).boxed();
Ok(BoardNotifications {
caller,
turn_id,
stream,
})
}
fn url(&self, suffix: &str) -> Url {
let mut url = self.board_url.clone();
url.set_path(&format!("{}{suffix}", url.path()));
url
}
async fn call<T: DeserializeOwned>(&self, caller: ThreadId, operation: Operation) -> Result<T> {
let timestamp = match &operation {
Operation::CreateChannel(_) => Some((self.clock)(caller).await?),
// The service can replay a committed post without a fresh timestamp.
// A new post still requires one; never substitute wall-clock time.
Operation::Post(_) => (self.clock)(caller).await.ok(),
Operation::ListChannels(_)
| Operation::ListThreads(_)
| Operation::SearchPosts(_)
| Operation::ReadThread(_)
| Operation::ReadPost(_)
| Operation::SetSubscription(_) => None,
};
let call = Call {
caller,
timestamp,
operation,
};
let body = serde_json::to_vec(&call)?;
if body.len() > MAX_BODY {
return Err(CodexErr::InvalidRequest(
"board request exceeds the service limit".into(),
));
}
let response = self
.http
.post(self.url("/call"))
.bearer_auth(&self.token.0)
.header("content-type", "application/json")
.body(body)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
}
macro_rules! operation {
($method:ident, $variant:ident, $input:ty, $output:ty) => {
fn $method(&self, caller: ThreadId, request: $input) -> BoxFuture<'_, Result<$output>> {
Box::pin(self.call(caller, Operation::$variant(request)))
}
};
}
impl AgentMessageBoard for RemoteAgentMessageBoard {
fn identity(&self) -> SessionId {
self.board
}
operation!(
create_channel,
CreateChannel,
CreateChannelRequest,
ChannelSummary
);
operation!(list_channels, ListChannels, ChannelQuery, ChannelPage);
fn upsert_channel(
&self,
_caller: ThreadId,
_request: UpsertChannelRequest,
) -> BoxFuture<'_, Result<()>> {
// The service has no description-update operation; creation has different semantics.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support channel upsert".into(),
))
})
}
operation!(post, Post, PostRequest, PostMetadata);
fn append(
&self,
_caller: ThreadId,
_request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>> {
// The remote protocol has no silent write operation. Posting is not equivalent.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support silent append".into(),
))
})
}
operation!(list_threads, ListThreads, ThreadQuery, Page<ThreadSummary>);
operation!(search_posts, SearchPosts, PostQuery, Page<PostPreview>);
operation!(read_thread, ReadThread, ReadThreadRequest, ThreadPage);
operation!(read_post, ReadPost, ReadPostRequest, PostContent);
operation!(
set_subscription,
SetSubscription,
SubscriptionRequest,
SubscriptionState
);
}
/// One active turn's live receiver. Frames are checked against this receiver's
/// identity before accepted notices enter the host's ordinary message delivery.
pub struct BoardNotifications {
caller: ThreadId,
turn_id: String,
stream: BoxStream<'static, Result<eventsource_stream::Event>>,
}
impl BoardNotifications {
/// Skips invalid individual notices. Transport and framing failures remain errors.
pub async fn next(&mut self) -> Result<Option<BoardNotification>> {
while let Some(event) = self.stream.next().await.transpose()? {
let error_kind = if event.event != "notification" {
"unexpected_event"
} else {
match serde_json::from_str::<BoardNotification>(&event.data) {
Ok(notice) => {
if notice.recipient != self.caller || notice.turn_id != self.turn_id {
"wrong_recipient_or_turn"
} else if notice.post.text_preview.chars().count() > 150 {
"oversized_preview"
} else {
return Ok(Some(notice));
}
}
Err(_) => "invalid_json",
}
};
tracing::warn!(
caller = %self.caller, turn_id = %self.turn_id, error_kind,
"Skipping invalid remote board notification"
);
}
Ok(None)
}
}
async fn decode<T: DeserializeOwned>(mut response: HttpResponse) -> Result<T> {
let status = response.status();
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(transport_error)? {
if body.len().saturating_add(chunk.len()) > MAX_RESPONSE {
return Err(transport_error("board response exceeds the service limit"));
}
body.extend_from_slice(&chunk);
}
if !status.is_success() {
let failure: Failure = serde_json::from_slice(&body)
.with_context(|| format!("invalid board error response (HTTP {status})"))
.map_err(transport_error)?;
if status == http::StatusCode::FORBIDDEN && failure.code == "permission_denied" {
let details: PermissionDeniedDetails = serde_json::from_slice(&body)?;
return Err(PermissionDenied {
message: failure.message,
action: details.action,
resource: details.resource,
}
.into());
}
let message = format!("{}: {}", failure.code, failure.message);
return Err(if status.is_server_error() {
transport_error(message)
} else {
CodexErr::InvalidRequest(message)
});
}
serde_json::from_slice(&body).map_err(CodexErr::from)
}
fn transport_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> CodexErr {
CodexErr::Io(std::io::Error::other(error))
}

View File

@@ -0,0 +1,122 @@
//! Receives live board previews for an active turn using the extension's turn hooks.
//! Provisioning and durable board ownership belong to the research host.
use crate::RemoteAgentMessageBoard;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::TurnAbortInput;
use akode_extension_api::TurnErrorInput;
use akode_extension_api::TurnLifecycleContributor;
use akode_extension_api::TurnStartInput;
use akode_extension_api::TurnStartPhase;
use akode_extension_api::TurnStopInput;
use akode_message_board::MessageBoardHost;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrKind;
use futures::channel::oneshot;
use std::sync::Arc;
use std::time::Duration;
use tokio_util::task::AbortOnDropHandle;
type Binding = (Arc<RemoteAgentMessageBoard>, Arc<dyn MessageBoardHost>);
type ResolveBinding = dyn Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync;
struct Notifications(Box<ResolveBinding>);
struct Receiver {
_task: AbortOnDropHandle<()>,
}
impl TurnLifecycleContributor for Notifications {
fn turn_start_phase(&self, _thread_store: &ExtensionData) -> TurnStartPhase {
TurnStartPhase::RegularTaskStart
}
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let Some((board, host)) = (self.0)(&input) else {
return;
};
let Ok(caller) = ThreadId::from_string(input.thread_store.level_id()) else {
return;
};
let turn_id = input.turn_id.to_owned();
let (first_attempt_tx, first_attempt_rx) = oneshot::channel();
input.turn_store.insert(Receiver {
_task: AbortOnDropHandle::new(tokio::spawn(async move {
let mut first_attempt_tx = Some(first_attempt_tx);
loop {
let connection = board.notifications(caller, turn_id.clone()).await;
if let Some(first_attempt_tx) = first_attempt_tx.take() {
let _ = first_attempt_tx.send(());
}
match connection {
Ok(mut stream) => loop {
match stream.next().await {
Ok(Some(notice)) => {
if let Err(error) = host.notify(caller, notice.post).await {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification delivery failed"
);
}
}
Ok(None) => break,
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification stream failed"
);
break;
}
}
},
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification connection failed"
);
}
}
// Reopen for future previews; the service does not replay missed ones.
tokio::time::sleep(Duration::from_secs(/*secs*/ 1)).await;
}
})),
});
// A healthy service is listening before inference. A failed first attempt
// releases startup while the same turn-owned receiver keeps retrying.
let _ = first_attempt_rx.await;
})
}
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
}
/// Installs live notification delivery. The host resolves the existing remote
/// client and delivery host. Accepted notices use the host's ordinary message policy.
/// The turn store owns the receiver and cancels it when the turn ends.
pub fn install_notifications<C: Sync>(
registry: &mut ExtensionRegistryBuilder<C>,
resolve: impl Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync + 'static,
) {
registry.turn_lifecycle_contributor(Arc::new(Notifications(Box::new(resolve))));
}

View File

@@ -0,0 +1,107 @@
//! Versioned service requests reuse board operations; only host identity travels separately.
use akode_message_board::ChannelQuery;
use akode_message_board::CreateChannelRequest;
use akode_message_board::PostPreview;
use akode_message_board::PostQuery;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::ReadThreadRequest;
use akode_message_board::SubscriptionRequest;
use akode_message_board::ThreadQuery;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use chrono::DateTime;
use chrono::Utc;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
pub(crate) const MAX_BODY: usize = 512 * 1024;
pub(crate) const MAX_RESPONSE: usize = 1024 * 1024;
/// A host credential. Debug output must never reveal its contents.
#[derive(Clone, Serialize)]
#[serde(transparent)]
pub struct AccessToken(pub(crate) String);
impl AccessToken {
pub fn new(value: String) -> anyhow::Result<Self> {
anyhow::ensure!(
(32..=4096).contains(&value.len()),
"credentials must contain 32–4096 bytes"
);
anyhow::ensure!(
value.bytes().all(|b| b.is_ascii_graphic()),
"credential must be ASCII without whitespace"
);
Ok(Self(value))
}
}
impl<'de> Deserialize<'de> for AccessToken {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl fmt::Debug for AccessToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AccessToken([REDACTED])")
}
}
#[derive(Serialize)]
pub(crate) struct Registration {
pub(crate) members: HashMap<ThreadId, AgentPath>,
}
#[derive(Serialize)]
pub(crate) struct Call {
pub(crate) caller: ThreadId,
pub(crate) timestamp: Option<DateTime<Utc>>,
#[serde(flatten)]
pub(crate) operation: Operation,
}
#[derive(Serialize)]
#[serde(tag = "method", content = "params", rename_all = "snake_case")]
pub(crate) enum Operation {
CreateChannel(CreateChannelRequest),
ListChannels(ChannelQuery),
Post(PostRequest),
ListThreads(ThreadQuery),
SearchPosts(PostQuery),
ReadThread(ReadThreadRequest),
ReadPost(ReadPostRequest),
SetSubscription(SubscriptionRequest),
}
#[derive(Serialize)]
pub(crate) struct Watch {
pub(crate) caller: ThreadId,
pub(crate) turn_id: String,
}
/// A best-effort preview bound to the receiving turn. Hosts must atomically check
/// `turn_id` when admitting it; a received preview must never start a new turn.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoardNotification {
pub recipient: ThreadId,
pub turn_id: String,
pub post: PostPreview,
}
#[derive(Deserialize)]
pub(crate) struct Failure {
pub(crate) code: String,
pub(crate) message: String,
}
#[derive(Deserialize)]
pub(crate) struct PermissionDeniedDetails {
pub(crate) action: Option<String>,
pub(crate) resource: Option<String>,
}

View File

@@ -1,25 +1,25 @@
//! Exercise the HTTP adapter's clock, authentication and turn-bound stream. //! Exercise the HTTP adapter's clock, authentication and turn-bound stream.
use akode_agent_message_board_client::AccessToken;
use akode_agent_message_board_client::BoardNotification;
use akode_agent_message_board_client::RemoteAgentMessageBoard;
use akode_http_client::HttpClientBuilder;
use akode_message_board::AgentMessageBoard;
use akode_message_board::AppendRequest;
use akode_message_board::PostContent;
use akode_message_board::PostDestination;
use akode_message_board::PostMetadata;
use akode_message_board::PostPreview;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::UpsertChannelRequest;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use chrono::DateTime; use chrono::DateTime;
use chrono::Utc; use chrono::Utc;
use codex_agent_message_board_client::AccessToken;
use codex_agent_message_board_client::BoardNotification;
use codex_agent_message_board_client::RemoteAgentMessageBoard;
use codex_http_client::HttpClientBuilder;
use codex_message_board::AgentMessageBoard;
use codex_message_board::AppendRequest;
use codex_message_board::PostContent;
use codex_message_board::PostDestination;
use codex_message_board::PostMetadata;
use codex_message_board::PostPreview;
use codex_message_board::PostRequest;
use codex_message_board::ReadPostRequest;
use codex_message_board::UpsertChannelRequest;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use serde_json::json; use serde_json::json;
use std::collections::HashMap; use std::collections::HashMap;

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board-host",
crate_name = "akode_agent_message_board_host",
)

View File

@@ -0,0 +1,25 @@
[package]
name = "akode-agent-message-board-host"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
test = false
doctest = false
[lints]
workspace = true
[dependencies]
chrono = { workspace = true }
akode-agent-message-board-client = { workspace = true }
akode-agent-message-board-extension = { workspace = true }
akode-core = { workspace = true }
akode-extension-api = { workspace = true }
akode-features = { workspace = true }
akode-message-board = { workspace = true }
akode-protocol = { workspace = true }
akode-state = { workspace = true }
akode-thread-store = { workspace = true }
futures = { workspace = true }

View File

@@ -0,0 +1,261 @@
//! Supplies board host capabilities through the public Core runtime interfaces.
//!
//! The extension owns backend construction, storage and tool registration. This adapter
//! selects configuration and supplies host capabilities. It never starts or restores
//! recipients during lookup. Notifications use ordinary agent-message scheduling.
//! Permanent board deletion uses the thread store's existing host cleanup callback.
#![deny(clippy::print_stdout, clippy::print_stderr)]
use akode_agent_message_board_client::RemoteAgentMessageBoard;
use akode_agent_message_board_extension::BoardBackend;
use akode_agent_message_board_extension::local_board_options;
use akode_core::CodexThread;
use akode_core::MULTI_AGENT_V2_NAMESPACE_DESCRIPTION;
use akode_core::ThreadManager;
use akode_core::config::Config;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::ThreadStartInput;
use akode_features::Feature;
use akode_message_board::LocalAgentMessageBoard;
use akode_message_board::LocalBoardConnection;
use akode_message_board::MessageBoardHost;
use akode_message_board::NotificationDelivery;
use akode_message_board::PostPreview;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::Result;
use akode_protocol::protocol::InterAgentCommunication;
use akode_protocol::protocol::Op;
use akode_state::SqliteConfig;
use akode_thread_store::ThreadStoreError;
use akode_thread_store::ThreadStoreResult;
use chrono::DateTime;
use chrono::Utc;
use futures::future::BoxFuture;
use std::sync::Arc;
use std::sync::Weak;
/// Registers the configured board for opted-in MAv2 runtimes.
/// Training can share an in-memory board per tree, including ephemeral sessions.
pub fn install_agent_message_board(
registry: &mut ExtensionRegistryBuilder<Config>,
manager: Weak<ThreadManager>,
) {
akode_agent_message_board_client::install_notifications(registry, |input| {
let board = input.thread_store.get::<RemoteAgentMessageBoard>()?;
let host = input.thread_store.get::<LocalBoardHost>()?;
Some((
board,
Arc::new(LocalBoardHost {
remote_notifications: true,
..host.as_ref().clone()
}),
))
});
akode_agent_message_board_extension::install(
registry,
MULTI_AGENT_V2_NAMESPACE_DESCRIPTION,
|config: &Config| config.multi_agent_v2.tool_namespace.clone(),
move |input: &ThreadStartInput<'_, Config>, tree, caller| {
let config = input.config;
let connection = input.thread_store.get::<LocalBoardConnection>();
let in_memory = config.multi_agent_v2.message_board_in_memory;
let mcp =
config.features.enabled(Feature::AgentMessageBoardMcp) && connection.is_none();
// Automatic boards need MAv2. In-memory boards and explicit host
// connections also work for isolated, ephemeral runtimes.
if connection.is_none()
&& ((!config.features.enabled(Feature::AgentMessageBoard) && !mcp)
|| !config.features.enabled(Feature::MultiAgentV2)
|| (config.ephemeral
&& !mcp
&& !in_memory
&& config.multi_agent_v2.message_board_remote.is_none()))
{
return None;
}
let backend = if mcp {
BoardBackend::Mcp
} else if let Some(connection) = &connection {
BoardBackend::Connected(connection.clone())
} else if let Some(remote) = config.multi_agent_v2.message_board_remote.clone() {
BoardBackend::Remote {
config: remote,
http: config.http_client_factory(),
}
} else if in_memory {
BoardBackend::InMemory
} else {
BoardBackend::Local(config.sqlite_config().clone())
};
Some((
backend,
LocalBoardHost {
manager: manager.clone(),
tree,
caller,
remote_notifications: false,
connection,
},
))
},
);
}
/// Removes persisted agent-board data through the thread store's deletion callback.
/// Cleanup also applies when the board feature is currently disabled.
pub async fn delete_agent_message_boards(
sqlite: &SqliteConfig,
thread_ids: &[ThreadId],
) -> ThreadStoreResult<()> {
let boards = thread_ids
.iter()
.copied()
.map(Into::into)
.collect::<Vec<_>>();
LocalAgentMessageBoard::delete_boards(sqlite, &local_board_options(), &boards)
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to delete agent message boards: {err}"),
})
}
#[derive(Clone)]
struct LocalBoardHost {
manager: Weak<ThreadManager>,
tree: SessionId,
caller: ThreadId,
remote_notifications: bool,
connection: Option<Arc<LocalBoardConnection>>,
}
impl LocalBoardHost {
async fn actor(&self, caller: ThreadId) -> Result<Arc<CodexThread>> {
let manager = self
.manager
.upgrade()
.ok_or_else(|| CodexErr::ThreadNotFound(caller))?;
if let Some(connection) = &self.connection {
return manager
.get_thread_with_extension::<LocalBoardConnection>(caller, |other| {
connection.same_board(other)
})
.await;
}
let actor = manager.get_thread(caller).await?;
if actor.startup_metadata().session_id != self.tree
|| actor
.thread_extension_data()
.get::<LocalBoardConnection>()
.is_some()
{
return Err(CodexErr::InvalidRequest(
"agent belongs to another message board".into(),
));
}
Ok(actor)
}
async fn registered_path(&self, actor: &CodexThread) -> Result<AgentPath> {
let caller = actor.startup_metadata().thread_id;
if let Some(connection) = &self.connection {
return connection.caller_path(caller);
}
let path = actor
.session_source()
.get_agent_path()
.or_else(|| (caller == ThreadId::from(self.tree)).then(AgentPath::root))
.ok_or_else(|| CodexErr::InvalidRequest("agent has no tree path".into()))?;
let resolved = actor.resolve_agent_reference(path.as_str()).await?;
if resolved != caller {
return Err(CodexErr::InvalidRequest(
"agent does not own its tree path".into(),
));
}
Ok(path)
}
}
impl MessageBoardHost for LocalBoardHost {
fn agent_path(&self, caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
Box::pin(async move {
let actor = self.actor(caller).await?;
self.registered_path(&actor).await
})
}
fn resolve_agent(&self, path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
Box::pin(async move {
if self.connection.is_some() {
let caller = path
.as_str()
.strip_prefix("/root/")
.and_then(|id| ThreadId::from_string(id).ok())
.ok_or_else(|| {
CodexErr::InvalidRequest("invalid connected board agent path".into())
})?;
return self
.actor(caller)
.await
.map(|actor| actor.startup_metadata().thread_id);
}
let actor = self.actor(self.caller).await?;
actor.resolve_agent_reference(path.as_str()).await
})
}
fn current_time(&self, caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
Box::pin(async move {
let actor = self.actor(caller).await?;
self.registered_path(&actor).await?;
actor.current_time().await
})
}
fn notify(
&self,
recipient_id: ThreadId,
post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>> {
Box::pin(async move {
let recipient = match self.actor(recipient_id).await {
Ok(thread) => thread,
Err(error) if matches!(error.details(), CodexErrorDetails::ThreadNotFound(_)) => {
return Ok(NotificationDelivery::SkippedInactive);
}
Err(error) => return Err(error),
};
let recipient_path = self.registered_path(&recipient).await?;
let communication = InterAgentCommunication::new(
post.metadata.author.clone(),
recipient_path,
Vec::new(),
post.notification_text(),
/*trigger_turn*/ false,
);
// Remote metadata is untrusted. Skip an oversized notice without closing
// the receiver; the post remains available through the board tools.
if self.remote_notifications
&& communication.content.len()
+ communication.author.as_str().len()
+ communication.recipient.as_str().len()
> 1024
{
return Err(CodexErr::InvalidRequest(
"remote board notice exceeds the context budget".into(),
));
}
recipient
.submit(Op::InterAgentCommunication {
communication,
start_options: Default::default(),
})
.await?;
Ok(NotificationDelivery::Accepted)
})
}
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-roles",
crate_name = "akode_agent_roles",
)

View File

@@ -0,0 +1,23 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-agent-roles"
version.workspace = true
[lib]
doctest = false
name = "akode_agent_roles"
path = "src/lib.rs"
test = false
[lints]
workspace = true
[dependencies]
akode-config = { workspace = true }
akode-file-system = { workspace = true }
akode-utils-absolute-path = { workspace = true }
akode-utils-path-uri = { workspace = true }
serde = { workspace = true, features = ["derive"] }
toml = { workspace = true, features = ["preserve_order"] }
tracing = { workspace = true }

View File

@@ -1,5 +1,5 @@
use codex_config::config_toml::ConfigToml; use akode_config::config_toml::ConfigToml;
use codex_utils_absolute_path::AbsolutePathBufGuard; use akode_utils_absolute_path::AbsolutePathBufGuard;
use serde::Deserialize; use serde::Deserialize;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::path::Path; use std::path::Path;

View File

@@ -0,0 +1,40 @@
use akode_file_system::ExecutorFileSystem;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use std::io;
use std::io::ErrorKind;
pub(crate) async fn collect_agent_role_files(
fs: &dyn ExecutorFileSystem,
dir: &AbsolutePathBuf,
) -> io::Result<Vec<AbsolutePathBuf>> {
let mut files = Vec::new();
let mut dirs = vec![dir.clone()];
while let Some(dir) = dirs.pop() {
let dir_uri = PathUri::from_abs_path(&dir);
let entries = match fs.read_directory(&dir_uri, /*sandbox*/ None).await {
Ok(entries) => entries,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
for entry in entries {
let path = dir.join(entry.file_name);
if entry.is_directory {
dirs.push(path);
continue;
}
if entry.is_file
&& path
.as_path()
.extension()
.is_some_and(|extension| extension == "toml")
{
files.push(path);
}
}
}
files.sort();
Ok(files)
}

View File

@@ -0,0 +1,335 @@
use crate::AgentRoleConfig;
use crate::ResolvedAgentRoleFile;
use crate::agent_role_config::normalize_agent_role_description;
use crate::agent_role_config::normalize_agent_role_nickname_candidates;
use crate::discovery::collect_agent_role_files;
use crate::parse_agent_role_file_contents;
use akode_config::ConfigLayerStack;
use akode_config::config_toml::AgentRoleToml;
use akode_config::config_toml::AgentsToml;
use akode_config::config_toml::ConfigToml;
use akode_file_system::ExecutorFileSystem;
use akode_file_system::GetMetadataOptions;
use akode_file_system::ReadFileOptions;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_absolute_path::AbsolutePathBufGuard;
use akode_utils_path_uri::PathUri;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::Path;
use std::path::PathBuf;
use toml::Value as TomlValue;
pub async fn load_agent_roles(
fs: &dyn ExecutorFileSystem,
cfg: &ConfigToml,
config_layer_stack: &ConfigLayerStack,
startup_warnings: &mut Vec<String>,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut layers = config_layer_stack.layers_low_to_high().peekable();
if layers.peek().is_none() {
return load_agent_roles_without_layers(fs, cfg).await;
}
let mut roles: BTreeMap<String, AgentRoleConfig> = BTreeMap::new();
for layer in layers {
let mut layer_roles: BTreeMap<String, AgentRoleConfig> = BTreeMap::new();
let mut declared_role_files = BTreeSet::new();
let config_folder = layer.config_folder();
let agents_toml = match agents_toml_from_layer(&layer.config, config_folder.as_deref()) {
Ok(agents_toml) => agents_toml,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
None
}
};
if let Some(agents_toml) = agents_toml {
for (declared_role_name, role_toml) in &agents_toml.roles {
let (role_name, role) =
match read_declared_role(fs, declared_role_name, role_toml).await {
Ok(role) => role,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
continue;
}
};
if let Some(config_file) = role.config_file.clone() {
declared_role_files.insert(config_file);
}
if layer_roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` declared in the same config layer"
),
),
);
continue;
}
layer_roles.insert(role_name, role);
}
}
if let Some(config_folder) = layer.config_folder() {
for (role_name, role) in discover_agent_roles_in_dir(
fs,
&config_folder.join("agents"),
&declared_role_files,
startup_warnings,
)
.await?
{
if layer_roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` declared in the same config layer"
),
),
);
continue;
}
layer_roles.insert(role_name, role);
}
}
for (role_name, role) in layer_roles {
let mut merged_role = role;
if let Some(existing_role) = roles.get(&role_name) {
merge_missing_role_fields(&mut merged_role, existing_role);
}
if let Err(err) = validate_required_agent_role_description(
&role_name,
merged_role.description.as_deref(),
) {
push_agent_role_warning(startup_warnings, err);
continue;
}
roles.insert(role_name, merged_role);
}
}
Ok(roles)
}
fn push_agent_role_warning(startup_warnings: &mut Vec<String>, err: std::io::Error) {
let message = format!("Ignoring malformed agent role definition: {err}");
tracing::warn!("{message}");
startup_warnings.push(message);
}
async fn load_agent_roles_without_layers(
fs: &dyn ExecutorFileSystem,
cfg: &ConfigToml,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut roles = BTreeMap::new();
if let Some(agents_toml) = cfg.agents.as_ref() {
for (declared_role_name, role_toml) in &agents_toml.roles {
let (role_name, role) = read_declared_role(fs, declared_role_name, role_toml).await?;
validate_required_agent_role_description(&role_name, role.description.as_deref())?;
if roles.insert(role_name.clone(), role).is_some() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("duplicate agent role name `{role_name}` declared in config"),
));
}
}
}
Ok(roles)
}
async fn read_declared_role(
fs: &dyn ExecutorFileSystem,
declared_role_name: &str,
role_toml: &AgentRoleToml,
) -> std::io::Result<(String, AgentRoleConfig)> {
let mut role = agent_role_config_from_toml(fs, declared_role_name, role_toml).await?;
let mut role_name = declared_role_name.to_string();
if let Some(config_file) = role.config_file.as_deref() {
let config_file = AbsolutePathBuf::from_absolute_path(config_file)?;
let parsed_file =
read_resolved_agent_role_file(fs, &config_file, Some(declared_role_name)).await?;
role_name = parsed_file.role_name;
role.description = parsed_file.description.or(role.description);
role.nickname_candidates = parsed_file.nickname_candidates.or(role.nickname_candidates);
}
Ok((role_name, role))
}
fn merge_missing_role_fields(role: &mut AgentRoleConfig, fallback: &AgentRoleConfig) {
role.description = role.description.clone().or(fallback.description.clone());
role.config_file = role.config_file.clone().or(fallback.config_file.clone());
role.nickname_candidates = role
.nickname_candidates
.clone()
.or(fallback.nickname_candidates.clone());
}
fn agents_toml_from_layer(
layer_toml: &TomlValue,
config_base_dir: Option<&Path>,
) -> std::io::Result<Option<AgentsToml>> {
let Some(agents_toml) = layer_toml.get("agents") else {
return Ok(None);
};
// AbsolutePathBufGuard resolves relative paths while it remains in scope.
let _guard = config_base_dir.map(AbsolutePathBufGuard::new);
agents_toml
.clone()
.try_into()
.map(Some)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
}
async fn agent_role_config_from_toml(
fs: &dyn ExecutorFileSystem,
role_name: &str,
role: &AgentRoleToml,
) -> std::io::Result<AgentRoleConfig> {
let config_file = role
.config_file
.as_ref()
.map(AbsolutePathBuf::from_absolute_path)
.transpose()?;
validate_agent_role_config_file(fs, role_name, config_file.as_ref()).await?;
let description = normalize_agent_role_description(
&format!("agents.{role_name}.description"),
role.description.as_deref(),
)?;
let nickname_candidates = normalize_agent_role_nickname_candidates(
&format!("agents.{role_name}.nickname_candidates"),
role.nickname_candidates.as_deref(),
)?;
Ok(AgentRoleConfig {
description,
config_file: config_file.map(AbsolutePathBuf::into_path_buf),
nickname_candidates,
})
}
async fn read_resolved_agent_role_file(
fs: &dyn ExecutorFileSystem,
path: &AbsolutePathBuf,
role_name_hint: Option<&str>,
) -> std::io::Result<ResolvedAgentRoleFile> {
let path_uri = PathUri::from_abs_path(path);
let contents = fs
.read_file_text(&path_uri, ReadFileOptions::default(), /*sandbox*/ None)
.await?;
let config_base_dir = path.parent().unwrap_or_else(|| path.clone());
parse_agent_role_file_contents(
&contents,
path.as_path(),
config_base_dir.as_path(),
role_name_hint,
)
}
fn validate_required_agent_role_description(
role_name: &str,
description: Option<&str>,
) -> std::io::Result<()> {
if description.is_some() {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("agent role `{role_name}` must define a description"),
))
}
}
async fn validate_agent_role_config_file(
fs: &dyn ExecutorFileSystem,
role_name: &str,
config_file: Option<&AbsolutePathBuf>,
) -> std::io::Result<()> {
let Some(config_file) = config_file else {
return Ok(());
};
let config_file_uri = PathUri::from_abs_path(config_file);
let metadata = fs
.get_metadata(
&config_file_uri,
GetMetadataOptions::default(),
/*sandbox*/ None,
)
.await
.map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agents.{role_name}.config_file must point to an existing file at {}: {e}",
config_file.as_path().display()
),
)
})?;
if metadata.is_file {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agents.{role_name}.config_file must point to a file: {}",
config_file.as_path().display()
),
))
}
}
async fn discover_agent_roles_in_dir(
fs: &dyn ExecutorFileSystem,
agents_dir: &AbsolutePathBuf,
declared_role_files: &BTreeSet<PathBuf>,
startup_warnings: &mut Vec<String>,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut roles = BTreeMap::new();
for agent_file in collect_agent_role_files(fs, agents_dir).await? {
if declared_role_files.contains(agent_file.as_path()) {
continue;
}
let parsed_file =
match read_resolved_agent_role_file(fs, &agent_file, /*role_name_hint*/ None).await {
Ok(parsed_file) => parsed_file,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
continue;
}
};
let role_name = parsed_file.role_name;
if roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` discovered in {}",
agents_dir.as_path().display()
),
),
);
continue;
}
roles.insert(
role_name,
AgentRoleConfig {
description: parsed_file.description,
config_file: Some(agent_file.to_path_buf()),
nickname_candidates: parsed_file.nickname_candidates,
},
);
}
Ok(roles)
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "akode-api",
crate_name = "akode_api",
)

View File

@@ -0,0 +1,48 @@
[package]
name = "akode-api"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
async-channel = { workspace = true }
base64 = { workspace = true }
bytes = { workspace = true }
chrono = { workspace = true }
akode-client = { workspace = true }
akode-http-client = { workspace = true }
akode-protocol = { workspace = true }
akode-utils-rustls-provider = { workspace = true }
akode-websocket-client = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
rustls = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["fs", "macros", "net", "rt", "sync", "time"] }
tokio-tungstenite = { workspace = true }
tungstenite = { workspace = true }
tracing = { workspace = true }
eventsource-stream = { workspace = true }
regex-lite = { workspace = true }
tokio-util = { workspace = true, features = ["codec", "io"] }
url = { workspace = true }
uuid = { workspace = true }
[dev-dependencies]
anyhow = { workspace = true }
assert_matches = { workspace = true }
pretty_assertions = { workspace = true }
rcgen = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
tokio-test = { workspace = true }
wiremock = { workspace = true }
[lints]
workspace = true
[lib]
doctest = false

View File

@@ -0,0 +1,30 @@
# akode-api
Typed clients for Codex/OpenAI APIs built on top of the generic transport in `akode-client`.
- Hosts the request/response models and request builders for Responses and related Codex APIs.
- Owns provider configuration (base URLs, headers, query params), auth header injection, retry tuning, and stream idle settings.
- Parses SSE streams into `ResponseEvent`/`ResponseStream`, including rate-limit snapshots and API-specific error mapping.
- Serves as the wire-level layer consumed by `akode-core`; higher layers handle auth refresh and business logic.
## Core interface
The public interface of this crate is intentionally small and uniform:
- **Responses endpoint**
- Input:
- `ResponsesApiRequest` for the request body (`model`, `input`, `tools`, `parallel_tool_calls`, reasoning/text controls).
- `ResponsesOptions` for transport/header concerns (`conversation_id`, `session_source`, `extra_headers`, `compression`, `turn_state`).
- Output: a `ResponseStream` of `ResponseEvent` (both re-exported from `common`).
- **Memory summarize endpoint**
- Input: `MemorySummarizeInput` (re-exported as `akode_api::MemorySummarizeInput`):
- `model: String`.
- `raw_memories: Vec<RawMemory>` (serialized as `traces` for wire compatibility).
- `RawMemory` includes `id`, `metadata.source_path`, and normalized `items`.
- `reasoning: Option<Reasoning>`.
- Output: `Vec<MemorySummarizeOutput>`.
- `MemoriesClient::summarize_input(&MemorySummarizeInput, extra_headers)` wraps JSON encoding and retry/telemetry wiring.
All HTTP details (URLs, headers, retry/backoff policies, SSE framing) are encapsulated in `akode-api` and `akode-client`. Callers construct prompts/inputs using protocol types and work with typed streams of `ResponseEvent` or other endpoint-specific response values.

View File

@@ -4,17 +4,17 @@ use crate::error::parse_terminal_provider_error;
use crate::rate_limits::parse_promo_message; use crate::rate_limits::parse_promo_message;
use crate::rate_limits::parse_rate_limit_for_limit; use crate::rate_limits::parse_rate_limit_for_limit;
use crate::rate_limits::parse_rate_limit_reached_type; use crate::rate_limits::parse_rate_limit_reached_type;
use akode_protocol::auth::PlanType;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::ConnectionFailedError;
use akode_protocol::error::RetryLimitReachedError;
use akode_protocol::error::UnexpectedResponseError;
use akode_protocol::error::UsageLimitReachedError;
use akode_protocol::protocol::MisalignmentErrorDetails;
use base64::Engine; use base64::Engine;
use chrono::DateTime; use chrono::DateTime;
use chrono::Utc; use chrono::Utc;
use codex_protocol::auth::PlanType;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::ConnectionFailedError;
use codex_protocol::error::RetryLimitReachedError;
use codex_protocol::error::UnexpectedResponseError;
use codex_protocol::error::UsageLimitReachedError;
use codex_protocol::protocol::MisalignmentErrorDetails;
use http::HeaderMap; use http::HeaderMap;
use serde::Deserialize; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
@@ -256,10 +256,7 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
} }
} }
CodexErr::RetryLimit(RetryLimitReachedError { provider_rate_limit_error(&body_text)
status,
request_id: extract_request_tracking_id(headers.as_ref()),
})
} else { } else {
CodexErr::UnexpectedStatus(UnexpectedResponseError { CodexErr::UnexpectedStatus(UnexpectedResponseError {
status, status,
@@ -294,6 +291,47 @@ fn map_api_error_details(err: ApiError) -> CodexErr {
} }
} }
/// Maps a plain HTTP 429 from a provider to a retryable rate-limit error, or to a terminal
/// error when the provider says its daily allowance is used up.
fn provider_rate_limit_error(body_text: &str) -> CodexErr {
let message = serde_json::from_str::<Value>(body_text)
.ok()
.and_then(|body| {
body.get("error")
.and_then(|error| error.get("message").or(Some(error)))
.or_else(|| body.get("message"))
.and_then(Value::as_str)
.map(str::to_string)
})
.unwrap_or_else(|| body_text.trim().to_string());
let message: String = message.chars().take(300).collect();
if is_daily_limit_message(&message) || is_daily_limit_message(body_text) {
CodexErr::new(CodexErrorDetails::ProviderDailyLimitExhausted(message))
} else {
CodexErr::new(CodexErrorDetails::ProviderRateLimited(message))
}
}
fn is_daily_limit_message(text: &str) -> bool {
let text = text.to_ascii_lowercase();
[
"per-day",
"per day",
"per_day",
"daily",
"requests per day",
"rpd",
]
.iter()
.any(|needle| {
text.match_indices(needle).any(|(start, matched)| {
let before = text[..start].chars().next_back();
let after = text[start + matched.len()..].chars().next();
!before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
})
})
}
const ACTIVE_LIMIT_HEADER: &str = "x-codex-active-limit"; const ACTIVE_LIMIT_HEADER: &str = "x-codex-active-limit";
const REQUEST_ID_HEADER: &str = "x-request-id"; const REQUEST_ID_HEADER: &str = "x-request-id";
const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id"; const OAI_REQUEST_ID_HEADER: &str = "x-oai-request-id";
@@ -317,10 +355,6 @@ const CLOUDFLARE_BLOCKED_MESSAGE: &str =
#[path = "api_bridge_tests.rs"] #[path = "api_bridge_tests.rs"]
mod tests; mod tests;
fn extract_request_tracking_id(headers: Option<&HeaderMap>) -> Option<String> {
extract_request_id(headers).or_else(|| extract_header(headers, CF_RAY_HEADER))
}
fn api_error_user_message(status: http::StatusCode, body: &str) -> Option<String> { fn api_error_user_message(status: http::StatusCode, body: &str) -> Option<String> {
if status == http::StatusCode::FORBIDDEN if status == http::StatusCode::FORBIDDEN
&& body.contains("Cloudflare") && body.contains("Cloudflare")

View File

@@ -1,8 +1,8 @@
use super::*; use super::*;
use akode_http_client::RetryAfter;
use akode_protocol::protocol::CodexErrorInfo;
use akode_protocol::protocol::RateLimitReachedType;
use base64::Engine; use base64::Engine;
use codex_http_client::RetryAfter;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::RateLimitReachedType;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
#[test] #[test]
@@ -152,11 +152,9 @@ async fn http_retry_deadline_survives_mapping_and_respects_terminal_errors() {
error.to_string() error.to_string()
), ),
( (
CodexErrorInfo::ResponseTooManyFailedAttempts { CodexErrorInfo::RateLimitExceeded,
http_status_code: Some(429), None,
}, "Limite del provider raggiunto: sensitive upstream detail".to_string(),
Some(429),
"exceeded retry limit, last status: 429 Too Many Requests".to_string(),
), ),
); );
} }
@@ -479,7 +477,7 @@ fn map_api_error_preserves_misalignment_details_from_403_body() {
error_type: Some("unauthorized_data_transfer".to_string()), error_type: Some("unauthorized_data_transfer".to_string()),
review_target: Some(" RB/opaque== ".to_string()), review_target: Some(" RB/opaque== ".to_string()),
detailed_explanation: Some("The agent attempted an external transfer.".to_string()), detailed_explanation: Some("The agent attempted an external transfer.".to_string()),
steer: Some(codex_protocol::protocol::MisalignmentSteer { steer: Some(akode_protocol::protocol::MisalignmentSteer {
message: "Do not transfer the user's files.".to_string(), message: "Do not transfer the user's files.".to_string(),
}), }),
}) })
@@ -529,7 +527,7 @@ fn map_api_error_preserves_misalignment_details_from_wrapped_websocket_error() {
error_type: Some("future_safety_category".to_string()), error_type: Some("future_safety_category".to_string()),
review_target: Some(" RB/opaque== ".to_string()), review_target: Some(" RB/opaque== ".to_string()),
detailed_explanation: Some("The agent attempted an external transfer.".to_string()), detailed_explanation: Some("The agent attempted an external transfer.".to_string()),
steer: Some(codex_protocol::protocol::MisalignmentSteer { steer: Some(akode_protocol::protocol::MisalignmentSteer {
message: "Do not transfer the user's files.".to_string(), message: "Do not transfer the user's files.".to_string(),
}), }),
}) })
@@ -575,9 +573,7 @@ fn map_api_error_distinguishes_http_quota_errors_from_rate_limits() {
serde_json::json!({"type": "rate_limit_error", "code": "slow_down"}), serde_json::json!({"type": "rate_limit_error", "code": "slow_down"}),
] { ] {
let expected = if error["type"] == "rate_limit_error" { let expected = if error["type"] == "rate_limit_error" {
CodexErrorInfo::ResponseTooManyFailedAttempts { CodexErrorInfo::RateLimitExceeded
http_status_code: Some(429),
}
} else { } else {
CodexErrorInfo::UsageLimitExceeded CodexErrorInfo::UsageLimitExceeded
}; };
@@ -893,3 +889,43 @@ fn runtime_auth_denials_stop_retries_without_losing_http_diagnostics() {
} }
} }
} }
/// A plain provider 429 is a retryable rate limit; a daily allowance that is used up is terminal.
#[test]
fn map_api_error_classifies_provider_rate_limits() {
let map = |body: &str| {
map_api_error(ApiError::Transport(TransportError::Http {
retry_after: None,
status: http::StatusCode::TOO_MANY_REQUESTS,
url: None,
headers: None,
body: Some(body.to_string()),
}))
};
let err =
map(r#"{"error":{"message":"Rate limit exceeded: limit_rpm/google/gemma","code":429}}"#);
assert_eq!(
err.to_codex_protocol_error(),
CodexErrorInfo::RateLimitExceeded
);
assert!(err.retry_delay(/*retry_count*/ 1).is_some());
for body in [
r#"{"error":{"message":"Rate limit exceeded: free-models-per-day. Add 10 credits to unlock 1000 free model requests per day","code":429}}"#,
"daily request quota reached",
] {
let err = map(body);
assert_eq!(
err.to_codex_protocol_error(),
CodexErrorInfo::UsageLimitExceeded,
"{body}"
);
assert_eq!(err.retry_delay(/*retry_count*/ 1), None, "{body}");
assert!(
err.to_string()
.starts_with("Limite giornaliero del provider esaurito."),
"{err}"
);
}
}

View File

@@ -0,0 +1,121 @@
use akode_client::Request;
use akode_client::TransportError;
use akode_http_client::NetworkPolicyDenied;
use http::HeaderMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
/// Error returned while applying authentication to an outbound request.
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
#[error(transparent)]
Policy(#[from] NetworkPolicyDenied),
#[error("request auth build error: {0}")]
Build(String),
#[error("transient auth error: {0}")]
Transient(String),
}
impl From<AuthError> for TransportError {
fn from(error: AuthError) -> Self {
match error {
AuthError::Policy(denied) => TransportError::Policy(denied),
AuthError::Build(message) => TransportError::Build(message),
AuthError::Transient(message) => TransportError::Network(message),
}
}
}
/// Applies authentication to API requests.
///
/// Header-only providers can implement `add_auth_headers`; providers that sign
/// complete requests can override `apply_auth`.
pub trait AuthProvider: Send + Sync {
/// Adds any auth headers that are available without request body access.
///
/// Implementations should be cheap and non-blocking. This method is also
/// used by telemetry and non-HTTP request paths. Providers that require async
/// work must return an error here and override `apply_auth_headers`.
/// Callers must not send the request if this returns an error.
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError>;
/// Returns any auth headers that are available without request body access.
fn to_auth_headers(&self) -> Result<HeaderMap, AuthError> {
let mut headers = HeaderMap::new();
self.add_auth_headers(&mut headers)?;
Ok(headers)
}
/// Describes headers expected on a successful request without refreshing or registering auth.
/// Async providers should override this rather than resolving credentials for telemetry.
fn auth_header_telemetry(&self) -> Result<AuthHeaderTelemetry, AuthError> {
let headers = self.to_auth_headers()?;
let name = headers
.contains_key(http::header::AUTHORIZATION)
.then_some("authorization");
Ok(AuthHeaderTelemetry {
attached: name.is_some(),
name,
})
}
/// Refreshes credentials after an explicit HTTP 401. Returns whether the caller
/// may retry with new credentials. Callers must bound retries and pass the headers
/// of the rejected request so concurrent failures can reuse an earlier refresh.
fn refresh_after_unauthorized(&self, _rejected_headers: HeaderMap) -> AuthRefreshFuture<'_> {
Box::pin(async { false })
}
/// Authenticates a header-only request, including removing credentials it supersedes.
///
/// Implementations may refresh credentials asynchronously. Providers with static credentials
/// can rely on the default implementation.
/// Callers must use the returned map rather than overlaying resolved headers.
fn apply_auth_headers(&self, mut headers: HeaderMap) -> AuthHeadersFuture<'_> {
Box::pin(async move {
headers.extend(self.to_auth_headers()?);
Ok(headers)
})
}
/// Applies auth to a complete outbound request and returns the request to send.
///
/// The input `request` is moved into this method. Implementations may mutate
/// the owned request, or replace it entirely, before returning.
///
/// Header-only auth providers can rely on the default implementation.
/// Request-signing providers can override this to inspect the final URL,
/// headers, and body bytes before the transport sends the request.
///
/// Callers must always use the returned request as authoritative.
/// If this returns [`AuthError`], the request should not be sent.
fn apply_auth(&self, request: Request) -> AuthProviderFuture<'_> {
Box::pin(async move {
let mut request = request;
request.headers = self.apply_auth_headers(request.headers).await?;
Ok(request)
})
}
}
pub type AuthProviderFuture<'a> =
Pin<Box<dyn Future<Output = Result<Request, AuthError>> + Send + 'a>>;
pub type AuthHeadersFuture<'a> =
Pin<Box<dyn Future<Output = Result<HeaderMap, AuthError>> + Send + 'a>>;
pub type AuthRefreshFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
/// Shared auth handle passed through API clients.
pub type SharedAuthProvider = Arc<dyn AuthProvider>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AuthHeaderTelemetry {
pub attached: bool,
pub name: Option<&'static str>,
}
pub fn auth_header_telemetry(auth: &dyn AuthProvider) -> Result<AuthHeaderTelemetry, AuthError> {
auth.auth_header_telemetry()
}

View File

@@ -0,0 +1,446 @@
use crate::error::ApiError;
use akode_protocol::ResponseUsageMetadata;
use akode_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig;
use akode_protocol::config_types::Verbosity as VerbosityConfig;
use akode_protocol::models::ResponseItem;
use akode_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
use akode_protocol::protocol::RateLimitSnapshot;
use akode_protocol::protocol::TokenUsage;
use akode_protocol::protocol::TurnModerationMetadataEvent;
use akode_protocol::protocol::W3cTraceContext;
use akode_protocol::turn_input::PromptCacheTtl;
use futures::Stream;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use serde_json::value::RawValue;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
pub const WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY: &str = "ws_request_header_traceparent";
pub const WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY: &str = "ws_request_header_tracestate";
/// Canonical input payload for the memory summarize endpoint.
#[derive(Debug, Clone, Serialize)]
pub struct MemorySummarizeInput {
pub model: String,
#[serde(rename = "traces")]
pub raw_memories: Vec<RawMemory>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning: Option<Reasoning>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RawMemory {
pub id: String,
pub metadata: RawMemoryMetadata,
pub items: Vec<Value>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RawMemoryMetadata {
pub source_path: String,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct MemorySummarizeOutput {
#[serde(rename = "trace_summary", alias = "raw_memory")]
pub raw_memory: String,
pub memory_summary: String,
}
/// The latest server response ID received in this turn, shared with tool-review extensions.
#[derive(Clone, Debug)]
pub struct ResponseId(pub String);
#[derive(Debug)]
pub enum ResponseEvent {
Created {
/// Existing server response ID, when supplied by the stream.
response_id: Option<String>,
},
SafetyBuffering(SafetyBuffering),
OutputItemDone(ResponseItem),
OutputItemAdded(ResponseItem),
/// Emitted when the server includes `OpenAI-Model` on the stream response.
/// This can differ from the requested model when backend safety routing applies.
ServerModel(String),
/// Emitted when the server includes moderation metadata for first-party turn presentation.
TurnModerationMetadata(TurnModerationMetadataEvent),
/// Action-bound Guardian evidence for request-scoped consumers, not model history.
GuardianAssessment(crate::guardian_assessment::GuardianAssessment),
/// Emitted when `X-Reasoning-Included: true` is present on the response,
/// meaning the server already accounted for past reasoning tokens and the
/// client should not re-estimate them.
ServerReasoningIncluded(bool),
Completed {
response_id: String,
token_usage: Option<TokenUsage>,
usage_metadata: Option<ResponseUsageMetadata>,
/// Did the model affirmatively end its turn? Some providers do not set this,
/// so we rely on fallback logic when this is `None`.
end_turn: Option<bool>,
},
OutputTextDelta(String),
ToolCallInputDelta {
item_id: String,
call_id: Option<String>,
delta: String,
},
/// aKode: progress of a local server before generation starts (imeAI gateway
/// `imeai.queue` / `imeai.prefill`): `kind` is `queue` or `prefill`.
ServerProgress {
kind: String,
percent: Option<f64>,
eta_s: Option<f64>,
ahead: Option<u64>,
},
ReasoningSummaryDelta {
delta: String,
summary_index: i64,
},
ReasoningSummaryDone {
item_id: String,
text: String,
summary_index: i64,
},
ReasoningContentDelta {
delta: String,
content_index: i64,
},
ReasoningSummaryPartAdded {
summary_index: i64,
},
RateLimits(RateLimitSnapshot),
ModelsEtag(String),
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct SafetyBuffering {
pub use_cases: Vec<String>,
pub reasons: Vec<String>,
#[serde(skip)]
pub show_buffering_ui: bool,
#[serde(rename = "retry_model")]
pub faster_model: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct SafetyBufferingTreatment {
pub faster_model: Option<String>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningContext {
Auto,
CurrentTurn,
AllTurns,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct Reasoning {
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_reasoning_effort"
)]
pub effort: Option<ReasoningEffortConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<ReasoningSummaryConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<ReasoningContext>,
}
fn serialize_reasoning_effort<S>(
effort: &Option<ReasoningEffortConfig>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if let Some(ReasoningEffortConfig::Custom(value)) = effort
&& let Ok(value) = value.parse::<u64>()
{
return serializer.serialize_u64(value);
}
effort.serialize(serializer)
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningSummaryDelivery {
SequentialCutoff,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct StreamOptions {
pub reasoning_summary_delivery: ReasoningSummaryDelivery,
}
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TextFormatType {
#[default]
JsonSchema,
}
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
pub struct TextFormat {
/// Format type used by the OpenAI text controls.
pub r#type: TextFormatType,
/// When true, the server is expected to strictly validate responses.
pub strict: bool,
/// JSON schema for the desired output.
pub schema: Value,
/// Friendly name for the format, used in telemetry/debugging.
pub name: String,
}
/// Controls the `text` field for the Responses API, combining verbosity and
/// optional JSON schema output formatting.
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
pub struct TextControls {
#[serde(skip_serializing_if = "Option::is_none")]
pub verbosity: Option<OpenAiVerbosity>,
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<TextFormat>,
}
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum OpenAiVerbosity {
Low,
#[default]
Medium,
High,
}
impl From<VerbosityConfig> for OpenAiVerbosity {
fn from(v: VerbosityConfig) -> Self {
match v {
VerbosityConfig::Low => OpenAiVerbosity::Low,
VerbosityConfig::Medium => OpenAiVerbosity::Medium,
VerbosityConfig::High => OpenAiVerbosity::High,
}
}
}
/// Serialized tool definitions for Responses API requests.
///
/// Keeping the tool list as raw JSON avoids rebuilding a generic JSON value
/// tree, while the shared allocation keeps request clones cheap.
#[derive(Debug, Clone)]
pub struct ResponsesApiTools(Arc<RawValue>);
impl ResponsesApiTools {
pub(crate) fn as_raw_value(&self) -> &RawValue {
&self.0
}
}
impl From<Arc<RawValue>> for ResponsesApiTools {
fn from(value: Arc<RawValue>) -> Self {
Self(value)
}
}
impl PartialEq for ResponsesApiTools {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0) || self.0.get() == other.0.get()
}
}
impl Serialize for ResponsesApiTools {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct PromptCacheOptions {
pub ttl: PromptCacheTtl,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct ResponsesApiRequest {
// Keep routing fields first: serde serializes struct fields in declaration order, and
// gateways may inspect request bodies incrementally before potentially multi-megabyte input.
pub model: String,
pub stream: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_tier: Option<String>,
pub input: Vec<ResponseItem>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tools: Option<ResponsesApiTools>,
pub tool_choice: String,
pub parallel_tool_calls: bool,
pub reasoning: Option<Reasoning>,
pub store: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub stream_options: Option<StreamOptions>,
pub include: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_options: Option<PromptCacheOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<TextControls>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_metadata: Option<HashMap<String, String>>,
/// Sampling values configured per model; unset values are not sent.
#[serde(flatten)]
pub sampling: SamplingParams,
}
/// Optional sampling values of a Responses request (`temperature`, `top_p`,
/// `max_output_tokens`), configured per model.
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
pub struct SamplingParams {
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u64>,
}
impl<'a> From<&'a ResponsesApiRequest> for ResponseCreateWsRequest<'a> {
fn from(request: &'a ResponsesApiRequest) -> Self {
Self {
model: &request.model,
previous_response_id: None,
input: &request.input,
tools: request.tools.as_ref().map(ResponsesApiTools::as_raw_value),
tool_choice: &request.tool_choice,
parallel_tool_calls: request.parallel_tool_calls,
reasoning: request.reasoning.as_ref(),
store: request.store,
stream: request.stream,
stream_options: request.stream_options.as_ref(),
include: &request.include,
service_tier: request.service_tier.as_deref(),
prompt_cache_key: request.prompt_cache_key.as_deref(),
prompt_cache_options: request.prompt_cache_options,
text: request.text.as_ref(),
generate: None,
client_metadata: request.client_metadata.clone(),
}
}
}
#[derive(Debug, Serialize)]
pub struct ResponseCreateWsRequest<'a> {
// Keep routing fields first: serde serializes struct fields in declaration order, and
// gateways may inspect request bodies incrementally before potentially multi-megabyte input.
pub model: &'a str,
pub stream: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_tier: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub previous_response_id: Option<String>,
pub input: &'a [ResponseItem],
#[serde(skip_serializing_if = "Option::is_none")]
pub tools: Option<&'a RawValue>,
pub tool_choice: &'a str,
pub parallel_tool_calls: bool,
pub reasoning: Option<&'a Reasoning>,
pub store: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub stream_options: Option<&'a StreamOptions>,
pub include: &'a [String],
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_options: Option<PromptCacheOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<&'a TextControls>,
#[serde(skip_serializing_if = "Option::is_none")]
pub generate: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_metadata: Option<HashMap<String, String>>,
}
pub fn response_create_client_metadata(
client_metadata: Option<HashMap<String, String>>,
trace: Option<&W3cTraceContext>,
) -> Option<HashMap<String, String>> {
let mut client_metadata = client_metadata.unwrap_or_default();
if let Some(traceparent) = trace.and_then(|trace| trace.traceparent.as_deref()) {
client_metadata.insert(
WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY.to_string(),
traceparent.to_string(),
);
}
if let Some(tracestate) = trace.and_then(|trace| trace.tracestate.as_deref()) {
client_metadata.insert(
WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY.to_string(),
tracestate.to_string(),
);
}
(!client_metadata.is_empty()).then_some(client_metadata)
}
#[derive(Debug, Serialize)]
#[serde(tag = "type")]
#[allow(clippy::large_enum_variant)]
pub enum ResponsesWsRequest<'a> {
#[serde(rename = "response.create")]
ResponseCreate(ResponseCreateWsRequest<'a>),
}
pub fn create_text_param_for_request(
verbosity: Option<VerbosityConfig>,
output_schema: &Option<Value>,
output_schema_strict: bool,
) -> Option<TextControls> {
if verbosity.is_none() && output_schema.is_none() {
return None;
}
Some(TextControls {
verbosity: verbosity.map(std::convert::Into::into),
format: output_schema.as_ref().map(|schema| TextFormat {
r#type: TextFormatType::JsonSchema,
strict: output_schema_strict,
schema: schema.clone(),
name: "codex_output_schema".to_string(),
}),
})
}
/// Distinguishes draining a live response from abandoning obsolete work.
#[derive(Clone, Copy)]
pub enum ResponseInterrupt {
/// Drain normally, without validating or waiting for interruption acknowledgements.
Drain,
/// Skip undispatched work or retire its transport at the cleanup deadline.
/// Undispatched work ends without a completion event and leaves the socket reusable.
Cancel { deadline: tokio::time::Instant },
}
pub struct ResponseStream {
pub rx_event: mpsc::Receiver<Result<ResponseEvent, ApiError>>,
/// Server-assigned `x-request-id` response header, when present.
pub upstream_request_id: Option<String>,
/// Requests a graceful interrupt. Keep consuming events through completion.
/// Only `Cancel` validates and waits for an interruption acknowledgement.
pub interrupt: Option<oneshot::Sender<ResponseInterrupt>>,
}
impl Stream for ResponseStream {
type Item = Result<ResponseEvent, ApiError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.rx_event.poll_recv(cx)
}
}

View File

@@ -0,0 +1,227 @@
use crate::auth::SharedAuthProvider;
use crate::common::MemorySummarizeInput;
use crate::common::MemorySummarizeOutput;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use akode_client::HttpTransport;
use akode_client::RequestTelemetry;
use http::HeaderMap;
use http::Method;
use serde::Deserialize;
use serde_json::to_value;
use std::sync::Arc;
pub struct MemoriesClient<T: HttpTransport> {
session: EndpointSession<T>,
}
impl<T: HttpTransport> MemoriesClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
}
}
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
Self {
session: self.session.with_request_telemetry(request),
}
}
fn path() -> &'static str {
"memories/trace_summarize"
}
pub async fn summarize(
&self,
body: serde_json::Value,
extra_headers: HeaderMap,
) -> Result<Vec<MemorySummarizeOutput>, ApiError> {
let resp = self
.session
.execute(Method::POST, Self::path(), extra_headers, Some(body))
.await?;
let parsed: SummarizeResponse =
serde_json::from_slice(&resp.body).map_err(|e| ApiError::Stream(e.to_string()))?;
Ok(parsed.output)
}
pub async fn summarize_input(
&self,
input: &MemorySummarizeInput,
extra_headers: HeaderMap,
) -> Result<Vec<MemorySummarizeOutput>, ApiError> {
let body = to_value(input).map_err(|e| {
ApiError::Stream(format!("failed to encode memory summarize input: {e}"))
})?;
self.summarize(body, extra_headers).await
}
}
#[derive(Debug, Deserialize)]
struct SummarizeResponse {
output: Vec<MemorySummarizeOutput>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::AuthProvider;
use crate::common::RawMemory;
use crate::common::RawMemoryMetadata;
use crate::provider::RetryConfig;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use http::HeaderMap;
use http::Method;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
#[derive(Clone, Default)]
struct DummyTransport;
impl HttpTransport for DummyTransport {
async fn execute(&self, _req: Request) -> Result<Response, TransportError> {
Err(TransportError::Build("execute should not run".to_string()))
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
#[derive(Clone, Default)]
struct DummyAuth;
impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
Ok(())
}
}
#[derive(Clone)]
struct CapturingTransport {
last_request: Arc<Mutex<Option<Request>>>,
response_body: Arc<Vec<u8>>,
}
impl CapturingTransport {
fn new(response_body: Vec<u8>) -> Self {
Self {
last_request: Arc::new(Mutex::new(None)),
response_body: Arc::new(response_body),
}
}
}
impl HttpTransport for CapturingTransport {
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
*self.last_request.lock().expect("lock request store") = Some(req);
Ok(Response {
status: StatusCode::OK,
headers: HeaderMap::new(),
body: self.response_body.as_ref().clone().into(),
})
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
fn provider(base_url: &str) -> Provider {
Provider {
name: "test".to_string(),
base_url: base_url.to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
retry_5xx: true,
retry_transport: true,
},
stream_idle_timeout: Duration::from_secs(1),
}
}
#[test]
fn path_is_memories_trace_summarize_for_wire_compatibility() {
assert_eq!(
MemoriesClient::<DummyTransport>::path(),
"memories/trace_summarize"
);
}
#[tokio::test]
async fn summarize_input_posts_expected_payload_and_parses_output() {
let transport = CapturingTransport::new(
serde_json::to_vec(&json!({
"output": [
{
"trace_summary": "raw summary",
"memory_summary": "memory summary"
}
]
}))
.expect("serialize response"),
);
let client = MemoriesClient::new(
transport.clone(),
provider("https://example.com/api/codex"),
Arc::new(DummyAuth),
);
let input = MemorySummarizeInput {
model: "gpt-test".to_string(),
raw_memories: vec![RawMemory {
id: "trace-1".to_string(),
metadata: RawMemoryMetadata {
source_path: "/tmp/trace.json".to_string(),
},
items: vec![json!({"type": "message", "role": "user", "content": []})],
}],
reasoning: None,
};
let output = client
.summarize_input(&input, HeaderMap::new())
.await
.expect("summarize input request should succeed");
assert_eq!(output.len(), 1);
assert_eq!(output[0].raw_memory, "raw summary");
assert_eq!(output[0].memory_summary, "memory summary");
let request = transport
.last_request
.lock()
.expect("lock request store")
.clone()
.expect("request should be captured");
assert_eq!(request.method, Method::POST);
assert_eq!(
request.url,
"https://example.com/api/codex/memories/trace_summarize"
);
let body = request
.body
.as_ref()
.and_then(RequestBody::json)
.expect("request body should be JSON");
assert_eq!(body["model"], "gpt-test");
assert_eq!(body["traces"][0]["id"], "trace-1");
assert_eq!(
body["traces"][0]["metadata"]["source_path"],
"/tmp/trace.json"
);
}
}

View File

@@ -0,0 +1,434 @@
use crate::auth::SharedAuthProvider;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use akode_client::HttpTransport;
use akode_client::RequestTelemetry;
use akode_protocol::openai_models::ModelInfo;
use akode_protocol::openai_models::ModelsResponse;
use bytes::Bytes;
use http::HeaderMap;
use http::Method;
use http::header::ETAG;
use std::sync::Arc;
use url::Url;
pub struct ModelsClient<T: HttpTransport> {
session: EndpointSession<T>,
}
impl<T: HttpTransport> ModelsClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
}
}
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
Self {
session: self.session.with_request_telemetry(request),
}
}
fn path() -> &'static str {
"models"
}
fn append_client_version_query(req: &mut akode_client::Request, client_version: &str) {
let separator = if req.url.contains('?') { '&' } else { '?' };
req.url = format!("{}{}client_version={client_version}", req.url, separator);
}
pub fn request_url(provider: &Provider, client_version: &str) -> String {
let mut request = provider.build_request(Method::GET, Self::path());
Self::append_client_version_query(&mut request, client_version);
request.url
}
/// Builds a full catalog URL, preserving provider routing parameters and client version.
pub fn catalog_request_url(
provider: &Provider,
catalog_url: &str,
client_version: &str,
) -> Result<String, ApiError> {
let invalid = |message: &str| ApiError::InvalidRequest {
message: message.to_string(),
};
let mut url = Url::parse(catalog_url)
.map_err(|_| invalid("model_catalog_url must be an absolute URL"))?;
{
let mut query = url.query_pairs_mut();
if let Some(params) = &provider.query_params {
query.extend_pairs(params);
}
query.append_pair("client_version", client_version);
}
Ok(url.into())
}
/// Fetches and decodes a catalog, optionally bounding response bytes before decoding.
pub async fn list_models(
&self,
request_url: String,
extra_headers: HeaderMap,
response_body_limit_bytes: Option<usize>,
) -> Result<(Vec<ModelInfo>, Option<String>), ApiError> {
let (body, header_etag) = self
.list_models_raw(request_url, extra_headers, response_body_limit_bytes)
.await?;
let ModelsResponse { models } =
serde_json::from_slice::<ModelsResponse>(&body).map_err(|e| {
ApiError::Stream(format!(
"failed to decode models response: {:?} at line {} column {} (body: {} bytes)",
e.classify(),
e.line(),
e.column(),
body.len()
))
})?;
Ok((models, header_etag))
}
/// Fetches a catalog using the provider's auth and retry policy without decoding it.
///
/// Callers accepting provider-controlled catalogs must validate the native response
/// without including raw values in diagnostics.
pub async fn list_models_raw(
&self,
request_url: String,
extra_headers: HeaderMap,
response_body_limit_bytes: Option<usize>,
) -> Result<(Bytes, Option<String>), ApiError> {
let resp = self
.session
.execute_with(
Method::GET,
Self::path(),
extra_headers,
/*body*/ None,
move |req| {
req.url.clone_from(&request_url);
req.response_body_limit_bytes = response_body_limit_bytes;
},
)
.await?;
let header_etag = resp
.headers
.get(ETAG)
.and_then(|value| value.to_str().ok())
.map(ToString::to_string);
Ok((resp.body, header_etag))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::AuthError;
use crate::auth::AuthProvider;
use crate::auth::AuthProviderFuture;
use crate::provider::RetryConfig;
use akode_client::Request;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use http::HeaderMap;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
#[derive(Clone)]
struct CapturingTransport {
last_request: Arc<Mutex<Option<Request>>>,
body: Arc<ModelsResponse>,
etag: Option<String>,
}
impl Default for CapturingTransport {
fn default() -> Self {
Self {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(ModelsResponse { models: Vec::new() }),
etag: None,
}
}
}
impl HttpTransport for CapturingTransport {
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
*self.last_request.lock().unwrap() = Some(req);
let body = serde_json::to_vec(&*self.body).unwrap();
let mut headers = HeaderMap::new();
if let Some(etag) = &self.etag {
headers.insert(ETAG, etag.parse().unwrap());
}
Ok(Response {
status: StatusCode::OK,
headers,
body: body.into(),
})
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
#[derive(Clone, Default)]
struct DummyAuth;
impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
Ok(())
}
}
#[derive(Default)]
struct RetryAuth {
request_limits: Mutex<Vec<Option<usize>>>,
}
impl AuthProvider for RetryAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
headers.insert(http::header::AUTHORIZATION, "Bearer test".parse().unwrap());
Ok(())
}
fn apply_auth(&self, mut request: Request) -> AuthProviderFuture<'_> {
Box::pin(async move {
let mut limits = self.request_limits.lock().unwrap();
limits.push(request.response_body_limit_bytes);
if limits.len() == 1 {
return Err(AuthError::Transient("retry authentication".to_string()));
}
self.add_auth_headers(&mut request.headers)?;
Ok(request)
})
}
}
fn provider(base_url: &str) -> Provider {
Provider {
name: "test".to_string(),
base_url: base_url.to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
retry_5xx: true,
retry_transport: true,
},
stream_idle_timeout: Duration::from_secs(1),
}
}
#[test]
fn catalog_request_url_preserves_routing_and_encodes_queries() {
let mut provider = provider("https://gateway.example/v1");
provider.query_params = Some(std::collections::HashMap::from([(
"api-version".to_string(),
"2026 09".to_string(),
)]));
let url = ModelsClient::<CapturingTransport>::catalog_request_url(
&provider,
"https://catalog.example/codex/models?deployment=one",
"1.2.3",
)
.unwrap();
assert_eq!(
url,
"https://catalog.example/codex/models?deployment=one&api-version=2026+09&client_version=1.2.3"
);
}
#[test]
fn catalog_request_url_rejects_relative_urls() {
let provider = provider("https://gateway.example/v1");
for catalog_url in ["/codex/models", "codex/models"] {
let error = ModelsClient::<CapturingTransport>::catalog_request_url(
&provider,
catalog_url,
"1.2.3",
)
.unwrap_err();
assert!(matches!(error, ApiError::InvalidRequest { .. }));
}
}
#[tokio::test]
async fn response_body_limit_survives_auth_retry_without_limiting_other_models_requests() {
let transport = CapturingTransport::default();
let auth = Arc::new(RetryAuth::default());
let mut provider = provider("https://example.com/api/codex");
provider.retry.max_attempts = 2;
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport.clone(), provider, auth.clone());
client
.list_models(
request_url.clone(),
HeaderMap::new(),
/*response_body_limit_bytes*/ Some(64),
)
.await
.expect("limited request should succeed after auth retry");
{
let request = transport.last_request.lock().unwrap();
let request = request.as_ref().unwrap();
assert_eq!(request.response_body_limit_bytes, Some(64));
assert_eq!(request.url, request_url);
assert_eq!(request.headers[http::header::AUTHORIZATION], "Bearer test");
}
let (models, _) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("ordinary request on the same client should remain unbounded");
assert!(models.is_empty());
assert_eq!(
transport
.last_request
.lock()
.unwrap()
.as_ref()
.unwrap()
.response_body_limit_bytes,
None
);
assert_eq!(
*auth.request_limits.lock().unwrap(),
vec![Some(64), Some(64), None]
);
}
#[tokio::test]
async fn appends_client_version_query() {
let response = ModelsResponse { models: Vec::new() };
let transport = CapturingTransport {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(response),
etag: None,
};
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport.clone(), provider, Arc::new(DummyAuth));
let (models, _) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("request should succeed");
assert_eq!(models.len(), 0);
let url = transport
.last_request
.lock()
.unwrap()
.as_ref()
.unwrap()
.url
.clone();
assert_eq!(
url,
"https://example.com/api/codex/models?client_version=0.99.0"
);
}
#[tokio::test]
async fn parses_models_response() {
let response = ModelsResponse {
models: vec![
serde_json::from_value(json!({
"slug": "gpt-test",
"display_name": "gpt-test",
"description": "desc",
"default_reasoning_level": "medium",
"supported_reasoning_levels": [{"effort": "low", "description": "low"}, {"effort": "medium", "description": "medium"}, {"effort": "high", "description": "high"}],
"shell_type": "shell_command",
"visibility": "list",
"minimal_client_version": [0, 99, 0],
"supported_in_api": true,
"priority": 1,
"upgrade": null,
"support_verbosity": false,
"default_verbosity": null,
"apply_patch_tool_type": null,
"truncation_policy": {"mode": "bytes", "limit": 10_000},
"supports_image_detail_original": false,
"context_window": 272_000,
"experimental_supported_tools": [],
}))
.unwrap(),
],
};
let transport = CapturingTransport {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(response),
etag: None,
};
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
let (models, _) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("request should succeed");
assert_eq!(models.len(), 1);
assert_eq!(models[0].slug, "gpt-test");
assert_eq!(models[0].supported_in_api, true);
assert_eq!(models[0].priority, 1);
}
#[tokio::test]
async fn list_models_includes_etag() {
let response = ModelsResponse { models: Vec::new() };
let transport = CapturingTransport {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(response),
etag: Some("\"abc\"".to_string()),
};
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.1.0");
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
let (models, etag) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("request should succeed");
assert_eq!(models.len(), 0);
assert_eq!(etag, Some("\"abc\"".to_string()));
}
}

View File

@@ -5,11 +5,11 @@ use crate::endpoint::realtime_websocket::session_update_session_json;
use crate::endpoint::session::EndpointSession; use crate::endpoint::session::EndpointSession;
use crate::error::ApiError; use crate::error::ApiError;
use crate::provider::Provider; use crate::provider::Provider;
use akode_client::HttpTransport;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::RequestTelemetry;
use bytes::Bytes; use bytes::Bytes;
use codex_client::HttpTransport;
use codex_client::Request;
use codex_client::RequestBody;
use codex_client::RequestTelemetry;
use http::HeaderMap; use http::HeaderMap;
use http::HeaderValue; use http::HeaderValue;
use http::Method; use http::Method;
@@ -116,7 +116,7 @@ impl<T: HttpTransport> RealtimeCallClient<T> {
session_config: RealtimeSessionConfig, session_config: RealtimeSessionConfig,
extra_headers: HeaderMap, extra_headers: HeaderMap,
) -> Result<RealtimeCallResponse, ApiError> { ) -> Result<RealtimeCallResponse, ApiError> {
trace!(target: "codex_api::realtime_websocket::wire", "realtime call request SDP: {sdp}"); trace!(target: "akode_api::realtime_websocket::wire", "realtime call request SDP: {sdp}");
// WebRTC can begin inference as soon as the peer connection comes up, so the initial // WebRTC can begin inference as soon as the peer connection comes up, so the initial
// session payload is sent with call creation. Legacy sidebands still send session.update // session payload is sent with call creation. Legacy sidebands still send session.update
// after joining; Frameless sidebands attach to the session that is already running. // after joining; Frameless sidebands attach to the session that is already running.
@@ -253,11 +253,11 @@ mod tests {
use crate::endpoint::realtime_websocket::RealtimeOutputModality; use crate::endpoint::realtime_websocket::RealtimeOutputModality;
use crate::endpoint::realtime_websocket::RealtimeSessionMode; use crate::endpoint::realtime_websocket::RealtimeSessionMode;
use crate::provider::RetryConfig; use crate::provider::RetryConfig;
use codex_client::Request; use akode_client::Request;
use codex_client::Response; use akode_client::Response;
use codex_client::StreamResponse; use akode_client::StreamResponse;
use codex_client::TransportError; use akode_client::TransportError;
use codex_protocol::protocol::RealtimeVoice; use akode_protocol::protocol::RealtimeVoice;
use http::StatusCode; use http::StatusCode;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use std::sync::Mutex; use std::sync::Mutex;

View File

@@ -21,17 +21,17 @@ use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::parse_realtime_event; use crate::endpoint::realtime_websocket::protocol::parse_realtime_event;
use crate::error::ApiError; use crate::error::ApiError;
use crate::provider::Provider; use crate::provider::Provider;
use codex_client::backoff; use akode_client::backoff;
use codex_http_client::HttpClientFactory; use akode_http_client::HttpClientFactory;
use codex_http_client::NetworkPolicyDenied; use akode_http_client::NetworkPolicyDenied;
use codex_http_client::maybe_build_rustls_client_config_with_custom_ca; use akode_http_client::maybe_build_rustls_client_config_with_custom_ca;
use codex_protocol::protocol::ConversationTextParams; use akode_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole; use akode_protocol::protocol::ConversationTextRole;
use codex_protocol::protocol::RealtimeTranscriptDelta; use akode_protocol::protocol::RealtimeTranscriptDelta;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider; use akode_utils_rustls_provider::ensure_rustls_crypto_provider;
use codex_websocket_client::WebSocketConnection; use akode_websocket_client::WebSocketConnection;
use codex_websocket_client::WebSocketConnector; use akode_websocket_client::WebSocketConnector;
use codex_websocket_client::WebSocketTlsMode; use akode_websocket_client::WebSocketTlsMode;
use futures::SinkExt; use futures::SinkExt;
use futures::StreamExt; use futures::StreamExt;
use http::HeaderMap; use http::HeaderMap;
@@ -62,7 +62,7 @@ use tungstenite::protocol::WebSocketConfig;
use tungstenite::protocol::frame::coding::CloseCode; use tungstenite::protocol::frame::coding::CloseCode;
use url::Url; use url::Url;
const REALTIME_WIRE_LOG_TARGET: &str = "codex_api::realtime_websocket::wire"; const REALTIME_WIRE_LOG_TARGET: &str = "akode_api::realtime_websocket::wire";
mod sideband; mod sideband;
struct WsStream { struct WsStream {
@@ -94,7 +94,7 @@ impl WsStream {
let transport_task = tokio::spawn(async move { let transport_task = tokio::spawn(async move {
let mut inner = inner; let mut inner = inner;
let report_write_policy_error = |error: &WsError| { let report_write_policy_error = |error: &WsError| {
if let Some(denied) = codex_websocket_client::network_policy_denial(error) { if let Some(denied) = akode_websocket_client::network_policy_denial(error) {
terminal_policy_tx.send_replace(Some(denied)); terminal_policy_tx.send_replace(Some(denied));
let _ = tx_message.try_send(Err(Self::policy_error(denied))); let _ = tx_message.try_send(Err(Self::policy_error(denied)));
} }
@@ -140,7 +140,7 @@ impl WsStream {
trace!(payload_len = payload.len(), "realtime websocket received ping"); trace!(payload_len = payload.len(), "realtime websocket received ping");
if let Err(err) = inner.send(Message::Pong(payload)).await { if let Err(err) = inner.send(Message::Pong(payload)).await {
error!("realtime websocket failed to send pong: {err}"); error!("realtime websocket failed to send pong: {err}");
terminal_policy_tx.send_replace(codex_websocket_client::network_policy_denial(&err)); terminal_policy_tx.send_replace(akode_websocket_client::network_policy_denial(&err));
let _ = tx_message.send(Err(err)).await; let _ = tx_message.send(Err(err)).await;
break; break;
} }
@@ -178,7 +178,7 @@ impl WsStream {
} }
Err(err) => { Err(err) => {
error!("realtime websocket receive failed: {err}"); error!("realtime websocket receive failed: {err}");
terminal_policy_tx.send_replace(codex_websocket_client::network_policy_denial(&err)); terminal_policy_tx.send_replace(akode_websocket_client::network_policy_denial(&err));
let _ = tx_message.send(Err(err)).await; let _ = tx_message.send(Err(err)).await;
break; break;
} }
@@ -1020,7 +1020,7 @@ impl RealtimeWebsocketClient {
.await; .await;
match result { match result {
Ok(connection) => return Ok(connection), Ok(connection) => return Ok(connection),
Err(err @ ApiError::Transport(codex_http_client::TransportError::Policy(_))) => { Err(err @ ApiError::Transport(akode_http_client::TransportError::Policy(_))) => {
return Err(err); return Err(err);
} }
Err(err) if webrtc_sideband_session_ended(&err) => return Err(err), Err(err) if webrtc_sideband_session_ended(&err) => return Err(err),
@@ -1118,7 +1118,7 @@ impl RealtimeWebsocketClient {
let tls_config = match tls_config { let tls_config = match tls_config {
Some(tls_config) => Some(tls_config), Some(tls_config) => Some(tls_config),
None => Some( None => Some(
codex_http_client::build_windows_platform_tls_config().map_err(|err| { akode_http_client::build_windows_platform_tls_config().map_err(|err| {
ApiError::Stream(format!("failed to configure websocket TLS: {err}")) ApiError::Stream(format!("failed to configure websocket TLS: {err}"))
})?, })?,
), ),
@@ -1190,8 +1190,8 @@ fn webrtc_sideband_session_ended(err: &ApiError) -> bool {
} }
fn map_realtime_websocket_connect_error(err: WsError) -> ApiError { fn map_realtime_websocket_connect_error(err: WsError) -> ApiError {
if let Some(denied) = codex_websocket_client::network_policy_denial(&err) { if let Some(denied) = akode_websocket_client::network_policy_denial(&err) {
return ApiError::Transport(codex_http_client::TransportError::Policy(denied)); return ApiError::Transport(akode_http_client::TransportError::Policy(denied));
} }
match err { match err {
WsError::Http(response) => ApiError::Api { WsError::Http(response) => ApiError::Api {
@@ -1372,17 +1372,16 @@ mod transcript_tests;
mod tests { mod tests {
use super::*; use super::*;
use crate::endpoint::realtime_websocket::protocol::RealtimeTranscriptEntry; use crate::endpoint::realtime_websocket::protocol::RealtimeTranscriptEntry;
use crate::provider::RetryConfig; use akode_http_client::OutboundProxyPolicy::ReqwestDefault;
use codex_http_client::OutboundProxyPolicy::ReqwestDefault; use akode_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeHandoffRequested; use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
use codex_protocol::protocol::RealtimeInputAudioSpeechStarted; use akode_protocol::protocol::RealtimeNoopRequested;
use codex_protocol::protocol::RealtimeNoopRequested; use akode_protocol::protocol::RealtimeResponseCancelled;
use codex_protocol::protocol::RealtimeResponseCancelled; use akode_protocol::protocol::RealtimeResponseCreated;
use codex_protocol::protocol::RealtimeResponseCreated; use akode_protocol::protocol::RealtimeResponseDone;
use codex_protocol::protocol::RealtimeResponseDone; use akode_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDelta; use akode_protocol::protocol::RealtimeTranscriptDone;
use codex_protocol::protocol::RealtimeTranscriptDone; use akode_protocol::protocol::RealtimeVoice;
use codex_protocol::protocol::RealtimeVoice;
use http::HeaderValue; use http::HeaderValue;
use http::StatusCode; use http::StatusCode;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
@@ -1628,11 +1627,11 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn writer_policy_failure_reaches_realtime_events() { async fn writer_policy_failure_reaches_realtime_events() {
use codex_http_client::DestinationPolicy::Unrestricted; use akode_http_client::DestinationPolicy::Unrestricted;
use codex_http_client::NetworkPolicyController; use akode_http_client::NetworkPolicyController;
use codex_http_client::NetworkPolicyDenied::Revoked; use akode_http_client::NetworkPolicyDenied::Revoked;
use codex_http_client::TransportError::Policy; use akode_http_client::TransportError::Policy;
use codex_websocket_client::network_policy_denial; use akode_websocket_client::network_policy_denial;
use tokio::time::timeout; use tokio::time::timeout;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -2366,34 +2365,6 @@ mod tests {
} }
} }
#[test]
fn webrtc_frameless_sideband_ignores_provider_base_url() {
let client = test_client(Provider {
name: "chatgpt".to_string(),
base_url: "https://chatgpt.com/backend-api/codex".to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 0,
base_delay: Duration::ZERO,
retry_429: false,
retry_5xx: false,
retry_transport: false,
},
stream_idle_timeout: Duration::from_secs(5),
});
let url = client
.webrtc_sideband_url(
RealtimeEventParser::FramelessBidi,
RealtimeSessionMode::Conversational,
"rtc_test",
)
.expect("build ws url");
assert_eq!(url.as_str(), "wss://api.openai.com/v1/live/rtc_test");
}
#[tokio::test] #[tokio::test]
async fn e2e_connect_and_exchange_events_against_mock_ws_server() { async fn e2e_connect_and_exchange_events_against_mock_ws_server() {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");

View File

@@ -0,0 +1,158 @@
//! Adapts caller-owned, bounded JSON channels to the existing realtime parser and writer.
//!
//! ```text
//! Caller -- incoming JSON --> read loop -- Message::Text --> Core event parser
//! Caller <-- outgoing JSON -- write loop <-- WsCommand ----- Core writer
//! ```
//!
//! Each channel item carries one JSON message of up to 1 MiB. The loops run
//! independently so Core can still receive events while a command waits for
//! space in the caller's queue. Shutdown seals incoming messages and drains accepted
//! input before closing both directions, including a frame awaiting parser capacity.
use super::*;
use akode_protocol::protocol::RealtimeSidebandTransport;
const MAX_MESSAGE_BYTES: usize = 1024 * 1024;
impl RealtimeWebsocketConnection {
/// Uses an already authenticated, caller-owned stream without opening or reconnecting a socket.
pub fn from_sideband(
transport: RealtimeSidebandTransport,
event_parser: RealtimeEventParser,
) -> Self {
let RealtimeSidebandTransport {
mut incoming,
outgoing,
} = transport;
let (tx_command, mut rx_command) = mpsc::channel::<WsCommand>(32);
let (tx_message, rx_message) = async_channel::bounded(32);
let (_, terminal_policy_error) = tokio::sync::watch::channel(None);
let (input_stop, mut input_stopped) = tokio::sync::watch::channel(false);
let transport_input_stop = input_stop.clone();
let transport_task = tokio::spawn(async move {
let read = async {
let mut is_draining = false;
loop {
let text = if is_draining {
// A reserved but unsent permit must not hold shutdown open.
// try_recv() will drain messages already queued and exit when emptied.
incoming.try_recv().ok()
} else {
tokio::select! {
biased;
// Core requested shutdown, or the transport's write loop ended.
_ = input_stopped.changed() => {
incoming.close();
is_draining = true;
continue;
}
// The caller dropped its receiver for Core commands.
// Detect this even when the writer is idle, then drain accepted input.
_ = outgoing.closed() => {
incoming.close();
is_draining = true;
continue;
}
text = incoming.recv() => text,
}
};
let Some(text) = text else {
break;
};
if text.len() > MAX_MESSAGE_BYTES {
break;
}
if tx_message
.send(Ok(Message::Text(text.into())))
.await
.is_err()
{
break;
}
}
};
let write = async {
while let Some(command) = rx_command.recv().await {
// These commands are still called WsCommand for legacy reasons.
match command {
WsCommand::Send {
message: Message::Text(text),
tx_result,
} => {
let result = if text.len() > MAX_MESSAGE_BYTES {
Err(WsError::Io(std::io::Error::other(
"sideband message too large",
)))
} else {
outgoing
.send(text.to_string())
.await
.map_err(|_| WsError::ConnectionClosed)
};
let failed = result.is_err();
// Tell Core's writer whether the caller's channel accepted the command.
let _ = tx_result.send(result);
if failed {
break;
}
}
WsCommand::Close {
frame: _,
tx_result,
} => {
let _ = tx_result.send(Ok(()));
break;
}
WsCommand::Send { tx_result, .. } => {
let _ = tx_result.send(Err(WsError::Io(std::io::Error::other(
"sideband requires JSON text",
))));
break;
}
}
}
};
tokio::pin!(read);
tokio::select! {
_ = &mut read => {},
_ = write => {
transport_input_stop.send_replace(true);
// Preserve the read future: it may already own a frame that
// has not yet fit into the parser queue.
read.await;
},
}
});
Self::new(
WsStream {
tx_command,
transport_task,
sideband_input_stop: Some(input_stop),
terminal_policy_error,
},
rx_message,
event_parser,
RealtimeTranscriptState::default(),
)
}
}
impl RealtimeWebsocketWriter {
/// Seal caller-owned input so its accepted events can drain without waiting for producers.
/// Socket-backed connections are unaffected.
pub fn close_sideband_input(&self) {
if let Some(input_stop) = &self.stream.sideband_input_stop {
input_stop.send_replace(true);
}
}
}
#[cfg(test)]
#[path = "sideband_tests.rs"]
mod tests;

View File

@@ -145,8 +145,8 @@ async fn queued_transcript_survives_peer_hangup() {
.unwrap() .unwrap()
.unwrap(), .unwrap(),
Some( Some(
codex_protocol::protocol::RealtimeEvent::InputTranscriptDelta( akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
codex_protocol::protocol::RealtimeTranscriptDelta { akode_protocol::protocol::RealtimeTranscriptDelta {
delta: "last words".into() delta: "last words".into()
} }
) )
@@ -154,7 +154,7 @@ async fn queued_transcript_survives_peer_hangup() {
); );
assert_eq!( assert_eq!(
connection.events().take_transcript_tail().await, connection.events().take_transcript_tail().await,
vec![codex_protocol::protocol::RealtimeTranscriptEntry { vec![akode_protocol::protocol::RealtimeTranscriptEntry {
role: "user".into(), role: "user".into(),
text: "last words".into() text: "last words".into()
}] }]
@@ -192,8 +192,8 @@ async fn input_stop_drains_backpressure_without_waiting_for_reserved_permit() {
.unwrap() .unwrap()
.unwrap(), .unwrap(),
Some( Some(
codex_protocol::protocol::RealtimeEvent::InputTranscriptDelta( akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
codex_protocol::protocol::RealtimeTranscriptDelta { akode_protocol::protocol::RealtimeTranscriptDelta {
delta: "tail".into() delta: "tail".into()
} }
) )

View File

@@ -53,8 +53,8 @@ fn client(base_url: String) -> RealtimeWebsocketClient {
}, },
stream_idle_timeout: Duration::from_secs(5), stream_idle_timeout: Duration::from_secs(5),
}, },
codex_http_client::HttpClientFactory::new( akode_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault, akode_http_client::OutboundProxyPolicy::ReqwestDefault,
), ),
) )
.with_webrtc_sideband_base_url(base_url) .with_webrtc_sideband_base_url(base_url)

View File

@@ -17,8 +17,8 @@ use crate::endpoint::realtime_websocket::protocol::RealtimeSessionConfig;
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode; use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice; use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::RealtimeWireAdapter; use crate::endpoint::realtime_websocket::protocol::RealtimeWireAdapter;
use codex_protocol::protocol::ConversationTextParams; use akode_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole; use akode_protocol::protocol::ConversationTextRole;
use serde_json::Result as JsonResult; use serde_json::Result as JsonResult;
use serde_json::Value; use serde_json::Value;
use serde_json::to_value; use serde_json::to_value;

View File

@@ -3,8 +3,8 @@ use crate::endpoint::realtime_websocket::protocol::FramelessInputTextContent;
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel; use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage; use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice; use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use codex_protocol::protocol::ConversationTextParams; use akode_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole; use akode_protocol::protocol::ConversationTextRole;
use serde_json::Value; use serde_json::Value;
use serde_json::json; use serde_json::json;

View File

@@ -2,8 +2,8 @@ use super::CONTEXT_APPEND_MAX_BYTES;
use super::context_append_chunks; use super::context_append_chunks;
use super::session_json; use super::session_json;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice; use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use codex_protocol::protocol::ConversationTextParams; use akode_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole; use akode_protocol::protocol::ConversationTextRole;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use serde_json::json; use serde_json::json;

View File

@@ -13,7 +13,7 @@ use crate::endpoint::realtime_websocket::protocol::SessionAudioInput;
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput; use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput;
use crate::endpoint::realtime_websocket::protocol::SessionType; use crate::endpoint::realtime_websocket::protocol::SessionType;
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession; use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
use codex_protocol::protocol::ConversationTextRole; use akode_protocol::protocol::ConversationTextRole;
pub(super) fn conversation_item_create_message( pub(super) fn conversation_item_create_message(
text: String, text: String,

View File

@@ -24,7 +24,7 @@ use crate::endpoint::realtime_websocket::protocol::SessionTurnDetection;
use crate::endpoint::realtime_websocket::protocol::SessionType; use crate::endpoint::realtime_websocket::protocol::SessionType;
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession; use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
use crate::endpoint::realtime_websocket::protocol::TurnDetectionType; use crate::endpoint::realtime_websocket::protocol::TurnDetectionType;
use codex_protocol::protocol::ConversationTextRole; use akode_protocol::protocol::ConversationTextRole;
use serde_json::json; use serde_json::json;
const REALTIME_V2_OUTPUT_MODALITY_AUDIO: &str = "audio"; const REALTIME_V2_OUTPUT_MODALITY_AUDIO: &str = "audio";

View File

@@ -0,0 +1,272 @@
use crate::endpoint::realtime_websocket::protocol_frameless_bidi::parse_frameless_bidi_event;
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
use crate::endpoint::realtime_websocket::protocol_v2::parse_realtime_event_v2;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
pub use akode_protocol::protocol::RealtimeAudioFrame;
pub use akode_protocol::protocol::RealtimeEvent;
pub use akode_protocol::protocol::RealtimeOutputModality;
pub use akode_protocol::protocol::RealtimeTranscriptEntry;
pub use akode_protocol::protocol::RealtimeVoice;
use serde::Serialize;
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RealtimeEventParser {
V1,
FramelessBidi,
RealtimeV2,
}
pub type RealtimeWireAdapter = RealtimeEventParser;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RealtimeSessionMode {
Conversational,
Transcription,
}
/// Selects the semantic stream used for Frameless Bidi context appends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RealtimeContextAppendChannel {
Speakable,
Commentary,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RealtimeSessionConfig {
pub instructions: String,
pub initial_items: Vec<ConversationTextParams>,
pub delegation_ack_filler: Option<bool>,
pub model: Option<String>,
pub session_id: Option<String>,
pub event_parser: RealtimeEventParser,
pub session_mode: RealtimeSessionMode,
pub output_modality: RealtimeOutputModality,
pub voice: RealtimeVoice,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub(super) enum RealtimeOutboundMessage {
#[serde(rename = "input_audio_buffer.append")]
InputAudioBufferAppend { audio: String },
#[serde(rename = "conversation.handoff.append")]
ConversationHandoffAppend {
handoff_id: String,
output_text: String,
},
#[serde(rename = "input_audio.append")]
InputAudioAppend { audio: String },
#[serde(rename = "delegation.context.append")]
DelegationContextAppend {
delegation_item_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
channel: Option<RealtimeContextAppendChannel>,
content: Vec<FramelessInputTextContent>,
},
#[serde(rename = "session.context.append")]
SessionContextAppend {
#[serde(skip_serializing_if = "Option::is_none")]
channel: Option<RealtimeContextAppendChannel>,
content: Vec<FramelessInputTextContent>,
},
#[serde(rename = "session.close")]
SessionClose,
#[serde(rename = "response.create")]
ResponseCreate,
#[serde(rename = "session.update")]
SessionUpdate { session: SessionUpdateSession },
#[serde(rename = "session.update")]
FramelessSessionUpdate { session: Value },
#[serde(rename = "conversation.item.create")]
ConversationItemCreate { item: ConversationItemPayload },
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct FramelessInputTextContent {
#[serde(rename = "type")]
pub(super) r#type: FramelessContentType,
pub(super) text: String,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum FramelessContentType {
InputText,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionUpdateSession {
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) id: Option<String>,
#[serde(rename = "type")]
pub(super) r#type: SessionType,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) instructions: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) output_modalities: Option<Vec<String>>,
pub(super) audio: SessionAudio,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) tools: Option<Vec<SessionFunctionTool>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) tool_choice: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum SessionType {
Quicksilver,
Realtime,
Transcription,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudio {
pub(super) input: SessionAudioInput,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) output: Option<SessionAudioOutput>,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioInput {
pub(super) format: SessionAudioFormat,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) noise_reduction: Option<SessionNoiseReduction>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) transcription: Option<SessionInputAudioTranscription>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) turn_detection: Option<SessionTurnDetection>,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionInputAudioTranscription {
pub(super) model: String,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioFormat {
#[serde(rename = "type")]
pub(super) r#type: AudioFormatType,
pub(super) rate: u32,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub(super) enum AudioFormatType {
#[serde(rename = "audio/pcm")]
AudioPcm,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) format: Option<SessionAudioOutputFormat>,
pub(super) voice: RealtimeVoice,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionNoiseReduction {
#[serde(rename = "type")]
pub(super) r#type: NoiseReductionType,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum NoiseReductionType {
NearField,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionTurnDetection {
#[serde(rename = "type")]
pub(super) r#type: TurnDetectionType,
pub(super) interrupt_response: bool,
pub(super) create_response: bool,
pub(super) silence_duration_ms: u32,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum TurnDetectionType {
ServerVad,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioOutputFormat {
#[serde(rename = "type")]
pub(super) r#type: AudioFormatType,
pub(super) rate: u32,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationMessageItem {
#[serde(rename = "type")]
pub(super) r#type: ConversationItemType,
pub(super) role: ConversationTextRole,
pub(super) content: Vec<ConversationItemContent>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum ConversationItemType {
Message,
FunctionCallOutput,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub(super) enum ConversationItemPayload {
Message(ConversationMessageItem),
FunctionCallOutput(ConversationFunctionCallOutputItem),
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationFunctionCallOutputItem {
#[serde(rename = "type")]
pub(super) r#type: ConversationItemType,
pub(super) call_id: String,
pub(super) output: String,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationItemContent {
#[serde(rename = "type")]
pub(super) r#type: ConversationContentType,
pub(super) text: String,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum ConversationContentType {
InputText,
OutputText,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionFunctionTool {
#[serde(rename = "type")]
pub(super) r#type: SessionToolType,
pub(super) name: String,
pub(super) description: String,
pub(super) parameters: Value,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum SessionToolType {
Function,
}
pub(super) fn parse_realtime_event(
payload: &str,
event_parser: RealtimeEventParser,
) -> Option<RealtimeEvent> {
match event_parser {
RealtimeEventParser::V1 => parse_realtime_event_v1(payload),
RealtimeEventParser::FramelessBidi => parse_frameless_bidi_event(payload),
RealtimeEventParser::RealtimeV2 => parse_realtime_event_v2(payload),
}
}

View File

@@ -1,6 +1,6 @@
use codex_protocol::protocol::RealtimeEvent; use akode_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeTranscriptDelta; use akode_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDone; use akode_protocol::protocol::RealtimeTranscriptDone;
use serde_json::Value; use serde_json::Value;
use tracing::debug; use tracing::debug;

View File

@@ -1,11 +1,11 @@
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event; use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload; use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event; use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use codex_protocol::protocol::RealtimeAudioFrame; use akode_protocol::protocol::RealtimeAudioFrame;
use codex_protocol::protocol::RealtimeEvent; use akode_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested; use akode_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeTranscriptDelta; use akode_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDone; use akode_protocol::protocol::RealtimeTranscriptDone;
use serde_json::Value; use serde_json::Value;
use tracing::debug; use tracing::debug;

View File

@@ -1,7 +1,7 @@
use super::parse_frameless_bidi_event; use super::parse_frameless_bidi_event;
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1; use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
use codex_protocol::protocol::RealtimeEvent; use akode_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested; use akode_protocol::protocol::RealtimeHandoffRequested;
#[test] #[test]
fn legacy_and_frameless_delegations_decode_to_the_same_handoff() { fn legacy_and_frameless_delegations_decode_to_the_same_handoff() {

View File

@@ -3,9 +3,9 @@ use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event; use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event; use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event; use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
use codex_protocol::protocol::RealtimeAudioFrame; use akode_protocol::protocol::RealtimeAudioFrame;
use codex_protocol::protocol::RealtimeEvent; use akode_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested; use akode_protocol::protocol::RealtimeHandoffRequested;
use serde_json::Value; use serde_json::Value;
use tracing::debug; use tracing::debug;

View File

@@ -3,14 +3,14 @@ use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event; use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event; use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event; use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
use codex_protocol::protocol::RealtimeAudioFrame; use akode_protocol::protocol::RealtimeAudioFrame;
use codex_protocol::protocol::RealtimeEvent; use akode_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested; use akode_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeInputAudioSpeechStarted; use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
use codex_protocol::protocol::RealtimeNoopRequested; use akode_protocol::protocol::RealtimeNoopRequested;
use codex_protocol::protocol::RealtimeResponseCancelled; use akode_protocol::protocol::RealtimeResponseCancelled;
use codex_protocol::protocol::RealtimeResponseCreated; use akode_protocol::protocol::RealtimeResponseCreated;
use codex_protocol::protocol::RealtimeResponseDone; use akode_protocol::protocol::RealtimeResponseDone;
use serde_json::Map as JsonMap; use serde_json::Map as JsonMap;
use serde_json::Value; use serde_json::Value;
use tracing::debug; use tracing::debug;

View File

@@ -0,0 +1,131 @@
//! V3 transcript reconciliation across interleaved speakers, reconnects, and turn boundaries.
use super::*;
use akode_protocol::protocol::RealtimeTranscriptDone;
use pretty_assertions::assert_eq;
fn events(transcript_state: RealtimeTranscriptState) -> RealtimeWebsocketEvents {
let (_, rx_message) = async_channel::unbounded();
RealtimeWebsocketEvents {
rx_message,
pending_events: Arc::new(Mutex::new(VecDeque::new())),
transcript_state,
event_parser: RealtimeEventParser::FramelessBidi,
is_closed: Arc::new(AtomicBool::new(false)),
}
}
fn entry(role: &str, text: &str) -> RealtimeTranscriptEntry {
RealtimeTranscriptEntry {
role: role.to_string(),
text: text.to_string(),
}
}
async fn observe(events: &RealtimeWebsocketEvents, mut event: RealtimeEvent) {
let original = event.clone();
events.update_active_transcript(&mut event).await;
assert_eq!(
event, original,
"live transcript events must pass through unchanged"
);
}
#[tokio::test]
async fn interleaved_transcripts_reconcile_across_reconnect_in_either_completion_order() {
for assistant_finishes_first in [false, true] {
let state = RealtimeTranscriptState::default();
let first = events(state.clone());
for event in [
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
delta: "What can ".into(),
}),
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
delta: "A bunch ".into(),
}),
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
delta: "you do?".into(),
}),
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
delta: "of stuff".into(),
}),
] {
observe(&first, event).await;
}
let reconnected = events(state);
let user = RealtimeEvent::InputTranscriptDone(RealtimeTranscriptDone {
text: "What can you do?".into(),
});
let assistant = RealtimeEvent::OutputTranscriptDone(RealtimeTranscriptDone {
text: "A bunch of stuff, including coding.".into(),
});
let finals = if assistant_finishes_first {
[assistant, user]
} else {
[user, assistant]
};
for event in finals {
observe(&reconnected, event).await;
}
assert_eq!(
reconnected.take_transcript_tail().await,
vec![
entry("user", "What can you do?"),
entry("assistant", "A bunch of stuff, including coding."),
]
);
assert_eq!(reconnected.take_transcript_tail().await, vec![]);
}
}
#[tokio::test]
async fn completed_utterances_keep_repeated_speech_and_final_only_turns_distinct() {
let events = events(RealtimeTranscriptState::default());
for role in ["user", "assistant"] {
for with_delta in [true, true, false] {
if with_delta {
let delta = RealtimeTranscriptDelta {
delta: "Again".into(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDelta(delta)
} else {
RealtimeEvent::OutputTranscriptDelta(delta)
},
)
.await;
}
let done = RealtimeTranscriptDone {
text: "Again.".into(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDone(done)
} else {
RealtimeEvent::OutputTranscriptDone(done)
},
)
.await;
// An empty delta must not reopen the utterance we just completed.
let empty = RealtimeTranscriptDelta {
delta: String::new(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDelta(empty)
} else {
RealtimeEvent::OutputTranscriptDelta(empty)
},
)
.await;
}
assert_eq!(
events.take_transcript_tail().await,
vec![entry(role, "Again."); 3]
);
}
}

View File

@@ -0,0 +1,169 @@
use crate::auth::SharedAuthProvider;
use crate::common::ResponseStream;
use crate::common::ResponsesApiRequest;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use crate::requests::Compression;
use crate::requests::headers::build_session_headers;
use crate::requests::headers::insert_header;
use crate::requests::headers::subagent_header;
use crate::sse::spawn_response_stream;
use crate::telemetry::SseTelemetry;
use akode_client::EncodedJsonBody;
use akode_client::HttpTransport;
use akode_client::RequestCompression;
use akode_client::RequestTelemetry;
use akode_protocol::protocol::SessionSource;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use serde_json::Value;
use std::sync::Arc;
use std::sync::OnceLock;
use tracing::instrument;
pub struct ResponsesClient<T: HttpTransport> {
session: EndpointSession<T>,
sse_telemetry: Option<Arc<dyn SseTelemetry>>,
}
#[derive(Default)]
pub struct ResponsesOptions {
pub session_id: Option<String>,
pub thread_id: Option<String>,
pub session_source: Option<SessionSource>,
pub extra_headers: HeaderMap,
pub compression: Compression,
pub turn_state: Option<Arc<OnceLock<String>>>,
}
impl<T: HttpTransport> ResponsesClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
sse_telemetry: None,
}
}
pub fn with_telemetry(
self,
request: Option<Arc<dyn RequestTelemetry>>,
sse: Option<Arc<dyn SseTelemetry>>,
) -> Self {
Self {
session: self.session.with_request_telemetry(request),
sse_telemetry: sse,
}
}
#[instrument(
name = "responses.stream_request",
level = "info",
skip_all,
fields(
transport = "responses_http",
http.method = "POST",
api.path = "/responses"
)
)]
pub async fn stream_request(
&self,
request: ResponsesApiRequest,
options: ResponsesOptions,
) -> Result<ResponseStream, ApiError> {
let ResponsesOptions {
session_id,
thread_id,
session_source,
extra_headers,
compression,
turn_state,
} = options;
let body = EncodedJsonBody::encode(&request)
.map_err(|e| ApiError::Stream(format!("failed to encode responses request: {e}")))?;
let mut headers = extra_headers;
if let Some(ref thread_id) = thread_id {
insert_header(&mut headers, "x-client-request-id", thread_id);
}
headers.extend(build_session_headers(session_id, thread_id));
if let Some(subagent) = subagent_header(&session_source) {
insert_header(&mut headers, "x-openai-subagent", &subagent);
}
self.stream_encoded(body, headers, compression, turn_state)
.await
}
#[instrument(
name = "responses.stream",
level = "info",
skip_all,
fields(
transport = "responses_http",
http.method = "POST",
api.path = "/responses",
turn.has_state = turn_state.is_some()
)
)]
pub async fn stream(
&self,
body: Value,
extra_headers: HeaderMap,
compression: Compression,
turn_state: Option<Arc<OnceLock<String>>>,
) -> Result<ResponseStream, ApiError> {
let body = EncodedJsonBody::encode(&body)
.map_err(|e| ApiError::Stream(format!("failed to encode responses request: {e}")))?;
self.stream_encoded(body, extra_headers, compression, turn_state)
.await
}
async fn stream_encoded(
&self,
body: EncodedJsonBody,
extra_headers: HeaderMap,
compression: Compression,
turn_state: Option<Arc<OnceLock<String>>>,
) -> Result<ResponseStream, ApiError> {
let request_compression = match compression {
Compression::None => RequestCompression::None,
Compression::Zstd => RequestCompression::Zstd,
};
let idle_timeout = self.session.provider().stream_idle_timeout;
// Local servers may send the headers only with the first token, after reading the whole
// prompt: the wait is bounded by the same (generous, configurable) idle timeout.
let stream_response = tokio::time::timeout(
idle_timeout,
self.session.stream_encoded_json_with(
Method::POST,
"/responses",
extra_headers,
Some(body),
|req| {
req.headers.insert(
http::header::ACCEPT,
HeaderValue::from_static("text/event-stream"),
);
req.compression = request_compression;
},
),
)
.await
.map_err(|_| {
ApiError::Stream(format!(
"nessuna risposta dal server entro {} s (stream_idle_timeout_ms)",
idle_timeout.as_secs()
))
})??;
Ok(spawn_response_stream(
stream_response,
idle_timeout,
self.sse_telemetry.clone(),
turn_state,
))
}
}

View File

@@ -18,11 +18,11 @@ use crate::safety_buffering::treatment_from_headers;
use crate::sse::ResponsesStreamEvent; use crate::sse::ResponsesStreamEvent;
use crate::sse::process_responses_event; use crate::sse::process_responses_event;
use crate::telemetry::WebsocketTelemetry; use crate::telemetry::WebsocketTelemetry;
use codex_client::TransportError; use akode_client::TransportError;
use codex_http_client::HttpClientFactory; use akode_http_client::HttpClientFactory;
use codex_http_client::RetryAfter; use akode_http_client::RetryAfter;
use codex_websocket_client::WebSocketConnection; use akode_websocket_client::WebSocketConnection;
use codex_websocket_client::WebSocketConnector; use akode_websocket_client::WebSocketConnector;
use futures::FutureExt; use futures::FutureExt;
use futures::SinkExt; use futures::SinkExt;
use futures::StreamExt; use futures::StreamExt;
@@ -175,7 +175,7 @@ const PREVIOUS_RESPONSE_NOT_FOUND_CODE: &str = "previous_response_not_found";
const PREVIOUS_RESPONSE_NOT_FOUND_MESSAGE: &str = const PREVIOUS_RESPONSE_NOT_FOUND_MESSAGE: &str =
"Previous response was not found. Retrying the full request."; "Previous response was not found. Retrying the full request.";
const RESPONSES_WEBSOCKET_TIMING_KIND: &str = "responsesapi.websocket_timing"; const RESPONSES_WEBSOCKET_TIMING_KIND: &str = "responsesapi.websocket_timing";
const RESPONSES_WEBSOCKET_TIMING_EVENT_TARGET: &str = "codex_api::responses_websocket_timing"; const RESPONSES_WEBSOCKET_TIMING_EVENT_TARGET: &str = "akode_api::responses_websocket_timing";
const SESSION_ID_CLIENT_METADATA_KEY: &str = "session_id"; const SESSION_ID_CLIENT_METADATA_KEY: &str = "session_id";
const THREAD_ID_CLIENT_METADATA_KEY: &str = "thread_id"; const THREAD_ID_CLIENT_METADATA_KEY: &str = "thread_id";
const TURN_ID_CLIENT_METADATA_KEY: &str = "turn_id"; const TURN_ID_CLIENT_METADATA_KEY: &str = "turn_id";
@@ -639,14 +639,14 @@ fn websocket_config() -> WebSocketConfig {
} }
fn map_ws_stream_error(error: WsError) -> ApiError { fn map_ws_stream_error(error: WsError) -> ApiError {
match codex_websocket_client::network_policy_denial(&error) { match akode_websocket_client::network_policy_denial(&error) {
Some(denied) => ApiError::Transport(TransportError::Policy(denied)), Some(denied) => ApiError::Transport(TransportError::Policy(denied)),
None => ApiError::Stream(error.to_string()), None => ApiError::Stream(error.to_string()),
} }
} }
fn map_ws_error(err: WsError, url: &Url) -> ApiError { fn map_ws_error(err: WsError, url: &Url) -> ApiError {
if let Some(denied) = codex_websocket_client::network_policy_denial(&err) { if let Some(denied) = akode_websocket_client::network_policy_denial(&err) {
return ApiError::Transport(TransportError::Policy(denied)); return ApiError::Transport(TransportError::Policy(denied));
} }
match err { match err {
@@ -1015,7 +1015,7 @@ fn emit_responses_websocket_timing_event(
} }
// This full payload is excluded from always-on sinks. Opt in with // This full payload is excluded from always-on sinks. Opt in with
// `RUST_LOG='codex_api::responses_websocket_timing=trace'`. // `RUST_LOG='akode_api::responses_websocket_timing=trace'`.
tracing::event!( tracing::event!(
name: RESPONSES_WEBSOCKET_TIMING_KIND, name: RESPONSES_WEBSOCKET_TIMING_KIND,
target: RESPONSES_WEBSOCKET_TIMING_EVENT_TARGET, target: RESPONSES_WEBSOCKET_TIMING_EVENT_TARGET,
@@ -1086,9 +1086,9 @@ mod tests {
use super::*; use super::*;
use crate::common::ResponseCreateWsRequest; use crate::common::ResponseCreateWsRequest;
use crate::common::ResponsesApiRequest; use crate::common::ResponsesApiRequest;
use codex_protocol::ResponseItemId; use akode_protocol::ResponseItemId;
use codex_protocol::models::ContentItem; use akode_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem; use akode_protocol::models::ResponseItem;
use http::HeaderValue; use http::HeaderValue;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
use serde_json::json; use serde_json::json;
@@ -1133,13 +1133,14 @@ mod tests {
service_tier: Some("priority".to_string()), service_tier: Some("priority".to_string()),
prompt_cache_key: Some("cache-key".to_string()), prompt_cache_key: Some("cache-key".to_string()),
prompt_cache_options: Some(crate::PromptCacheOptions { prompt_cache_options: Some(crate::PromptCacheOptions {
ttl: codex_protocol::turn_input::PromptCacheTtl::TwelveHours, ttl: akode_protocol::turn_input::PromptCacheTtl::TwelveHours,
}), }),
text: None, text: None,
client_metadata: Some(HashMap::from([( client_metadata: Some(HashMap::from([(
"traceparent".to_string(), "traceparent".to_string(),
"00-0123456789abcdef0123456789abcdef-0123456789abcdef-01".to_string(), "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01".to_string(),
)])), )])),
sampling: Default::default(),
}; };
let request = ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest { let request = ResponsesWsRequest::ResponseCreate(ResponseCreateWsRequest {
previous_response_id: Some("resp-1".to_string()), previous_response_id: Some("resp-1".to_string()),
@@ -1268,7 +1269,7 @@ mod tests {
let wrapped = parse_wrapped_websocket_error_event(&payload).expect("websocket error"); let wrapped = parse_wrapped_websocket_error_event(&payload).expect("websocket error");
let api_error = map_wrapped_websocket_error_event(wrapped, payload).expect("API error"); let api_error = map_wrapped_websocket_error_event(wrapped, payload).expect("API error");
let err = crate::api_bridge::map_api_error(api_error); let err = crate::api_bridge::map_api_error(api_error);
let codex_protocol::error::CodexErrorDetails::UsageLimitReached(usage_limit) = let akode_protocol::error::CodexErrorDetails::UsageLimitReached(usage_limit) =
err.details() err.details()
else { else {
panic!("expected usage-limit error, got {err:?}"); panic!("expected usage-limit error, got {err:?}");

View File

@@ -8,7 +8,7 @@ use super::merge_request_headers;
use crate::ApiError; use crate::ApiError;
use crate::RESPONSES_PATH; use crate::RESPONSES_PATH;
use crate::WebsocketTelemetry; use crate::WebsocketTelemetry;
use codex_websocket_client::WebSocketConnector; use akode_websocket_client::WebSocketConnector;
use http::HeaderMap; use http::HeaderMap;
use std::sync::Arc; use std::sync::Arc;
use std::sync::OnceLock; use std::sync::OnceLock;

View File

@@ -0,0 +1,324 @@
use crate::auth::SharedAuthProvider;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use crate::search::SearchRequest;
use crate::search::SearchResponse;
use akode_client::HttpTransport;
use akode_client::RequestTelemetry;
use http::HeaderMap;
use http::Method;
use serde_json::to_value;
use std::sync::Arc;
/// The provider-relative endpoint for standalone web search.
const SEARCH_ENDPOINT: &str = "alpha/search";
pub struct SearchClient<T: HttpTransport> {
session: EndpointSession<T>,
}
impl<T: HttpTransport> SearchClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
}
}
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
Self {
session: self.session.with_request_telemetry(request),
}
}
pub async fn search(
&self,
request: &SearchRequest,
extra_headers: HeaderMap,
) -> Result<SearchResponse, ApiError> {
let body = to_value(request)
.map_err(|e| ApiError::Stream(format!("failed to encode search request: {e}")))?;
let resp = self
.session
.execute(Method::POST, SEARCH_ENDPOINT, extra_headers, Some(body))
.await?;
serde_json::from_slice(&resp.body)
.map_err(|e| ApiError::Stream(format!("failed to decode search response: {e}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::AuthProvider;
use crate::provider::RetryConfig;
use crate::search::AllowedCaller;
use crate::search::ApproximateLocation;
use crate::search::ExternalWebAccess;
use crate::search::LocationType;
use crate::search::OpenOperation;
use crate::search::SearchCommands;
use crate::search::SearchContextSize;
use crate::search::SearchFilters;
use crate::search::SearchImageSettings;
use crate::search::SearchInput;
use crate::search::SearchQuery;
use crate::search::SearchSettings;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use akode_protocol::ResponseItemId;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ImageReference;
use akode_protocol::models::ResponseItem;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Mutex;
use std::time::Duration;
#[derive(Clone, Default)]
struct DummyAuth;
impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
Ok(())
}
}
#[derive(Clone)]
struct CapturingTransport {
last_request: Arc<Mutex<Option<Request>>>,
response_body: Arc<Vec<u8>>,
}
impl CapturingTransport {
fn new(response_body: Vec<u8>) -> Self {
Self {
last_request: Arc::new(Mutex::new(None)),
response_body: Arc::new(response_body),
}
}
}
impl HttpTransport for CapturingTransport {
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
*self.last_request.lock().expect("lock request store") = Some(req);
Ok(Response {
status: StatusCode::OK,
headers: HeaderMap::new(),
body: self.response_body.as_ref().clone().into(),
})
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
fn provider() -> Provider {
Provider {
name: "test".to_string(),
base_url: "https://example.com/v1".to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
retry_5xx: true,
retry_transport: true,
},
stream_idle_timeout: Duration::from_secs(1),
}
}
#[tokio::test]
async fn search_posts_typed_request_and_parses_output() {
let transport = CapturingTransport::new(
serde_json::to_vec(&json!({
"encrypted_output": "ciphertext",
"output": "search result",
"results": [{
"type": "text_result",
"ref_id": "turn0search0",
"url": "https://example.com/result",
"future_field": {"preserved": true},
}],
}))
.expect("serialize response"),
);
let client = SearchClient::new(transport.clone(), provider(), Arc::new(DummyAuth));
let response = client
.search(
&SearchRequest {
id: "search-session".to_string(),
model: "gpt-test".to_string(),
reasoning: None,
input: Some(SearchInput::Items(vec![ResponseItem::Message {
status: None,
encrypted_content: None,
id: Some(ResponseItemId::with_suffix("msg", "search")),
role: "user".to_string(),
content: vec![
ContentItem::InputText {
text: "find this".to_string(),
},
ContentItem::InputImage {
image: ImageReference::Inline {
image_url: "https://example.com/image.png".to_string(),
},
detail: None,
},
],
phase: None,
internal_chat_message_metadata_passthrough: None,
}])),
commands: Some(SearchCommands {
search_query: Some(vec![SearchQuery {
q: "OpenAI news".to_string(),
recency: Some(7),
domains: Some(vec!["openai.com".to_string()]),
}]),
open: Some(vec![OpenOperation {
ref_id: "https://openai.com".to_string(),
lineno: Some(12),
}]),
..Default::default()
}),
settings: Some(SearchSettings {
user_location: Some(ApproximateLocation {
r#type: LocationType::Approximate,
country: Some("US".to_string()),
region: None,
city: Some("San Francisco".to_string()),
timezone: None,
}),
search_context_size: Some(SearchContextSize::Low),
filters: Some(SearchFilters {
allowed_domains: Some(vec!["openai.com".to_string()]),
blocked_domains: Some(vec!["example.com".to_string()]),
}),
image_settings: Some(SearchImageSettings {
max_results: Some(4),
caption: Some(true),
}),
allowed_callers: Some(vec![AllowedCaller::Direct]),
external_web_access: Some(ExternalWebAccess::Boolean(true)),
}),
max_output_tokens: Some(2500),
},
HeaderMap::new(),
)
.await
.expect("search request should succeed");
assert_eq!(
response,
SearchResponse {
encrypted_output: Some("ciphertext".to_string()),
output: "search result".to_string(),
results: Some(vec![json!({
"type": "text_result",
"ref_id": "turn0search0",
"url": "https://example.com/result",
"future_field": {"preserved": true},
})]),
}
);
let request = transport
.last_request
.lock()
.expect("lock request store")
.clone()
.expect("request should be captured");
let body = request
.body
.as_ref()
.and_then(RequestBody::json)
.expect("request body should be JSON");
assert_eq!(
body,
&json!({
"id": "search-session",
"model": "gpt-test",
"input": [{
"type": "message",
"id": "msg_search",
"role": "user",
"content": [
{"type": "input_text", "text": "find this"},
{
"type": "input_image",
"image_url": "https://example.com/image.png"
}
]
}],
"commands": {
"search_query": [{
"q": "OpenAI news",
"recency": 7,
"domains": ["openai.com"]
}],
"open": [{"ref_id": "https://openai.com", "lineno": 12}]
},
"settings": {
"user_location": {
"type": "approximate",
"country": "US",
"city": "San Francisco"
},
"search_context_size": "low",
"filters": {
"allowed_domains": ["openai.com"],
"blocked_domains": ["example.com"]
},
"image_settings": {"max_results": 4, "caption": true},
"allowed_callers": ["direct"],
"external_web_access": true
},
"max_output_tokens": 2500
})
);
}
#[test]
fn search_response_defaults_missing_results_for_older_endpoints() {
let response: SearchResponse = serde_json::from_value(json!({
"encrypted_output": null,
"output": "search result",
}))
.expect("response without results should deserialize");
assert_eq!(
response,
SearchResponse {
encrypted_output: None,
output: "search result".to_string(),
results: None,
}
);
}
#[test]
fn search_response_preserves_supported_empty_results() {
let response: SearchResponse = serde_json::from_value(json!({
"encrypted_output": null,
"output": "search result",
"results": [],
}))
.expect("response with empty results should deserialize");
assert_eq!(
response,
SearchResponse {
encrypted_output: None,
output: "search result".to_string(),
results: Some(Vec::new()),
}
);
}
}

View File

@@ -0,0 +1,156 @@
use crate::auth::SharedAuthProvider;
use crate::error::ApiError;
use crate::provider::Provider;
use crate::telemetry::run_with_request_telemetry;
use akode_client::EncodedJsonBody;
use akode_client::HttpTransport;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::RequestTelemetry;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use http::HeaderMap;
use http::Method;
use serde_json::Value;
use std::sync::Arc;
use tracing::instrument;
pub(crate) struct EndpointSession<T: HttpTransport> {
transport: T,
provider: Provider,
auth: SharedAuthProvider,
request_telemetry: Option<Arc<dyn RequestTelemetry>>,
}
impl<T: HttpTransport> EndpointSession<T> {
pub(crate) fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
transport,
provider,
auth,
request_telemetry: None,
}
}
pub(crate) fn with_request_telemetry(
mut self,
request: Option<Arc<dyn RequestTelemetry>>,
) -> Self {
self.request_telemetry = request;
self
}
pub(crate) fn provider(&self) -> &Provider {
&self.provider
}
fn make_request(
&self,
method: &Method,
path: &str,
extra_headers: &HeaderMap,
body: Option<&RequestBody>,
) -> Request {
let mut req = self.provider.build_request(method.clone(), path);
req.headers.extend(extra_headers.clone());
if let Some(body) = body {
req.body = Some(body.clone());
}
req
}
pub(crate) async fn execute(
&self,
method: Method,
path: &str,
extra_headers: HeaderMap,
body: Option<Value>,
) -> Result<Response, ApiError> {
self.execute_with(method, path, extra_headers, body, |_| {})
.await
}
#[instrument(
name = "endpoint_session.execute_with",
level = "info",
skip_all,
fields(http.method = %method, api.path = path)
)]
pub(crate) async fn execute_with<C>(
&self,
method: Method,
path: &str,
extra_headers: HeaderMap,
body: Option<Value>,
configure: C,
) -> Result<Response, ApiError>
where
C: Fn(&mut Request),
{
let body = body.map(RequestBody::Json);
let make_request = || {
let mut req = self.make_request(&method, path, &extra_headers, body.as_ref());
configure(&mut req);
req
};
let response = run_with_request_telemetry(
self.provider.retry.to_policy(),
self.request_telemetry.clone(),
make_request,
|req| {
let auth = self.auth.clone();
let transport = &self.transport;
async move {
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
transport.execute(req).await
}
},
)
.await?;
Ok(response)
}
#[instrument(
name = "endpoint_session.stream_encoded_json_with",
level = "info",
skip_all,
fields(http.method = %method, api.path = path)
)]
pub(crate) async fn stream_encoded_json_with<C>(
&self,
method: Method,
path: &str,
extra_headers: HeaderMap,
body: Option<EncodedJsonBody>,
configure: C,
) -> Result<StreamResponse, ApiError>
where
C: Fn(&mut Request),
{
let body = body.map(RequestBody::EncodedJson);
let mut request = self.make_request(&method, path, &extra_headers, body.as_ref());
configure(&mut request);
let request = request.into_prepared().map_err(TransportError::Build)?;
let make_request = || request.clone();
let stream = run_with_request_telemetry(
self.provider.retry.to_policy(),
self.request_telemetry.clone(),
make_request,
|req| {
let auth = self.auth.clone();
let transport = &self.transport;
async move {
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
transport.stream(req).await
}
},
)
.await?;
Ok(stream)
}
}

View File

@@ -0,0 +1,197 @@
use crate::rate_limits::RateLimitError;
use akode_client::TransportError;
use akode_http_client::RetryAfter;
use akode_protocol::error::ResponseIncompleteError;
use akode_protocol::protocol::MisalignmentErrorDetails;
use http::StatusCode;
use serde_json::Value;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ApiError {
#[error(transparent)]
Transport(#[from] TransportError),
#[error("api error {status}: {message}")]
Api { status: StatusCode, message: String },
#[error("stream error: {0}")]
Stream(String),
#[error("stream error: Incomplete response returned, reason: content_filter")]
ContentFilter,
#[error(transparent)]
ResponseIncomplete(Box<ResponseIncompleteError>),
#[error("context window exceeded")]
ContextWindowExceeded,
#[error("quota exceeded")]
QuotaExceeded,
#[error("usage not included")]
UsageNotIncluded,
#[error("session budget exceeded")]
SessionBudgetExceeded,
#[error("retryable error: {message}")]
Retryable {
message: String,
retry_after: Option<RetryAfter>,
},
#[error("rate limit exceeded: {message}")]
RateLimitExceeded {
message: String,
retry_after: Option<RetryAfter>,
},
#[error("rate limit: {0}")]
RateLimit(String),
#[error("invalid request: {message}")]
InvalidRequest { message: String },
#[error("{message}")]
InvalidAudioInput {
message: String,
/// True when the provider rejected an individual clip, independent of request size.
per_recording: bool,
},
#[error("{message}")]
ModelNotFound {
message: String,
status: Option<StatusCode>,
},
#[error("invalid prompt: {message}")]
InvalidPrompt { message: String },
#[error("cyber policy: {message}")]
CyberPolicy { message: String },
#[error("bio policy: {message}")]
BioPolicy { message: String },
#[error("misalignment policy violation: {message}")]
MisalignmentPolicyViolation {
message: String,
misalignment: Option<MisalignmentErrorDetails>,
},
#[error("Flex capacity unavailable.")]
FlexUnavailable,
/// Server-confirmed capacity failure on a policy-restricted route.
#[error("policy-restricted capacity unavailable")]
PolicyCapacityUnavailable { retry_after: Option<RetryAfter> },
#[error("server overloaded")]
ServerOverloaded { retry_after: Option<RetryAfter> },
}
impl From<RateLimitError> for ApiError {
fn from(err: RateLimitError) -> Self {
Self::RateLimit(err.to_string())
}
}
pub(crate) fn parse_terminal_provider_error(
error: Option<&Value>,
status: Option<StatusCode>,
) -> Option<ApiError> {
let error = error?;
if let Some(message) = context_overflow_message(error) {
return Some(ApiError::InvalidRequest { message });
}
let code = error.get("code")?.as_str()?;
match (code, status) {
("budget_reached", None | Some(StatusCode::BAD_REQUEST)) => {
Some(ApiError::SessionBudgetExceeded)
}
(
"audio_too_large"
| "audio_too_short"
| "invalid_audio"
| "invalid_audio_data"
| "invalid_audio_format"
| "missing_audio_sample_rate",
None | Some(StatusCode::BAD_REQUEST),
) => Some(ApiError::InvalidAudioInput {
per_recording: code != "audio_too_large",
message: error
.get("message")
.and_then(Value::as_str)
.filter(|message| !message.trim().is_empty())
.unwrap_or("Invalid audio input.")
.to_owned(),
}),
("flex_unavailable", None | Some(StatusCode::TOO_MANY_REQUESTS)) => {
Some(ApiError::FlexUnavailable)
}
(
"model_not_found",
None | Some(StatusCode::BAD_REQUEST | StatusCode::FORBIDDEN | StatusCode::NOT_FOUND),
) => Some(ApiError::ModelNotFound {
message: error
.get("message")
.and_then(Value::as_str)
.filter(|message| !message.trim().is_empty())
.unwrap_or(code)
.to_owned(),
status,
}),
_ => None,
}
}
/// Returns the server's own message from a provider `error` value (an object with
/// `message`, or a bare string), when it has one.
pub(crate) fn provider_error_message(error: &Value) -> Option<String> {
let message = match error {
Value::String(message) => message.as_str(),
Value::Object(_) => error.get("message").and_then(Value::as_str)?,
_ => return None,
};
let message = message.trim();
(!message.is_empty()).then(|| message.to_string())
}
/// Builds the error for a provider `error` value seen in the stream, keeping the server's
/// message instead of a generic "stream closed" error.
pub(crate) fn provider_stream_error(error: &Value) -> Option<ApiError> {
if let Some(error) = parse_terminal_provider_error(Some(error), /*status*/ None) {
return Some(error);
}
provider_error_message(error)
.map(|message| ApiError::Stream(format!("errore del server: {message}")))
}
/// Recognizes context-overflow errors from OpenAI-compatible servers (llama.cpp, vLLM, ...)
/// and turns them into an actionable Italian message. The OpenAI `context_length_exceeded`
/// code keeps its dedicated handling (auto-compaction) and is not matched here.
pub(crate) fn context_overflow_message(error: &Value) -> Option<String> {
if error.get("code").and_then(Value::as_str) == Some("context_length_exceeded") {
return None;
}
let is_overflow_type =
error.get("type").and_then(Value::as_str) == Some("exceed_context_size_error");
let message = provider_error_message(error).unwrap_or_default();
let lower = message.to_ascii_lowercase();
let mentions_overflow = [
"exceeds the available context size",
"maximum context length",
"context length exceeded",
"exceeds the context size",
"context size exceeded",
]
.iter()
.any(|needle| lower.contains(needle));
if !is_overflow_type && !mentions_overflow {
return None;
}
let n_ctx = error
.get("n_ctx")
.and_then(Value::as_i64)
.or_else(|| first_number(&message));
Some(match n_ctx {
Some(n_ctx) => format!(
"Il server ha superato il contesto ({n_ctx} token): aumenta il contesto del modello sul server e in /endpoint."
),
None => "Il server ha superato il contesto: aumenta il contesto del modello sul server e in /endpoint.".to_string(),
})
}
fn first_number(text: &str) -> Option<i64> {
text.split(|c: char| !c.is_ascii_digit())
.find(|part| !part.is_empty())
.and_then(|part| part.parse().ok())
}
impl From<crate::AuthError> for ApiError {
fn from(error: crate::AuthError) -> Self {
Self::Transport(error.into())
}
}

View File

@@ -0,0 +1,117 @@
pub(crate) mod api_bridge;
pub(crate) mod auth;
pub(crate) mod common;
pub(crate) mod endpoint;
pub(crate) mod error;
mod guardian_assessment;
pub(crate) mod provider;
pub(crate) mod rate_limits;
pub(crate) mod requests;
mod responses_headers;
pub(crate) mod safety_buffering;
pub(crate) mod search;
pub(crate) mod sse;
pub(crate) mod telemetry;
/// Path of the Responses endpoint, relative to a provider's base URL.
pub const RESPONSES_PATH: &str = "/responses";
pub use crate::requests::headers::build_session_headers;
pub use akode_client::RequestTelemetry;
pub use akode_client::ReqwestTransport;
pub use akode_client::TransportError;
pub use crate::api_bridge::map_api_error;
pub use crate::auth::AuthError;
pub use crate::auth::AuthHeaderTelemetry;
pub use crate::auth::AuthHeadersFuture;
pub use crate::auth::AuthProvider;
pub use crate::auth::AuthProviderFuture;
pub use crate::auth::AuthRefreshFuture;
pub use crate::auth::SharedAuthProvider;
pub use crate::auth::auth_header_telemetry;
pub use crate::common::MemorySummarizeInput;
pub use crate::common::MemorySummarizeOutput;
pub use crate::common::OpenAiVerbosity;
pub use crate::common::PromptCacheOptions;
pub use crate::common::RawMemory;
pub use crate::common::RawMemoryMetadata;
pub use crate::common::Reasoning;
pub use crate::common::ReasoningContext;
pub use crate::common::ReasoningSummaryDelivery;
pub use crate::common::ResponseCreateWsRequest;
pub use crate::common::ResponseEvent;
pub use crate::common::ResponseId;
pub use crate::common::ResponseInterrupt;
pub use crate::common::ResponseStream;
pub use crate::common::ResponsesApiRequest;
pub use crate::common::ResponsesApiTools;
pub use crate::common::ResponsesWsRequest;
pub use crate::common::SamplingParams;
pub use crate::common::StreamOptions;
pub use crate::common::TextControls;
pub use crate::common::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY;
pub use crate::common::WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY;
pub use crate::common::create_text_param_for_request;
pub use crate::common::response_create_client_metadata;
pub use crate::endpoint::MemoriesClient;
pub use crate::endpoint::ModelsClient;
pub use crate::endpoint::RealtimeCallClient;
pub use crate::endpoint::RealtimeCallResponse;
pub use crate::endpoint::RealtimeContextAppendChannel;
pub use crate::endpoint::RealtimeEventParser;
pub use crate::endpoint::RealtimeOutputModality;
pub use crate::endpoint::RealtimeSessionConfig;
pub use crate::endpoint::RealtimeSessionMode;
pub use crate::endpoint::RealtimeTranscriptState;
pub use crate::endpoint::RealtimeWebsocketClient;
pub use crate::endpoint::RealtimeWebsocketConnection;
pub use crate::endpoint::RealtimeWebsocketEvents;
pub use crate::endpoint::RealtimeWebsocketWriter;
pub use crate::endpoint::ResponsesClient;
pub use crate::endpoint::ResponsesOptions;
pub use crate::endpoint::ResponsesWebsocketClient;
pub use crate::endpoint::ResponsesWebsocketClose;
pub use crate::endpoint::ResponsesWebsocketConnection;
pub use crate::endpoint::ResponsesWebsocketProbe;
pub use crate::endpoint::ResponsesWebsocketProbeError;
pub use crate::endpoint::ResponsesWebsocketProbeFailureStage;
pub use crate::endpoint::SearchClient;
pub use crate::endpoint::session_update_session_json;
pub use crate::error::ApiError;
pub use crate::guardian_assessment::GuardianAssessment;
pub use crate::provider::Provider;
pub use crate::provider::RetryConfig;
pub use crate::provider::is_azure_responses_provider;
pub use crate::requests::Compression;
pub use crate::search::AllowedCaller;
pub use crate::search::ApproximateLocation;
pub use crate::search::ClickOperation;
pub use crate::search::ExternalWebAccess;
pub use crate::search::ExternalWebAccessMode;
pub use crate::search::FinanceAssetType;
pub use crate::search::FinanceOperation;
pub use crate::search::FindOperation;
pub use crate::search::LocationType;
pub use crate::search::OpenOperation;
pub use crate::search::ScreenshotOperation;
pub use crate::search::SearchCommands;
pub use crate::search::SearchContextSize;
pub use crate::search::SearchFilters;
pub use crate::search::SearchImageSettings;
pub use crate::search::SearchInput;
pub use crate::search::SearchQuery;
pub use crate::search::SearchRequest;
pub use crate::search::SearchResponse;
pub use crate::search::SearchResponseLength;
pub use crate::search::SearchSettings;
pub use crate::search::SportsFunction;
pub use crate::search::SportsLeague;
pub use crate::search::SportsOperation;
pub use crate::search::SportsToolName;
pub use crate::search::TimeOperation;
pub use crate::search::WeatherOperation;
pub use crate::telemetry::SseTelemetry;
pub use crate::telemetry::WebsocketTelemetry;
pub use akode_protocol::protocol::RealtimeAudioFrame;
pub use akode_protocol::protocol::RealtimeEvent;

View File

@@ -0,0 +1,67 @@
pub use akode_client::Provider;
pub use akode_client::RetryConfig;
pub fn is_azure_responses_provider(name: &str, base_url: Option<&str>) -> bool {
if name.eq_ignore_ascii_case("azure") {
true
} else if let Some(base_url) = base_url {
matches_azure_responses_base_url(base_url)
} else {
false
}
}
fn matches_azure_responses_base_url(base_url: &str) -> bool {
let base_url = base_url.to_ascii_lowercase();
const AZURE_MARKERS: [&str; 6] = [
"openai.azure.",
"cognitiveservices.azure.",
"aoai.azure.",
"azure-api.",
"azurefd.",
"windows.net/openai",
];
AZURE_MARKERS.iter().any(|marker| base_url.contains(marker))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_azure_responses_base_urls() {
let positive_cases = [
"https://foo.openai.azure.com/openai",
"https://foo.openai.azure.us/openai/deployments/bar",
"https://foo.cognitiveservices.azure.cn/openai",
"https://foo.aoai.azure.com/openai",
"https://foo.openai.azure-api.net/openai",
"https://foo.z01.azurefd.net/",
];
for base_url in positive_cases {
assert!(
is_azure_responses_provider("test", Some(base_url)),
"expected {base_url} to be detected as Azure"
);
}
assert!(is_azure_responses_provider(
"Azure",
Some("https://example.com")
));
let negative_cases = [
"https://api.openai.com/v1",
"https://example.com/openai",
"https://myproxy.azurewebsites.net/openai",
];
for base_url in negative_cases {
assert!(
!is_azure_responses_provider("test", Some(base_url)),
"expected {base_url} not to be detected as Azure"
);
}
}
}

View File

@@ -0,0 +1,382 @@
use akode_protocol::account::PlanType;
use akode_protocol::protocol::CreditsSnapshot;
use akode_protocol::protocol::RateLimitReachedType;
use akode_protocol::protocol::RateLimitSnapshot;
use akode_protocol::protocol::RateLimitWindow;
use http::HeaderMap;
use serde::Deserialize;
use std::collections::BTreeSet;
use std::fmt::Display;
#[derive(Debug)]
pub struct RateLimitError {
pub message: String,
}
impl Display for RateLimitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
/// Parses the default Codex rate-limit header family into a `RateLimitSnapshot`.
pub fn parse_default_rate_limit(headers: &HeaderMap) -> Option<RateLimitSnapshot> {
parse_rate_limit_for_limit(headers, /*limit_id*/ None)
}
/// Parses all known rate-limit header families into update records keyed by limit id.
pub fn parse_all_rate_limits(headers: &HeaderMap) -> Vec<RateLimitSnapshot> {
let mut snapshots = Vec::new();
if let Some(snapshot) = parse_default_rate_limit(headers) {
snapshots.push(snapshot);
}
let mut limit_ids: BTreeSet<String> = BTreeSet::new();
for name in headers.keys() {
let header_name = name.as_str().to_ascii_lowercase();
if let Some(limit_id) = header_name_to_limit_id(&header_name)
&& limit_id != "codex"
{
limit_ids.insert(limit_id);
}
}
snapshots.extend(limit_ids.into_iter().filter_map(|limit_id| {
let snapshot = parse_rate_limit_for_limit(headers, Some(limit_id.as_str()))?;
has_rate_limit_data(&snapshot).then_some(snapshot)
}));
snapshots
}
/// Parses rate-limit headers for the provided limit id.
///
/// `limit_id` should match the server-provided metered limit id (e.g. `codex`,
/// `codex_other`). When omitted, this defaults to the legacy `codex` header family.
pub fn parse_rate_limit_for_limit(
headers: &HeaderMap,
limit_id: Option<&str>,
) -> Option<RateLimitSnapshot> {
let normalized_limit = limit_id
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("codex")
.to_ascii_lowercase()
.replace('_', "-");
let prefix = format!("x-{normalized_limit}");
let primary = parse_rate_limit_window(
headers,
&format!("{prefix}-primary-used-percent"),
&format!("{prefix}-primary-window-minutes"),
&format!("{prefix}-primary-reset-at"),
);
let secondary = parse_rate_limit_window(
headers,
&format!("{prefix}-secondary-used-percent"),
&format!("{prefix}-secondary-window-minutes"),
&format!("{prefix}-secondary-reset-at"),
);
let normalized_limit_id = normalize_limit_id(normalized_limit);
let credits = parse_credits_snapshot(headers);
let limit_name_header = format!("{prefix}-limit-name");
let parsed_limit_name = parse_header_str(headers, &limit_name_header)
.map(str::trim)
.filter(|name| !name.is_empty())
.map(std::string::ToString::to_string);
Some(RateLimitSnapshot {
limit_id: Some(normalized_limit_id),
limit_name: parsed_limit_name,
normal_model_slug: None,
primary,
secondary,
credits,
individual_limit: None,
spend_control_reached: None,
plan_type: None,
rate_limit_reached_type: None,
})
}
#[derive(Debug, Deserialize)]
struct RateLimitEventWindow {
used_percent: f64,
window_minutes: Option<i64>,
reset_at: Option<i64>,
}
#[derive(Debug, Deserialize)]
struct RateLimitEventDetails {
primary: Option<RateLimitEventWindow>,
secondary: Option<RateLimitEventWindow>,
}
#[derive(Debug, Deserialize)]
struct RateLimitEventCredits {
has_credits: bool,
unlimited: bool,
balance: Option<String>,
}
#[derive(Debug, Deserialize)]
struct RateLimitEvent {
#[serde(rename = "type")]
kind: String,
plan_type: Option<PlanType>,
rate_limits: Option<RateLimitEventDetails>,
credits: Option<RateLimitEventCredits>,
metered_limit_name: Option<String>,
limit_name: Option<String>,
}
pub fn parse_rate_limit_event(payload: &str) -> Option<RateLimitSnapshot> {
let event: RateLimitEvent = serde_json::from_str(payload).ok()?;
if event.kind != "codex.rate_limits" {
return None;
}
let (primary, secondary) = if let Some(details) = event.rate_limits.as_ref() {
(
map_event_window(details.primary.as_ref()),
map_event_window(details.secondary.as_ref()),
)
} else {
(None, None)
};
let credits = event.credits.map(|credits| CreditsSnapshot {
has_credits: credits.has_credits,
unlimited: credits.unlimited,
balance: credits.balance,
});
let limit_id = event
.metered_limit_name
.or(event.limit_name)
.map(normalize_limit_id);
Some(RateLimitSnapshot {
limit_id: Some(limit_id.unwrap_or_else(|| "codex".to_string())),
limit_name: None,
normal_model_slug: None,
primary,
secondary,
credits,
individual_limit: None,
spend_control_reached: None,
plan_type: event.plan_type,
rate_limit_reached_type: None,
})
}
fn map_event_window(window: Option<&RateLimitEventWindow>) -> Option<RateLimitWindow> {
let window = window?;
Some(RateLimitWindow {
used_percent: window.used_percent,
window_minutes: window.window_minutes,
resets_at: window.reset_at,
})
}
/// Parses the bespoke Codex rate-limit headers into a `RateLimitSnapshot`.
pub fn parse_promo_message(headers: &HeaderMap) -> Option<String> {
parse_header_str(headers, "x-codex-promo-message")
.map(str::trim)
.filter(|value| !value.is_empty())
.map(std::string::ToString::to_string)
}
pub(crate) fn parse_rate_limit_reached_type(headers: &HeaderMap) -> Option<RateLimitReachedType> {
parse_header_str(headers, "x-codex-rate-limit-reached-type")?
.trim()
.parse()
.ok()
}
fn parse_rate_limit_window(
headers: &HeaderMap,
used_percent_header: &str,
window_minutes_header: &str,
resets_at_header: &str,
) -> Option<RateLimitWindow> {
let used_percent: Option<f64> = parse_header_f64(headers, used_percent_header);
used_percent.and_then(|used_percent| {
let window_minutes = parse_header_i64(headers, window_minutes_header);
let resets_at = parse_header_i64(headers, resets_at_header);
let has_data = used_percent != 0.0
|| window_minutes.is_some_and(|minutes| minutes != 0)
|| resets_at.is_some();
has_data.then_some(RateLimitWindow {
used_percent,
window_minutes,
resets_at,
})
})
}
fn parse_credits_snapshot(headers: &HeaderMap) -> Option<CreditsSnapshot> {
let has_credits = parse_header_bool(headers, "x-codex-credits-has-credits")?;
let unlimited = parse_header_bool(headers, "x-codex-credits-unlimited")?;
let balance = parse_header_str(headers, "x-codex-credits-balance")
.map(str::trim)
.filter(|value| !value.is_empty())
.map(std::string::ToString::to_string);
Some(CreditsSnapshot {
has_credits,
unlimited,
balance,
})
}
fn parse_header_f64(headers: &HeaderMap, name: &str) -> Option<f64> {
parse_header_str(headers, name)?
.parse::<f64>()
.ok()
.filter(|v| v.is_finite())
}
fn parse_header_i64(headers: &HeaderMap, name: &str) -> Option<i64> {
parse_header_str(headers, name)?.parse::<i64>().ok()
}
fn parse_header_bool(headers: &HeaderMap, name: &str) -> Option<bool> {
let raw = parse_header_str(headers, name)?;
if raw.eq_ignore_ascii_case("true") || raw == "1" {
Some(true)
} else if raw.eq_ignore_ascii_case("false") || raw == "0" {
Some(false)
} else {
None
}
}
fn parse_header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers.get(name)?.to_str().ok()
}
fn has_rate_limit_data(snapshot: &RateLimitSnapshot) -> bool {
snapshot.primary.is_some() || snapshot.secondary.is_some() || snapshot.credits.is_some()
}
fn header_name_to_limit_id(header_name: &str) -> Option<String> {
let suffix = "-primary-used-percent";
let prefix = header_name.strip_suffix(suffix)?;
let limit = prefix.strip_prefix("x-")?;
Some(normalize_limit_id(limit.to_string()))
}
fn normalize_limit_id(name: impl Into<String>) -> String {
name.into().trim().to_ascii_lowercase().replace('-', "_")
}
#[cfg(test)]
mod tests {
use super::*;
use http::HeaderValue;
use pretty_assertions::assert_eq;
#[test]
fn parse_rate_limit_for_limit_defaults_to_codex_headers() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-primary-used-percent",
HeaderValue::from_static("12.5"),
);
headers.insert(
"x-codex-primary-window-minutes",
HeaderValue::from_static("60"),
);
headers.insert(
"x-codex-primary-reset-at",
HeaderValue::from_static("1704069000"),
);
let snapshot = parse_rate_limit_for_limit(&headers, /*limit_id*/ None).expect("snapshot");
assert_eq!(snapshot.limit_id.as_deref(), Some("codex"));
assert_eq!(snapshot.limit_name, None);
let primary = snapshot.primary.expect("primary");
assert_eq!(primary.used_percent, 12.5);
assert_eq!(primary.window_minutes, Some(60));
assert_eq!(primary.resets_at, Some(1704069000));
}
#[test]
fn parse_rate_limit_for_limit_reads_secondary_headers() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-secondary-primary-used-percent",
HeaderValue::from_static("80"),
);
headers.insert(
"x-codex-secondary-primary-window-minutes",
HeaderValue::from_static("1440"),
);
headers.insert(
"x-codex-secondary-primary-reset-at",
HeaderValue::from_static("1704074400"),
);
let snapshot =
parse_rate_limit_for_limit(&headers, Some("codex_secondary")).expect("snapshot");
assert_eq!(snapshot.limit_id.as_deref(), Some("codex_secondary"));
assert_eq!(snapshot.limit_name, None);
let primary = snapshot.primary.expect("primary");
assert_eq!(primary.used_percent, 80.0);
assert_eq!(primary.window_minutes, Some(1440));
assert_eq!(primary.resets_at, Some(1704074400));
assert_eq!(snapshot.secondary, None);
}
#[test]
fn parse_rate_limit_for_limit_prefers_limit_name_header() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-bengalfox-primary-used-percent",
HeaderValue::from_static("80"),
);
headers.insert(
"x-codex-bengalfox-limit-name",
HeaderValue::from_static("gpt-5.2-codex-sonic"),
);
let snapshot =
parse_rate_limit_for_limit(&headers, Some("codex_bengalfox")).expect("snapshot");
assert_eq!(snapshot.limit_id.as_deref(), Some("codex_bengalfox"));
assert_eq!(snapshot.limit_name.as_deref(), Some("gpt-5.2-codex-sonic"));
}
#[test]
fn parse_all_rate_limits_reads_all_limit_families() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-primary-used-percent",
HeaderValue::from_static("12.5"),
);
headers.insert(
"x-codex-secondary-primary-used-percent",
HeaderValue::from_static("80"),
);
let updates = parse_all_rate_limits(&headers);
assert_eq!(updates.len(), 2);
assert_eq!(updates[0].limit_id.as_deref(), Some("codex"));
assert_eq!(updates[1].limit_id.as_deref(), Some("codex_secondary"));
assert_eq!(updates[0].limit_name, None);
assert_eq!(updates[1].limit_name, None);
}
#[test]
fn parse_all_rate_limits_includes_default_codex_snapshot() {
let headers = HeaderMap::new();
let updates = parse_all_rate_limits(&headers);
assert_eq!(updates.len(), 1);
assert_eq!(updates[0].limit_id.as_deref(), Some("codex"));
assert_eq!(updates[0].limit_name, None);
assert_eq!(updates[0].primary, None);
assert_eq!(updates[0].secondary, None);
assert_eq!(updates[0].credits, None);
}
}

View File

@@ -0,0 +1,40 @@
use akode_protocol::protocol::SessionSource;
use http::HeaderMap;
use http::HeaderValue;
pub fn build_session_headers(session_id: Option<String>, thread_id: Option<String>) -> HeaderMap {
let mut headers = HeaderMap::new();
if let Some(id) = session_id {
insert_header(&mut headers, "session-id", &id);
}
if let Some(id) = thread_id {
insert_header(&mut headers, "thread-id", &id);
}
headers
}
pub(crate) fn subagent_header(source: &Option<SessionSource>) -> Option<String> {
let SessionSource::SubAgent(sub) = source.as_ref()? else {
return None;
};
match sub {
akode_protocol::protocol::SubAgentSource::Review => Some("review".to_string()),
akode_protocol::protocol::SubAgentSource::Compact => Some("compact".to_string()),
akode_protocol::protocol::SubAgentSource::MemoryConsolidation => {
Some("memory_consolidation".to_string())
}
akode_protocol::protocol::SubAgentSource::ThreadSpawn { .. } => {
Some("collab_spawn".to_string())
}
akode_protocol::protocol::SubAgentSource::Other(label) => Some(label.clone()),
}
}
pub(crate) fn insert_header(headers: &mut HeaderMap, name: &str, value: &str) {
if let (Ok(header_name), Ok(header_value)) = (
name.parse::<http::HeaderName>(),
HeaderValue::from_str(value),
) {
headers.insert(header_name, header_value);
}
}

View File

@@ -0,0 +1,308 @@
use crate::common::Reasoning;
use akode_protocol::models::ResponseItem;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct SearchRequest {
pub id: String,
pub model: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning: Option<Reasoning>,
#[serde(skip_serializing_if = "Option::is_none")]
pub input: Option<SearchInput>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commands: Option<SearchCommands>,
#[serde(skip_serializing_if = "Option::is_none")]
pub settings: Option<SearchSettings>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u64>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(untagged)]
pub enum SearchInput {
Text(String),
Items(Vec<ResponseItem>),
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, JsonSchema)]
pub struct SearchCommands {
/// Query the internet search engine for a given list of queries.
#[serde(skip_serializing_if = "Option::is_none")]
pub search_query: Option<Vec<SearchQuery>>,
/// Search for scientific papers. Open relevant papers and cite the primary sources you use.
#[serde(skip_serializing_if = "Option::is_none")]
pub literature_search_query: Option<Vec<SearchQuery>>,
/// Query the image search engine for a given list of queries.
#[serde(skip_serializing_if = "Option::is_none")]
pub image_query: Option<Vec<SearchQuery>>,
/// Open pages by reference id or URL.
#[serde(skip_serializing_if = "Option::is_none")]
pub open: Option<Vec<OpenOperation>>,
/// Open links from previously opened pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub click: Option<Vec<ClickOperation>>,
/// Find text patterns in pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub find: Option<Vec<FindOperation>>,
/// Take screenshots of PDF pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub screenshot: Option<Vec<ScreenshotOperation>>,
/// Look up prices for the given stock symbols.
#[serde(skip_serializing_if = "Option::is_none")]
pub finance: Option<Vec<FinanceOperation>>,
/// Look up weather forecasts.
#[serde(skip_serializing_if = "Option::is_none")]
pub weather: Option<Vec<WeatherOperation>>,
/// Look up sports schedules and standings.
#[serde(skip_serializing_if = "Option::is_none")]
pub sports: Option<Vec<SportsOperation>>,
/// Get time for the given UTC offsets.
#[serde(skip_serializing_if = "Option::is_none")]
pub time: Option<Vec<TimeOperation>>,
/// Set the length of the response to be returned.
#[serde(skip_serializing_if = "Option::is_none")]
pub response_length: Option<SearchResponseLength>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct SearchQuery {
/// Search query.
pub q: String,
/// Whether to filter by recency, as a number of recent days.
#[serde(skip_serializing_if = "Option::is_none")]
pub recency: Option<u64>,
/// Whether to filter by a specific list of domains.
#[serde(skip_serializing_if = "Option::is_none")]
pub domains: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct OpenOperation {
/// Reference id or URL to open.
pub ref_id: String,
/// Line number to position the page at.
#[serde(skip_serializing_if = "Option::is_none")]
pub lineno: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct ClickOperation {
/// Reference id containing the numbered link.
pub ref_id: String,
/// Numbered link id to open.
pub id: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct FindOperation {
/// Reference id or URL to search within.
pub ref_id: String,
/// Text pattern to find.
pub pattern: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct ScreenshotOperation {
/// Reference id or URL to screenshot.
pub ref_id: String,
/// Zero-indexed PDF page number.
pub pageno: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct FinanceOperation {
/// Ticker symbol to look up.
pub ticker: String,
/// Asset type to look up.
pub r#type: FinanceAssetType,
/// ISO 3166-1 alpha-3 country code, "OTC", or "" for cryptocurrency.
#[serde(skip_serializing_if = "Option::is_none")]
pub market: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FinanceAssetType {
Equity,
Fund,
Crypto,
Index,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct WeatherOperation {
/// Location in "Country, Area, City" format.
pub location: String,
/// Start date in YYYY-MM-DD format. Defaults to today.
#[serde(skip_serializing_if = "Option::is_none")]
pub start: Option<String>,
/// Number of days to return. Defaults to 7.
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct SportsOperation {
/// Tool name for sports requests.
#[serde(skip_serializing_if = "Option::is_none")]
pub tool: Option<SportsToolName>,
/// Sports function to call.
pub r#fn: SportsFunction,
/// League to look up.
pub league: SportsLeague,
/// Team to look up, using the common 3 or 4 letter alias used in broadcasts.
#[serde(skip_serializing_if = "Option::is_none")]
pub team: Option<String>,
/// Opponent to use with `team` when narrowing the lookup.
#[serde(skip_serializing_if = "Option::is_none")]
pub opponent: Option<String>,
/// Start date in YYYY-MM-DD format.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_from: Option<String>,
/// End date in YYYY-MM-DD format.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_to: Option<String>,
/// Number of games to return.
#[serde(skip_serializing_if = "Option::is_none")]
pub num_games: Option<u64>,
/// Locale for the lookup.
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SportsToolName {
Sports,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SportsFunction {
Schedule,
Standings,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SportsLeague {
Nba,
Wnba,
Nfl,
Nhl,
Mlb,
Epl,
Ncaamb,
Ncaawb,
Ipl,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct TimeOperation {
/// UTC offset formatted like "+03:00".
pub utc_offset: String,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SearchResponseLength {
Short,
Medium,
Long,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExternalWebAccessMode {
Cached,
Indexed,
Live,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(untagged)]
pub enum ExternalWebAccess {
Boolean(bool),
Mode(ExternalWebAccessMode),
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct SearchSettings {
#[serde(skip_serializing_if = "Option::is_none")]
pub user_location: Option<ApproximateLocation>,
#[serde(skip_serializing_if = "Option::is_none")]
pub search_context_size: Option<SearchContextSize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub filters: Option<SearchFilters>,
#[serde(skip_serializing_if = "Option::is_none")]
pub image_settings: Option<SearchImageSettings>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_callers: Option<Vec<AllowedCaller>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_web_access: Option<ExternalWebAccess>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ApproximateLocation {
pub r#type: LocationType,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub timezone: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LocationType {
Approximate,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SearchContextSize {
Low,
Medium,
High,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct SearchFilters {
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_domains: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blocked_domains: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct SearchImageSettings {
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub caption: Option<bool>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AllowedCaller {
Direct,
Shell,
CodeInterpreter,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct SearchResponse {
pub encrypted_output: Option<String>,
pub output: String,
/// Structured result DTOs are passed to clients out-of-band from `output`.
/// Keep them opaque here so newer result variants remain forward-compatible.
#[serde(default)]
pub results: Option<Vec<JsonValue>>,
}

File diff suppressed because it is too large Load Diff

View File

@@ -4,8 +4,8 @@
use crate::error::ApiError; use crate::error::ApiError;
use crate::error::parse_terminal_provider_error; use crate::error::parse_terminal_provider_error;
use crate::responses_headers::json_headers_to_http_headers; use crate::responses_headers::json_headers_to_http_headers;
use codex_http_client::RetryAfter; use akode_http_client::RetryAfter;
use codex_protocol::protocol::MisalignmentErrorDetails; use akode_protocol::protocol::MisalignmentErrorDetails;
use serde::Deserialize; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
use std::time::Duration; use std::time::Duration;

View File

@@ -4,10 +4,10 @@ use super::process_responses_event;
use super::spawn_response_stream; use super::spawn_response_stream;
use crate::api_bridge::map_api_error; use crate::api_bridge::map_api_error;
use crate::common::ResponseEvent; use crate::common::ResponseEvent;
use akode_client::StreamResponse;
use akode_http_client::RetryAfter;
use akode_protocol::protocol::CodexErrorInfo;
use bytes::Bytes; use bytes::Bytes;
use codex_client::StreamResponse;
use codex_http_client::RetryAfter;
use codex_protocol::protocol::CodexErrorInfo;
use futures::StreamExt; use futures::StreamExt;
use futures::stream; use futures::stream;
use http::HeaderMap; use http::HeaderMap;
@@ -50,7 +50,7 @@ fn audio_validation_codes_map_to_non_retryable_audio_input_errors_on_all_transpo
assert_eq!(error.retry_delay(/*retry_count*/ 1), None); assert_eq!(error.retry_delay(/*retry_count*/ 1), None);
assert!(matches!( assert!(matches!(
error.details(), error.details(),
codex_protocol::error::CodexErrorDetails::InvalidAudioInput { .. } akode_protocol::error::CodexErrorDetails::InvalidAudioInput { .. }
)); ));
assert_eq!(error.to_string(), "Invalid recording."); assert_eq!(error.to_string(), "Invalid recording.");
} }

View File

@@ -0,0 +1,98 @@
use crate::error::ApiError;
use akode_client::Request;
use akode_client::RequestTelemetry;
use akode_client::Response;
use akode_client::RetryPolicy;
use akode_client::StreamResponse;
use akode_client::TransportError;
use akode_client::run_with_retry;
use http::StatusCode;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
/// Generic telemetry.
pub trait SseTelemetry: Send + Sync {
fn on_sse_poll(
&self,
result: &Result<
Option<
Result<
eventsource_stream::Event,
eventsource_stream::EventStreamError<TransportError>,
>,
>,
tokio::time::error::Elapsed,
>,
duration: Duration,
);
}
/// Telemetry for Responses WebSocket transport.
pub trait WebsocketTelemetry: Send + Sync {
/// Reports how long it took to send the request and whether the send failed.
fn on_ws_request(&self, duration: Duration, error: Option<&ApiError>, connection_reused: bool);
/// Reports the poll duration for timeouts, stream errors, end of stream,
/// and binary, close, or raw frames.
fn on_ws_receive_failure(&self, duration: Duration);
/// Reports each text frame and its poll duration. `kind` is `None` if decoding the stream event failed.
fn on_ws_text_event(&self, text: &str, kind: Option<&str>, duration: Duration);
}
pub(crate) trait WithStatus {
fn status(&self) -> StatusCode;
}
fn http_status(err: &TransportError) -> Option<StatusCode> {
match err {
TransportError::Http { status, .. } => Some(*status),
_ => None,
}
}
impl WithStatus for Response {
fn status(&self) -> StatusCode {
self.status
}
}
impl WithStatus for StreamResponse {
fn status(&self) -> StatusCode {
self.status
}
}
pub(crate) async fn run_with_request_telemetry<T, F, Fut>(
policy: RetryPolicy,
telemetry: Option<Arc<dyn RequestTelemetry>>,
make_request: impl FnMut() -> Request,
send: F,
) -> Result<T, TransportError>
where
T: WithStatus,
F: Clone + Fn(Request) -> Fut,
Fut: Future<Output = Result<T, TransportError>>,
{
// Wraps `run_with_retry` to attach per-attempt request telemetry for both
// unary and streaming HTTP calls.
run_with_retry(policy, make_request, move |req, attempt| {
let telemetry = telemetry.clone();
let send = send.clone();
async move {
let start = Instant::now();
let result = send(req).await;
if let Some(t) = telemetry.as_ref() {
let (status, err) = match &result {
Ok(resp) => (Some(resp.status()), None),
Err(err) => (http_status(err), Some(err)),
};
t.on_request(attempt, status, err, start.elapsed());
}
result
}
})
.await
}

View File

@@ -3,27 +3,27 @@ use std::sync::Arc;
use std::sync::Mutex; use std::sync::Mutex;
use std::time::Duration; use std::time::Duration;
use akode_api::ApiError;
use akode_api::AuthError;
use akode_api::AuthProvider;
use akode_api::Compression;
use akode_api::Provider;
use akode_api::ResponsesApiRequest;
use akode_api::ResponsesClient;
use akode_api::ResponsesOptions;
use akode_client::HttpTransport;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use akode_protocol::ResponseItemId;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ResponseItem;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
use anyhow::Result; use anyhow::Result;
use bytes::Bytes; use bytes::Bytes;
use codex_api::ApiError;
use codex_api::AuthError;
use codex_api::AuthProvider;
use codex_api::Compression;
use codex_api::Provider;
use codex_api::ResponsesApiRequest;
use codex_api::ResponsesClient;
use codex_api::ResponsesOptions;
use codex_client::HttpTransport;
use codex_client::Request;
use codex_client::RequestBody;
use codex_client::Response;
use codex_client::StreamResponse;
use codex_client::TransportError;
use codex_protocol::ResponseItemId;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use http::HeaderMap; use http::HeaderMap;
use http::HeaderValue; use http::HeaderValue;
use http::StatusCode; use http::StatusCode;
@@ -144,7 +144,7 @@ fn provider(name: &str) -> Provider {
base_url: "https://example.com/v1".to_string(), base_url: "https://example.com/v1".to_string(),
query_params: None, query_params: None,
headers: HeaderMap::new(), headers: HeaderMap::new(),
retry: codex_api::RetryConfig { retry: akode_api::RetryConfig {
max_attempts: 1, max_attempts: 1,
base_delay: Duration::from_millis(1), base_delay: Duration::from_millis(1),
retry_429: false, retry_429: false,
@@ -158,7 +158,7 @@ fn provider(name: &str) -> Provider {
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct FlakyTransportState { struct FlakyTransportState {
attempts: i64, attempts: i64,
requests: Vec<(RequestBody, HeaderMap, codex_client::RequestCompression)>, requests: Vec<(RequestBody, HeaderMap, akode_client::RequestCompression)>,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -186,7 +186,7 @@ impl FlakyTransport {
.attempts .attempts
} }
fn requests(&self) -> Vec<(RequestBody, HeaderMap, codex_client::RequestCompression)> { fn requests(&self) -> Vec<(RequestBody, HeaderMap, akode_client::RequestCompression)> {
self.state self.state
.lock() .lock()
.expect("flaky transport state mutex should not be poisoned") .expect("flaky transport state mutex should not be poisoned")
@@ -240,7 +240,7 @@ impl AuthProvider for FailsOnceAuth {
Ok(()) Ok(())
} }
fn apply_auth(&self, request: Request) -> codex_api::AuthProviderFuture<'_> { fn apply_auth(&self, request: Request) -> akode_api::AuthProviderFuture<'_> {
Box::pin(FailsOnceAuth::apply_auth(self, request)) Box::pin(FailsOnceAuth::apply_auth(self, request))
} }
} }
@@ -358,6 +358,7 @@ async fn responses_client_stream_request_preserves_item_ids() -> Result<()> {
prompt_cache_options: None, prompt_cache_options: None,
text: None, text: None,
client_metadata: None, client_metadata: None,
sampling: Default::default(),
}; };
let expected = serde_json::to_value(&request)?; let expected = serde_json::to_value(&request)?;
@@ -414,6 +415,7 @@ async fn responses_client_stream_request_sends_routing_fields_ahead_of_large_inp
prompt_cache_options: None, prompt_cache_options: None,
text: None, text: None,
client_metadata: None, client_metadata: None,
sampling: Default::default(),
}; };
let expected = serde_json::to_value(&request)?; let expected = serde_json::to_value(&request)?;
@@ -504,6 +506,7 @@ async fn streaming_client_retries_on_transport_error() -> Result<()> {
prompt_cache_options: None, prompt_cache_options: None,
text: None, text: None,
client_metadata: None, client_metadata: None,
sampling: Default::default(),
}; };
let client = ResponsesClient::new(transport.clone(), provider, Arc::new(NoAuth)); let client = ResponsesClient::new(transport.clone(), provider, Arc::new(NoAuth));
@@ -534,7 +537,7 @@ async fn streaming_client_retries_on_transport_error() -> Result<()> {
requests[0].1.get(http::header::CONTENT_ENCODING), requests[0].1.get(http::header::CONTENT_ENCODING),
Some(&HeaderValue::from_static("zstd")) Some(&HeaderValue::from_static("zstd"))
); );
assert_eq!(requests[0].2, codex_client::RequestCompression::None); assert_eq!(requests[0].2, akode_client::RequestCompression::None);
Ok(()) Ok(())
} }
@@ -567,7 +570,7 @@ async fn streaming_client_retries_on_transient_auth_error() -> Result<()> {
async fn streaming_client_does_not_retry_terminal_auth_errors() { async fn streaming_client_does_not_retry_terminal_auth_errors() {
for error in [ for error in [
AuthError::Build("invalid auth configuration".into()), AuthError::Build("invalid auth configuration".into()),
AuthError::Policy(codex_http_client::NetworkPolicyDenied::Revoked), AuthError::Policy(akode_http_client::NetworkPolicyDenied::Revoked),
] { ] {
let state = RecordingState::default(); let state = RecordingState::default();
let transport = RecordingTransport::new(state.clone()); let transport = RecordingTransport::new(state.clone());
@@ -629,6 +632,7 @@ async fn azure_store_sends_ids_and_headers() -> Result<()> {
prompt_cache_options: None, prompt_cache_options: None,
text: None, text: None,
client_metadata: None, client_metadata: None,
sampling: Default::default(),
}; };
let mut extra_headers = HeaderMap::new(); let mut extra_headers = HeaderMap::new();
@@ -728,13 +732,13 @@ async fn header_auth_error_prevents_sending_partial_authentication() {
struct AsyncHeaderAuth; struct AsyncHeaderAuth;
impl AuthProvider for AsyncHeaderAuth { impl AuthProvider for AsyncHeaderAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> { fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), akode_api::AuthError> {
Err(codex_api::AuthError::Build( Err(akode_api::AuthError::Build(
"authentication requires async header resolution".to_string(), "authentication requires async header resolution".to_string(),
)) ))
} }
fn apply_auth_headers(&self, mut headers: HeaderMap) -> codex_api::AuthHeadersFuture<'_> { fn apply_auth_headers(&self, mut headers: HeaderMap) -> akode_api::AuthHeadersFuture<'_> {
Box::pin(async move { Box::pin(async move {
headers.insert( headers.insert(
http::header::AUTHORIZATION, http::header::AUTHORIZATION,

View File

@@ -1,18 +1,18 @@
use codex_api::AuthProvider; use akode_api::AuthProvider;
use codex_api::ModelsClient; use akode_api::ModelsClient;
use codex_api::Provider; use akode_api::Provider;
use codex_api::RetryConfig; use akode_api::RetryConfig;
use codex_client::ReqwestTransport; use akode_client::ReqwestTransport;
use codex_http_client::HttpClientBuilder; use akode_http_client::HttpClientBuilder;
use codex_protocol::config_types::ReasoningSummary; use akode_protocol::config_types::ReasoningSummary;
use codex_protocol::openai_models::ConfigShellToolType; use akode_protocol::openai_models::ConfigShellToolType;
use codex_protocol::openai_models::ModelInfo; use akode_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelVisibility; use akode_protocol::openai_models::ModelVisibility;
use codex_protocol::openai_models::ModelsResponse; use akode_protocol::openai_models::ModelsResponse;
use codex_protocol::openai_models::ReasoningEffort; use akode_protocol::openai_models::ReasoningEffort;
use codex_protocol::openai_models::ReasoningEffortPreset; use akode_protocol::openai_models::ReasoningEffortPreset;
use codex_protocol::openai_models::TruncationPolicyConfig; use akode_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::openai_models::default_input_modalities; use akode_protocol::openai_models::default_input_modalities;
use http::HeaderMap; use http::HeaderMap;
use http::Method; use http::Method;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
@@ -28,7 +28,7 @@ use wiremock::matchers::path;
struct DummyAuth; struct DummyAuth;
impl AuthProvider for DummyAuth { impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> { fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), akode_api::AuthError> {
Ok(()) Ok(())
} }
} }

View File

@@ -3,24 +3,24 @@ use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use std::time::Duration; use std::time::Duration;
use codex_api::ApiError; use akode_api::ApiError;
use codex_api::Provider; use akode_api::Provider;
use codex_api::RealtimeAudioFrame; use akode_api::RealtimeAudioFrame;
use codex_api::RealtimeEvent; use akode_api::RealtimeEvent;
use codex_api::RealtimeEventParser; use akode_api::RealtimeEventParser;
use codex_api::RealtimeOutputModality; use akode_api::RealtimeOutputModality;
use codex_api::RealtimeSessionConfig; use akode_api::RealtimeSessionConfig;
use codex_api::RealtimeSessionMode; use akode_api::RealtimeSessionMode;
use codex_api::RealtimeTranscriptState; use akode_api::RealtimeTranscriptState;
use codex_api::RealtimeWebsocketClient; use akode_api::RealtimeWebsocketClient;
use codex_api::RetryConfig; use akode_api::RetryConfig;
use codex_http_client::HttpClientFactory; use akode_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy::ReqwestDefault; use akode_http_client::OutboundProxyPolicy::ReqwestDefault;
use codex_protocol::protocol::RealtimeHandoffRequested; use akode_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeTranscriptDelta; use akode_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDone; use akode_protocol::protocol::RealtimeTranscriptDone;
use codex_protocol::protocol::RealtimeTranscriptEntry; use akode_protocol::protocol::RealtimeTranscriptEntry;
use codex_protocol::protocol::RealtimeVoice; use akode_protocol::protocol::RealtimeVoice;
use futures::SinkExt; use futures::SinkExt;
use futures::StreamExt; use futures::StreamExt;
use http::HeaderMap; use http::HeaderMap;

View File

@@ -8,21 +8,21 @@ use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use std::time::Instant; use std::time::Instant;
use codex_api::Provider; use akode_api::Provider;
use codex_api::RealtimeEventParser; use akode_api::RealtimeEventParser;
use codex_api::RealtimeOutputModality; use akode_api::RealtimeOutputModality;
use codex_api::RealtimeSessionConfig; use akode_api::RealtimeSessionConfig;
use codex_api::RealtimeSessionMode; use akode_api::RealtimeSessionMode;
use codex_api::RealtimeWebsocketClient; use akode_api::RealtimeWebsocketClient;
use codex_api::RetryConfig; use akode_api::RetryConfig;
use codex_http_client::HttpClientFactory; use akode_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy; use akode_http_client::OutboundProxyPolicy;
use codex_protocol::protocol::RealtimeVoice; use akode_protocol::protocol::RealtimeVoice;
use http::HeaderMap; use http::HeaderMap;
use pretty_assertions::assert_eq; use pretty_assertions::assert_eq;
const ADDRESS_ENV: &str = "CODEX_TEST_REALTIME_TLS_ADDRESS"; const ADDRESS_ENV: &str = "AKODE_TEST_REALTIME_TLS_ADDRESS";
const TRUST_ENV: &str = "CODEX_TEST_REALTIME_TLS_TRUST"; const TRUST_ENV: &str = "AKODE_TEST_REALTIME_TLS_TRUST";
#[test] #[test]
fn realtime_tls_selects_system_and_custom_trust() { fn realtime_tls_selects_system_and_custom_trust() {
@@ -35,7 +35,7 @@ fn realtime_tls_selects_system_and_custom_trust() {
return; return;
} }
codex_utils_rustls_provider::ensure_rustls_crypto_provider(); akode_utils_rustls_provider::ensure_rustls_crypto_provider();
let certificate = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap(); let certificate = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
let temp = tempfile::TempDir::new().unwrap(); let temp = tempfile::TempDir::new().unwrap();
let ca = temp.path().join("ca.pem"); let ca = temp.path().join("ca.pem");
@@ -96,10 +96,10 @@ fn realtime_tls_selects_system_and_custom_trust() {
]) ])
.env(ADDRESS_ENV, format!("localhost:{}", address.port())) .env(ADDRESS_ENV, format!("localhost:{}", address.port()))
.env(TRUST_ENV, trust) .env(TRUST_ENV, trust)
.env_remove("CODEX_CA_CERTIFICATE") .env_remove("AKODE_CA_CERTIFICATE")
.env_remove("SSL_CERT_FILE"); .env_remove("SSL_CERT_FILE");
if trust == "custom" { if trust == "custom" {
child.env("CODEX_CA_CERTIFICATE", &ca).env( child.env("AKODE_CA_CERTIFICATE", &ca).env(
"SSL_CERT_FILE", "SSL_CERT_FILE",
temp.path().join("missing-lower-priority-ca.pem"), temp.path().join("missing-lower-priority-ca.pem"),
); );

Some files were not shown because too many files have changed in this diff Show More