Files
magpie/internal/sessions/calls_pi.go
T
yetone 9474eaf9cb sessions: Raft's Pi agents' sessions are listed as Raft's, with their prompts, calls and delete
Raft (slock's raft-computer) runs its agents on Pi and keeps each one's
Pi SDK session files in that agent's folder: <slock>/agents/<id>/
.pi-sessions/<ts>_<id>.jsonl, or .builtin-sessions/ for its built-in
runtime. <slock> is $SLOCK_HOME or ~/.slock (%USERPROFILE%\.slock on
Windows, the distro's ~/.slock under WSL). Read from raft-computer
1.0.14's PiDriver (buildPiSessionDir), BuiltInDriver and
resolveSlockHome, and a read-only listing of ~/.slock here.
runtime-sessions/ holds handoff notes, no sessions, and is not read.

- The Sessions page lists them as Raft's (agent "raft", in agent.Clients'
  others), titled and opened with their prompts as Pi's are.
- Their calls count on the Usage page as Raft's; calls through magpie
  stay the gateway's, as Pi's do.
- Raft's Pi uses the user's own ~/.pi/agent, so a request it sends
  through magpie reaches the gateway as Pi's under the same session id.
  sessions.GatewayKeys gives a Raft session both "raft|ID" and "pi|ID",
  so the gateway's copy is not listed twice nor counted twice (Merge,
  stats, NativeIDs, the GUI's Via).
- Delete and restore work as Pi's: the one file goes to the trash, and a
  folder beside it is left (the agent's workspace is not the session's).
  A session written in the last minutes is refused as active.
- No resume command, no carry and no trace export: Raft starts its own
  agents, and nothing outside it can resume one.
- SLOCK_HOME is passed through agentenv like the other agents' homes.

Run (at 958ad9f10 on e61e10535):
- mote (macOS): -run 'Raft|TestPi|TestDirs|TestVars|TestFolderVars' in
  sessions and agentenv: ok, and red for each break below. A full
  go test ./... was started there; at load ~300 from other sessions'
  suites it printed only magpie and internal/access (ok) before mote
  stopped answering (host down), so no full macOS record exists.
- mote (macOS), rebased on 5d24bc6cc: go test -count=1 ./internal/sessions/
  ./internal/agentenv/: ok (sessions 495s, agentenv 1.1s). agent and gui
  were not run in full on macOS.
- mote: GOOS=windows go vet of sessions, agent, agentenv, gui; GOOS=linux
  go vet of sessions, agent, agentenv: ok.
- Windows (win-run): agentenv ok; -run 'Raft|TestPi|TestDirs' in
  sessions ok. The full sessions package hit its 30m timeout after
  TestOneListing's red (#4114) and the Agy reds (#4115, #4177). agent
  and gui reds (Hermes, WorkBuddy, Lody, Qoder/Copilot plugin folders,
  Codex keychain, ClaudeDesktop language, Aside, InstallWithoutNode,
  DesktopExec, AionUi, ImportStatus, UpdateThatWontStart,
  GatewayHeldByAContainer, GatewaySessionHistoryAndCalendar): each run
  again at origin/main c1660481c on Windows and red there too, except
  TestHermesProfilesFollowMagpieModel which passed there alone; it is
  #1388's Hermes model rewrite, which this change does not reach.
- Linux (wsl-run): sessions ok, agentenv ok. agent's TestInstalledVersion,
  TestGrokInstalled, TestCursorFolderFromTheEditorIsNotTheCLI and
  TestOmpDetectedWithPiDir are red at origin/main c1660481c too (#4033,
  #3548). gui does not build there (no gtk4/webkitgtk-6.0 in the distro).

Broken by hand, each red, then restored: Raft's listing removed; the
"pi|ID" key dropped from GatewayKeys; the folder-beside check reverted to
Pi's absence; $SLOCK_HOME ignored; Raft's calls left out of piCallFiles;
NativeIDs without Raft; stats' native keys without "pi|ID".

Not tried: with real Raft. No agent on this machine has run on Pi, so
the fixtures are Pi 1.1.0's own files (testdata/pi-calls, testdata/pi)
placed in Raft's folders. The GUI was not run in a browser: no JS
changed, Raft's name and icon come from agent.Clients. Raft's icon is the
generic one.
2026-10-29 15:29:30 +08:00

187 lines
6.2 KiB
Go

package sessions
import (
"bytes"
"encoding/json"
"math"
"strings"
"time"
)
// Pi's and omp's calls (#1951, Elenoxe: Pi in WSL on its own provider
// never reached Usage). Read from the session files Sessions reads
// (pi.go, omp.go), as Pi 1.1.0 and omp 18.9.1 wrote them in a sandbox
// against a relay of their own: each model response is an assistant
// message, written as it ended, naming the provider and model that
// answered and its usage (input without the cache, output with the
// reasoning); Pi adds durationMs, omp duration and ttft:
//
// {"type":"message","id":"36b3bbef","parentId":"807675bc",
// "timestamp":"2026-10-13T07:47:34.522Z","message":{"role":"assistant",
// "content":[…],"api":"openai-completions","provider":"relay",
// "model":"deepseek-v4","usage":{"input":201,"output":30,"cacheRead":1000,
// "cacheWrite":0,"reasoning":0,"totalTokens":1231,…},"stopReason":"stop",
// "timestamp":1791877653894,"responseId":"chatcmpl-fake1","durationMs":628}}
//
// The calls outside the conversation are counted too, as Sessions counts
// them: "usage" and omp's "model_usage" entries, each naming its provider
// and model, and a compaction's, a branch summary's or a tool's result's
// usage, on the model and provider in use. A call that failed is written
// with no usage, and is none.
//
// A call made through magpie's own entry (provider "magpie", which
// internal/agent's pi.go and omp.go write, "dial" before the rename) is the
// gateway's to count: it logged the call itself, with the provider and
// account that answered.
//
// A fork (pi --fork, /fork) starts with a copy of its parent's entries, ids
// and times kept: they are the parent's calls, left out of the fork as
// Sessions leaves them (written before its header), and a call is keyed by
// its entry's id and time, so Calls counts one twice in no case.
// piCallFiles are Pi's and omp's session files, here and in WSL.
func piCallFiles() []file {
out := append(piFiles(), raftFiles()...)
out = append(out, ompFiles()...)
return append(out, wslFiles("pi", "raft", "omp")...)
}
// piGateway is whether a provider is magpie's own entry.
func piGateway(provider string) bool { return provider == "magpie" || provider == "dial" }
type piCallLine struct {
Type string `json:"type"`
ID string `json:"id"`
Timestamp string `json:"timestamp"`
Cwd string `json:"cwd"` // session
Parent string `json:"parentSession"`
Provider string `json:"provider"` // model_change, usage, model_usage
ModelID string `json:"modelId"` // model_change
Model string `json:"model"` // usage, model_usage; omp's model_change, as provider/model
Usage *piUsage `json:"usage"`
Message *struct {
Role string `json:"role"`
Provider string `json:"provider"`
Model string `json:"model"`
Usage *piUsage `json:"usage"`
DurationMs float64 `json:"durationMs"` // Pi's
Duration float64 `json:"duration"` // omp's, in milliseconds
TTFT float64 `json:"ttft"` // omp's
} `json:"message"`
}
// piCarry is what a Pi or omp session file's lines have said so far that a
// later line's call is read with: the header's cwd and, for a fork, when it
// began (what was written before is its parent's), and the provider and
// model in use. Pi and omp only append to the file, a line an entry, so a
// file that grew is read on from where the last read left off with it
// (lineCallReaders).
type piCarry struct {
Header bool
Cwd string
Since time.Time
Provider, Model string
}
// piCallsBegin starts a session file read from its start.
func piCallsBegin(st *callFile, f file) {
st.Session = strings.TrimPrefix(f.key, f.agent+":")
st.Pi = &piCarry{}
}
// piCallsKept is whether st holds what reading on needs: a disk shard
// written before the carry was kept there does not, and its file is read
// whole again once it changes.
func piCallsKept(st *callFile) bool { return st.Pi != nil }
// readPiCallLine reads one line of a Pi or omp session file.
func readPiCallLine(st *callFile, b []byte) {
if len(b) == 0 || len(b) > maxLine || !(bytes.Contains(b, piUsed) || bytes.Contains(b, piHeader) || bytes.Contains(b, piModel)) {
return
}
var l piCallLine
if json.Unmarshal(b, &l) != nil {
return
}
p := st.Pi
switch l.Type {
case "session":
if !p.Header {
p.Header, p.Cwd = true, l.Cwd
if l.Parent != "" {
p.Since, _ = time.Parse(time.RFC3339Nano, l.Timestamp)
}
}
case "model_change":
prov, id := l.Provider, l.ModelID
if id == "" {
prov, id, _ = strings.Cut(l.Model, "/")
}
if id != "" {
p.Provider, p.Model = prov, id
}
case "message":
if m := l.Message; m != nil && m.Role == "assistant" && m.Model != "" {
p.Provider, p.Model = m.Provider, m.Model
}
}
if c, ok := piCall(st, st.Agent, l, p.Provider, p.Model); ok && !c.Time.Before(p.Since) {
c.Cwd = st.str(p.Cwd)
st.Calls = append(st.Calls, c)
}
}
// piCall is an entry as a call, on the provider and model in use for the
// usage that names none.
func piCall(st *callFile, agent string, l piCallLine, provider, model string) (Call, bool) {
var u *piUsage
var millis, ttft int64
switch l.Type {
case "message":
m := l.Message
if m == nil {
return Call{}, false
}
u = m.Usage
if m.Role == "assistant" {
provider, model = m.Provider, m.Model
millis = int64(math.Round(max(m.DurationMs, m.Duration)))
ttft = int64(math.Round(m.TTFT))
}
case "usage", "model_usage":
u, provider, model = l.Usage, l.Provider, l.Model
case "compaction", "branch_summary":
u = l.Usage
default:
return Call{}, false
}
if u == nil || model == "" || piGateway(provider) {
return Call{}, false
}
if u.Input < 0 || u.Output < 0 || u.CacheRead < 0 || u.CacheWrite < 0 {
return Call{}, false
}
// the entry's time: when the call ended, as a call's Time is
at, _ := time.Parse(time.RFC3339Nano, l.Timestamp)
if at.IsZero() {
return Call{}, false
}
c := Call{
Agent: agent,
Time: at,
Session: st.Session,
Model: st.str(model),
Upstream: st.str(provider),
Tokens: u.tokens(),
Millis: max(millis, 0),
TTFT: max(ttft, 0),
}
if c.Tokens.zero() {
return Call{}, false
}
if l.ID != "" {
c.Msg = st.str(agent + ":" + l.ID + ":" + l.Timestamp)
}
return c, true
}