Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(computer): run background Memory and Wiki on local Pi
white64a5c2565e0f
diff --git a/apps/computer/AGENTS.md b/apps/computer/AGENTS.mdindex d4a115c7..1a084c83 100644--- a/apps/computer/AGENTS.md+++ b/apps/computer/AGENTS.md@@ -61,6 +61,10 @@## Runtime And Safety+- A Pi background model call uses one ephemeral RPC turn with no tools. It+ checks the Runtime's actual default against the local library's loaded+ models and a loopback endpoint before submitting the prompt.+- Default tests use deterministic providers and real fixture child processes;they never call a live model.- Process-test watchdogs are harness budgets for loaded developer machines, notdiff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.goindex 276dd413..41d82c99 100644--- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go+++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go@@ -409,9 +409,13 @@ func run(args []string) (resultErr error) {RuntimeHomeRoot: filepath.Join(computer.StateDirectory, "runtime-homes"),Lookup: func(ctx context.Context, runtimeType string) (provider.ModelInvokeRuntime, bool, error) {installed, ok, err := providerCatalog.Lookup(ctx, runtimeType)- return provider.ModelInvokeRuntime{+ runtime := provider.ModelInvokeRuntime{ExecutablePath: installed.ExecutablePath, Environment: installed.Environment, Version: installed.Version,- }, ok, err+ }+ if runtimeType == "pi" {+ runtime.LoadedPiModels = localModels.LoadedPiModels()+ }+ return runtime, ok, err},},})diff --git a/apps/computer/local-daemon/internal/daemon/model_invoke_test.go b/apps/computer/local-daemon/internal/daemon/model_invoke_test.goindex bb2ee45a..82a4b62a 100644--- a/apps/computer/local-daemon/internal/daemon/model_invoke_test.go+++ b/apps/computer/local-daemon/internal/daemon/model_invoke_test.go@@ -100,27 +100,33 @@ func waitForModelInvoked(t *testing.T, stream *fakeStream, invokeID string) map[}func TestModelInvokeRunsTheCallAndReportsItsResult(t *testing.T) {- invoker := newFakeModelInvoker()- d, stream := modelInvokeFixture(t, invoker)- if err := d.handleModelInvoke(context.Background(), stream, modelInvokeCommand("invoke-1", map[string]any{"session_key": "permission-review:abc"})); err != nil {- t.Fatal(err)- }- request := <-invoker.started- if request.RuntimeType != "codex" || request.Mode != "structured" || request.ReasoningEffort != "low" ||- request.Instructions != "Answer." || request.Input != "Question" || string(request.OutputSchema) != `{"type":"object"}` ||- request.Timeout != 30*time.Second || request.SessionKey != "permission-review:abc" {- t.Fatalf("request = %+v", request)- }- close(invoker.release)- payload := waitForModelInvoked(t, stream, "invoke-1")- if payload["outcome"] != "completed" || payload["text"] != `{"answer":"ok"}` || payload["model"] != "fixture-model" ||- payload["runtime_version"] != "0.166.0" || payload["command_id"] != "command-invoke-1" || payload["runner_id"] != "computer-1" ||- payload["reason"] != nil {- t.Fatalf("payload = %v", payload)- }- usage, _ := payload["usage"].(map[string]any)- if usage["input_tokens"] != float64(10) || usage["cached_input_tokens"] != float64(2) || usage["output_tokens"] != float64(3) {- t.Fatalf("usage = %v", usage)+ for _, runtime := range []string{"codex", "pi"} {+ t.Run(runtime, func(t *testing.T) {+ invoker := newFakeModelInvoker()+ d, stream := modelInvokeFixture(t, invoker)+ command := modelInvokeCommand("invoke-1", map[string]any{"session_key": "permission-review:abc"})+ command.RuntimeType = runtime+ if err := d.handleModelInvoke(context.Background(), stream, command); err != nil {+ t.Fatal(err)+ }+ request := <-invoker.started+ if request.RuntimeType != runtime || request.Mode != "structured" || request.ReasoningEffort != "low" ||+ request.Instructions != "Answer." || request.Input != "Question" || string(request.OutputSchema) != `{"type":"object"}` ||+ request.Timeout != 30*time.Second || request.SessionKey != "permission-review:abc" {+ t.Fatalf("request = %+v", request)+ }+ close(invoker.release)+ payload := waitForModelInvoked(t, stream, "invoke-1")+ if payload["outcome"] != "completed" || payload["text"] != `{"answer":"ok"}` || payload["model"] != "fixture-model" ||+ payload["runtime_version"] != "0.166.0" || payload["command_id"] != "command-invoke-1" || payload["runner_id"] != "computer-1" ||+ payload["reason"] != nil {+ t.Fatalf("payload = %v", payload)+ }+ usage, _ := payload["usage"].(map[string]any)+ if usage["input_tokens"] != float64(10) || usage["cached_input_tokens"] != float64(2) || usage["output_tokens"] != float64(3) {+ t.Fatalf("usage = %v", usage)+ }+ })}}diff --git a/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go b/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.goindex 59292340..37e38588 100644--- a/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go+++ b/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go@@ -336,6 +336,10 @@ func TestGatewayModelInvocationKeepsIdentityAndRawRequest(t *testing.T) {request.InvokeID != "invoke-1" || request.Input != "Question" || string(request.OutputSchema) != `{"type":"object"}` {t.Fatalf("command = %+v request = %+v", command, request)}+ pi, err := decodeGatewayCommand([]byte(strings.Replace(valid, `"runtime_type":"codex"`, `"runtime_type":"pi"`, 1)))+ if err != nil || pi.RuntimeType != "pi" {+ t.Fatalf("Pi model invocation decoded as %+v: %v", pi, err)+ }for _, change := range [][2]string{{`"protocol_version":"2"`, `"protocol_version":"1.2"`},{`"tenant_id":"tenant-1",`, ""},diff --git a/apps/computer/local-daemon/internal/localmodels/library.go b/apps/computer/local-daemon/internal/localmodels/library.goindex 27c943db..2b1b065e 100644--- a/apps/computer/local-daemon/internal/localmodels/library.go+++ b/apps/computer/local-daemon/internal/localmodels/library.go@@ -338,6 +338,21 @@ func (l *Library) commit(snapshot wire.LocalModelsSnapshot) {l.publish(cloneSnapshot(snapshot))}+// LoadedPiModels returns the Pi names of models loaded in the last library report.+func (l *Library) LoadedPiModels() []string {+ l.mu.Lock()+ defer l.mu.Unlock()+ var models []string+ if l.current != nil && l.current.Available {+ for _, model := range l.current.Models {+ if model.State == "loaded" && model.PiModel != "" {+ models = append(models, model.PiModel)+ }+ }+ }+ return models+}+// Act starts one action and returns the tool's answer: accepted (nil) or// its refusal. deadline is when the requester stops waiting. When it passes// before the tool has decided, answered is false: the Daemon does not guessdiff --git a/apps/computer/local-daemon/internal/provider/model_invoke.go b/apps/computer/local-daemon/internal/provider/model_invoke.goindex 57927e56..9123e6b3 100644--- a/apps/computer/local-daemon/internal/provider/model_invoke.go+++ b/apps/computer/local-daemon/internal/provider/model_invoke.go@@ -106,6 +106,7 @@ type ModelInvokeRuntime struct {ExecutablePath stringEnvironment map[string]stringVersion string+ LoadedPiModels []string}// ModelInvokeFile is one workspace file, relative to the working directory.@@ -149,7 +150,7 @@ type ModelInvokeResult struct {Reason string}-// ModelInvoker runs one-shot model calls on the installed Codex or Claude CLI+// ModelInvoker runs one-shot model calls on the installed Runtime// in a fresh temporary directory. It never injects the Linger CLI credential// and never loads the user's instructions, MCP servers, hooks or Skills.type ModelInvoker struct {@@ -220,7 +221,7 @@ type modelInvocation struct {// Invoke runs one model call and always returns a result; failures are// classified into outcomes instead of returned as errors.func (m ModelInvoker) Invoke(ctx context.Context, request ModelInvokeRequest) ModelInvokeResult {- if request.RuntimeType != "codex" && request.RuntimeType != "claude" {+ if !native.Supports(request.RuntimeType) {return ModelInvokeResult{Outcome: ModelInvokeRuntimeUnavailable, Reason: "Runtime does not support model invocation"}}if m.Lookup == nil {@@ -251,6 +252,9 @@ func (m ModelInvoker) invoke(ctx context.Context, request ModelInvokeRequest, inreturn ModelInvokeResult{Outcome: ModelInvokeFailed, Reason: "Prepare model invocation directory: " + err.Error()}}}+ if request.RuntimeType == "pi" {+ return invokePiModel(ctx, request, installed, work, scratch)+ }if request.Mode == ModelInvokeWorkspace {if err := writeModelInvokeFiles(work, request.WorkspaceFiles); err != nil {return ModelInvokeResult{Outcome: ModelInvokeFailed, Reason: err.Error()}diff --git a/apps/computer/local-daemon/internal/provider/model_invoke_test.go b/apps/computer/local-daemon/internal/provider/model_invoke_test.goindex a9f0cbd4..bf9c0325 100644--- a/apps/computer/local-daemon/internal/provider/model_invoke_test.go+++ b/apps/computer/local-daemon/internal/provider/model_invoke_test.go@@ -406,9 +406,9 @@ func TestModelInvokerRejectsUnsupportedOrMissingRuntimes(t *testing.T) {called := falsefixture := newCodexInvokeFixture(t, func(context.Context, *exec.Cmd) error { called = true; return nil })request := structuredRequest()- request.RuntimeType = "pi"+ request.RuntimeType = "unsupported"if result := fixture.invoker.Invoke(context.Background(), request); result.Outcome != ModelInvokeRuntimeUnavailable {- t.Fatalf("pi result = %+v", result)+ t.Fatalf("unsupported result = %+v", result)}request.RuntimeType = "claude"if result := fixture.invoker.Invoke(context.Background(), request); result.Outcome != ModelInvokeRuntimeUnavailable {diff --git a/apps/computer/local-daemon/internal/provider/native/pi_catalog.go b/apps/computer/local-daemon/internal/provider/native/pi_catalog.goindex ef4a9973..55f4d8cc 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_catalog.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_catalog.go@@ -24,6 +24,7 @@ type piCatalogState struct {Model struct {ID string `json:"id"`Provider string `json:"provider"`+ BaseURL string `json:"baseUrl"`} `json:"model"`ThinkingLevel string `json:"thinkingLevel"`}diff --git a/apps/computer/local-daemon/internal/provider/native/pi_events.go b/apps/computer/local-daemon/internal/provider/native/pi_events.goindex fdd39c17..4ae62de7 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_events.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_events.go@@ -154,7 +154,10 @@ func (t *piTurn) applyMessageEnd(message piWireMessage, observed time.Time) {}t.textID = ""t.sawAssistant = true- t.output = piFilterMarkup(piMessageText(message.Content))+ t.output = piMessageText(message.Content)+ if !t.oneShot {+ t.output = piFilterMarkup(t.output)+ }t.failure = ""if message.StopReason == "error" || message.StopReason == "aborted" {t.failure = message.ErrorMessagediff --git a/apps/computer/local-daemon/internal/provider/native/pi_finish.go b/apps/computer/local-daemon/internal/provider/native/pi_finish.goindex dce29c69..a1aabccd 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_finish.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_finish.go@@ -67,7 +67,7 @@ func (t *piTurn) drive(prompt string) {func (t *piTurn) startup(prompt string) error {ctx, cancel := context.WithTimeout(t.runCtx, piStartupBudget)defer cancel()- if !t.reused {+ if !t.reused && !t.oneShot {if _, err := t.proc.sessionState(ctx); err != nil {return err}@@ -201,8 +201,10 @@ func (t *piTurn) settledStatus() (string, string) {case p.waitErr != nil:return statusFailed, "Pi exited unsuccessfully: " + p.waitErr.Error()}- if err := piValidateSession(p.sessionDir, p.sessionID, p.contextDir); err != nil {- return statusFailed, err.Error()+ if !t.oneShot {+ if err := piValidateSession(p.sessionDir, p.sessionID, p.contextDir); err != nil {+ return statusFailed, err.Error()+ }}return statusCompleted, ""}diff --git a/apps/computer/local-daemon/internal/provider/native/pi_model_invoke.go b/apps/computer/local-daemon/internal/provider/native/pi_model_invoke.gonew file mode 100644index 00000000..402570ed--- /dev/null+++ b/apps/computer/local-daemon/internal/provider/native/pi_model_invoke.go@@ -0,0 +1,90 @@+package native++import (+ "context"+ "encoding/json"+ "errors"+ "log/slog"+ "net/netip"+ "net/url"+ "slices"+ "strings"+)++// ErrPiLocalModelUnavailable means Pi has no verified loaded local default.+// Do not send a background prompt to an unverified endpoint.+var ErrPiLocalModelUnavailable = errors.New("Pi background calls need a loaded local model selected as Pi's default")++// InvokePiModel runs a single tool-free RPC turn with the same Pi profile and+// event handling as managed execution, but with no persistent session.+func InvokePiModel(ctx context.Context, profile Profile, dir, instructionsFile, prompt, effort string, loadedModels []string) (Outcome, string, error) {+ if len(loadedModels) == 0 {+ return Outcome{}, "", ErrPiLocalModelUnavailable+ }+ thinking, err := piThinkingLevel(effort)+ if err != nil {+ return Outcome{}, "", err+ }+ args := append([]string{"--mode", "rpc", "--no-session", "--no-tools"}, PiRPCResourceArgs()...)+ if instructionsFile != "" {+ args = append(args, "--append-system-prompt", instructionsFile)+ }+ if thinking != "" {+ args = append(args, "--thinking", thinking)+ }+ profile.Logger = slog.Default()+ procCtx, stop := context.WithCancel(context.Background())+ defer stop()+ cmd := ownedCommand(procCtx, profileInvocation(profile.Program, nil, profile.Env), args...)+ cmd.Dir, cmd.WaitDelay = dir, piChildPipeDrain+ proc, err := piLaunch(profile, cmd)+ if err != nil {+ return Outcome{}, "", err+ }+ proc.sessionDir, proc.cancel = dir, stop+ proc.res.bind(dir, profile)+ proc.run()+ defer func() {+ if proc.stop() {+ piResidents.forget(proc)+ } else {+ piResidents.hold(proc)+ }+ }()++ probeCtx, cancelProbe := context.WithTimeout(ctx, piStartupBudget)+ state, err := proc.call(probeCtx, "get_state", nil, nil)+ cancelProbe()+ if err != nil {+ return Outcome{}, "", errors.New("Pi background model state could not be read")+ }+ var catalog piCatalogState+ if json.Unmarshal(state.Data, &catalog) != nil {+ return Outcome{}, "", ErrPiLocalModelUnavailable+ }+ model := catalog.Model.Provider + "/" + catalog.Model.ID+ if !slices.Contains(loadedModels, model) || !piLoopbackURL(catalog.Model.BaseURL) {+ return Outcome{}, "", ErrPiLocalModelUnavailable+ }+ runCtx, cancel := context.WithCancel(ctx)+ defer cancel()+ turn := newPiTurn(runCtx, cancel, proc, false, releaseFence{}, profile.Logger)+ turn.oneShot = true+ if err := proc.bind(turn); err != nil {+ return Outcome{}, "", err+ }+ go turn.drive(prompt)+ for range turn.events {+ }+ return <-turn.outcome, model, nil+}++func piLoopbackURL(raw string) bool {+ endpoint, err := url.Parse(raw)+ if err != nil || endpoint.User != nil || (endpoint.Scheme != "http" && endpoint.Scheme != "https") {+ return false+ }+ host := endpoint.Hostname()+ ip, err := netip.ParseAddr(host)+ return (err == nil && ip.Unmap().IsLoopback()) || strings.EqualFold(host, "localhost")+}diff --git a/apps/computer/local-daemon/internal/provider/native/pi_model_invoke_test.go b/apps/computer/local-daemon/internal/provider/native/pi_model_invoke_test.gonew file mode 100644index 00000000..06656f52--- /dev/null+++ b/apps/computer/local-daemon/internal/provider/native/pi_model_invoke_test.go@@ -0,0 +1,16 @@+package native++import "testing"++func TestPiBackgroundEndpointMustBeLoopback(t *testing.T) {+ for _, endpoint := range []string{"http://127.0.0.1:8080/v1", "http://[::1]:8080", "http://localhost:8080"} {+ if !piLoopbackURL(endpoint) {+ t.Errorf("refused loopback endpoint %s", endpoint)+ }+ }+ for _, endpoint := range []string{"", "http://localhost.example.test", "https://example.test/v1", "http://[email protected]", "file://localhost/model"} {+ if piLoopbackURL(endpoint) {+ t.Errorf("accepted non-loopback endpoint %s", endpoint)+ }+ }+}diff --git a/apps/computer/local-daemon/internal/provider/native/pi_run.go b/apps/computer/local-daemon/internal/provider/native/pi_run.goindex c963fa79..549702de 100644--- a/apps/computer/local-daemon/internal/provider/native/pi_run.go+++ b/apps/computer/local-daemon/internal/provider/native/pi_run.go@@ -17,11 +17,12 @@ const piEventBuffer = 256// steering belong to this turn only, never to a later turn of the same// reused process.type piTurn struct {- proc *piProcess- id string- reused bool- fence releaseFence- logger *slog.Logger+ proc *piProcess+ id string+ reused bool+ oneShot bool+ fence releaseFence+ logger *slog.LoggerrunCtx context.Contextcancel context.CancelFuncdiff --git a/apps/computer/local-daemon/internal/provider/pi_model_invoke.go b/apps/computer/local-daemon/internal/provider/pi_model_invoke.gonew file mode 100644index 00000000..b8ec8f23--- /dev/null+++ b/apps/computer/local-daemon/internal/provider/pi_model_invoke.go@@ -0,0 +1,68 @@+package provider++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "strings"++ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider/native"+ localworkspace "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/workspace"+)++func invokePiModel(ctx context.Context, request ModelInvokeRequest, installed ModelInvokeRuntime, work, scratch string) ModelInvokeResult {+ if request.Mode == ModelInvokeWorkspace {+ return ModelInvokeResult{Outcome: ModelInvokeRuntimeUnavailable, Reason: "Pi background calls do not run file tools"}+ }+ environment := modelInvokeEnvironment(installed.Environment, scratch)+ // The verified loopback endpoint must not be routed through a user proxy.+ for key := range environment {+ switch strings.ToUpper(key) {+ case "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY":+ delete(environment, key)+ }+ }+ environment, err := localworkspace.PiSourceEnvironment(environment)+ if err != nil {+ return ModelInvokeResult{Outcome: ModelInvokeRuntimeUnavailable, Reason: "Pi background profile is unavailable"}+ }+ instructions := request.Instructions+ if request.Mode == ModelInvokeStructured {+ instructions += "\n\nReturn only a JSON object matching this schema:\n" + string(request.OutputSchema)+ }+ instructionsFile := ""+ if instructions != "" {+ instructionsFile = filepath.Join(scratch, "instructions.md")+ if err := os.WriteFile(instructionsFile, []byte(instructions), 0o600); err != nil {+ return ModelInvokeResult{Outcome: ModelInvokeFailed, Reason: "Could not prepare Pi background instructions"}+ }+ }+ invokeCtx, cancel := context.WithTimeout(ctx, modelInvokeTimeout(request.Timeout))+ defer cancel()+ answer, model, err := native.InvokePiModel(+ invokeCtx, native.Profile{Program: installed.ExecutablePath, Env: environment},+ work, instructionsFile, request.Input, request.ReasoningEffort, installed.LoadedPiModels,+ )+ switch {+ case invokeCtx.Err() != nil:+ return classifyModelInvokeFailure(ctx, invokeCtx, err, "", "")+ case errors.Is(err, native.ErrPiLocalModelUnavailable):+ return ModelInvokeResult{Outcome: ModelInvokeRuntimeUnavailable, Reason: err.Error()}+ case err != nil || answer.Status != "completed" || !answer.ExitConfirmed:+ // Pi errors may include provider URLs or credentials.+ return ModelInvokeResult{Outcome: ModelInvokeFailed, Reason: "Pi background call did not complete"}+ case len(answer.Output) > ModelInvokeMaxTextBytes:+ return ModelInvokeResult{Outcome: ModelInvokeOutputLimited, Reason: "Pi background reply exceeds 1 MiB"}+ }+ result := ModelInvokeResult{Outcome: ModelInvokeCompleted, Text: answer.Output, Model: model}+ for _, count := range answer.Usage {+ if result.Usage == nil {+ result.Usage = &ModelInvokeUsage{}+ }+ result.Usage.InputTokens += count.Input+ result.Usage.OutputTokens += count.Output+ result.Usage.CachedInputTokens += count.CacheRead+ }+ return result+}diff --git a/apps/computer/local-daemon/internal/provider/pi_model_invoke_test.go b/apps/computer/local-daemon/internal/provider/pi_model_invoke_test.gonew file mode 100644index 00000000..4b7d90c8--- /dev/null+++ b/apps/computer/local-daemon/internal/provider/pi_model_invoke_test.go@@ -0,0 +1,118 @@+package provider++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++func TestModelInvokerPiLocal(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("fixture launches the POSIX pnpm Pi shim")+ }+ const structuredReply, textReply = `{"answer":"local"}`, "Local model reply."+ pi, err := filepath.Abs("../../../node_modules/.bin/pi")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(pi); err != nil {+ t.Skip("install Computer's pinned Pi with pnpm install to run the local endpoint fixture")+ }+ root := t.TempDir()+ payloads := make(chan string, 2)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {+ var payload json.RawMessage+ if req.URL.Path != "/v1/chat/completions" || json.NewDecoder(req.Body).Decode(&payload) != nil {+ t.Error("unexpected Pi model request")+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ select {+ case payloads <- string(payload):+ default:+ t.Error("unexpected additional local model request")+ }+ w.Header().Set("Content-Type", "text/event-stream")+ reply := textReply+ if strings.Contains(string(payload), "matching this schema") {+ reply = structuredReply+ }+ if _, err := fmt.Fprintf(w, `data: {"id":"test","object":"chat.completion.chunk","created":1,"model":"fixture","choices":[{"index":0,"delta":{"role":"assistant","content":%q},"finish_reason":null}]}++data: {"id":"test","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}++data: [DONE]++`, reply); err != nil {+ t.Error(err)+ }+ }))+ defer server.Close()+ write := func(name, content string) {+ t.Helper()+ if err := os.WriteFile(filepath.Join(root, name), []byte(content), 0600); err != nil {+ t.Fatal(err)+ }+ }+ write("models.json", fmt.Sprintf(`{"providers":{"local-fixture":{"baseUrl":%q,"api":"openai-completions","apiKey":"fixture","models":[{"id":"fixture"}]}}}`, server.URL+"/v1"))+ write("settings.json", `{"defaultProvider":"local-fixture","defaultModel":"fixture"}`)+ loaded := []string{"local-fixture/fixture"}+ invoker := ModelInvoker{+ TempBase: root,+ Lookup: func(_ context.Context, runtime string) (ModelInvokeRuntime, bool, error) {+ return ModelInvokeRuntime{+ ExecutablePath: pi, LoadedPiModels: loaded,+ Environment: map[string]string{"HOME": root, "PI_CODING_AGENT_DIR": root, "PATH": os.Getenv("PATH")},+ }, runtime == "pi", nil+ },+ }+ for _, mode := range []string{ModelInvokeStructured, ModelInvokeText} {+ t.Run(mode, func(t *testing.T) {+ request := ModelInvokeRequest{RuntimeType: "pi", Mode: mode, ReasoningEffort: "low", Instructions: "Fixture instructions.", Input: "Fixture source.", Timeout: 15 * time.Second}+ want := textReply+ if mode == ModelInvokeStructured {+ want = structuredReply+ request.OutputSchema = json.RawMessage(`{"type":"object","properties":{"answer":{"type":"string"}},"required":["answer"]}`)+ }+ result := invoker.Invoke(t.Context(), request)+ if result.Outcome != ModelInvokeCompleted || result.Text != want || result.Model != "local-fixture/fixture" {+ t.Fatalf("Pi invocation = %+v", result)+ }+ payload := <-payloads+ if !strings.Contains(payload, "Fixture source.") || !strings.Contains(payload, "Fixture instructions.") ||+ strings.Contains(payload, `"tools":[{`) ||+ (mode == ModelInvokeStructured) != strings.Contains(payload, "matching this schema") {+ t.Fatalf("unexpected request: %s", payload)+ }+ })+ }+ for _, test := range []struct {+ name, mode, reason string+ loaded []string+ }{+ {name: "not loaded", mode: ModelInvokeText, reason: "loaded local model"},+ {name: "default is not loaded", mode: ModelInvokeText, reason: "loaded local model", loaded: []string{"local-fixture/other"}},+ {name: "file tools are not enabled", mode: ModelInvokeWorkspace, reason: "file tools", loaded: loaded},+ } {+ t.Run(test.name, func(t *testing.T) {+ loaded = test.loaded+ result := invoker.Invoke(t.Context(), ModelInvokeRequest{RuntimeType: "pi", Mode: test.mode, Input: "Must not be sent.", Timeout: 15 * time.Second})+ if result.Outcome != ModelInvokeRuntimeUnavailable || !strings.Contains(result.Reason, test.reason) {+ t.Fatalf("Pi invocation = %+v", result)+ }+ select {+ case <-payloads:+ t.Fatal("sent a prompt before Pi was eligible for the call")+ default:+ }+ })+ }+}diff --git a/apps/computer/package.json b/apps/computer/package.jsonindex 8e251e4b..1200a71e 100644--- a/apps/computer/package.json+++ b/apps/computer/package.json@@ -1,6 +1,6 @@{"name": "@linger/computer",- "version": "0.54.0",+ "version": "0.55.0","description": "Local Computer: resident Daemon, control CLI, and Runner Gateway transport.","private": true,"type": "module",diff --git a/apps/node-services/src/agent/AGENTS.md b/apps/node-services/src/agent/AGENTS.mdindex 35dc58e2..2552067e 100644--- a/apps/node-services/src/agent/AGENTS.md+++ b/apps/node-services/src/agent/AGENTS.md@@ -32,13 +32,15 @@ take precedence.- Keep model/provider behavior behind the existing runtime interfaces. The onlyexception is `src/runtime-model-call.ts`: a stateless prompt on the owner's- Agent Runtime (Codex or Claude, the Runtime's default model) through the+ Agent Runtime (Codex, Claude or Pi, using its default model) through theDaemon's one-shot `model.invoke`, for tool-less service work such as Agent- Memory, also used by Memory, by the LLM Wiki (workspace mode), and exposed+ Memory, also used by Memory, by the LLM Wiki, and exposedto TeamHub as `POST /v1/model-calls`.It is not a Runtime turn and never creates a Context, Local Run, orOperation. Callers name an owner (or an Agent placement) and a reasoning- effort; never add a model name, gateway, or model environment variable.+ effort; never add a model name, gateway, or model environment variable. Pi+ stays on Pi and requires a loaded local default. It serves structured and+ text calls without tools; workspace mode remains on Codex and Claude.- TeamHub owns persisted Agent Runtime configuration, Execution Context,accepted input, Inbox cursor, Local Run, RuntimeSession, Runtime status,Local Computer and Agent placement state. Agent Runners and Operations livediff --git a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts b/apps/node-services/src/agent/runner-gateway/local-computer-management.tsindex fe7932d8..757518cf 100644--- a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts+++ b/apps/node-services/src/agent/runner-gateway/local-computer-management.ts@@ -39,6 +39,8 @@ export const FIRST_MODEL_INVOKE_CANCEL_COMPUTER_VERSION = "0.53.0";// The first release that runs `model_source` commands. An older Computer// closes the connection on a command kind it cannot decode.export const FIRST_MODEL_SOURCE_COMPUTER_VERSION = "0.54.0";+// Older Daemons do not decode Pi as a model_invoke Runtime.+export const FIRST_PI_MODEL_INVOKE_COMPUTER_VERSION = "0.55.0";const COMPUTER_RELEASE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;diff --git a/apps/node-services/src/agent/runner-gateway/runner-connections.ts b/apps/node-services/src/agent/runner-gateway/runner-connections.tsindex 95422b39..e7a66931 100644--- a/apps/node-services/src/agent/runner-gateway/runner-connections.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-connections.ts@@ -25,6 +25,7 @@ import {LocalRuntimeAdmissionUnavailableError,MINIMUM_CURRENT_COMPUTER_VERSION,FIRST_MODEL_INVOKE_CANCEL_COMPUTER_VERSION,+ FIRST_PI_MODEL_INVOKE_COMPUTER_VERSION,FIRST_SERVICE_FEATURES_COMPUTER_VERSION,type LocalPlacementRequirement,type LocalReasoningEffort,@@ -814,7 +815,11 @@ export class RunnerConnections {const connection = this.#connections.get(runnerId);return (isServingConnection(connection) &&- (runtimeType === "codex" || runtimeType === "claude") &&+ (runtimeType !== "pi" ||+ isComputerVersionAtLeast(+ connection.hello.daemon_version,+ FIRST_PI_MODEL_INVOKE_COMPUTER_VERSION,+ )) &&connection.hello.runtime_diagnostics.some(({ type, status }) => type === runtimeType && status === "ready",)diff --git a/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts b/apps/node-services/src/agent/runner-gateway/runner-model-invocation.tsindex e2d63f58..651fed5c 100644--- a/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts@@ -250,7 +250,9 @@ export class RunnerModelInvocation {}if (!connections.supportsModelInvoke(computerId, runtimeType)) {throw new RunnerModelInvokeUnavailableError(- `Local Computer Runtime ${runtimeType} is not ready`,+ runtimeType === "pi"+ ? "Pi is not ready for background model calls. Update the Local Computer and load its local model."+ : `Local Computer Runtime ${runtimeType} is not ready`,);}}diff --git a/apps/node-services/src/runtime-model-call.ts b/apps/node-services/src/runtime-model-call.tsindex 5a5292ae..f411751f 100644--- a/apps/node-services/src/runtime-model-call.ts+++ b/apps/node-services/src/runtime-model-call.ts@@ -20,9 +20,8 @@ import { modelCallPolicies, type ModelCallKind } from "./model-tasks.js";type AnotherMePlacement = components["schemas"]["AnotherMePlacement"];/**- * Background model calls run on the owner's own Agent Runtime (Codex or- * Claude) through the Daemon's one-shot model invocation, with the Runtime's- * default model. No gateway, API key or model name is involved.+ * Background model calls use the Daemon's one-shot model invocation and the+ * selected Runtime's default model. The request names no endpoint, key or model.*/export type ModelCallEffort = ModelInvoke["reasoning_effort"];@@ -217,7 +216,7 @@ export interface RuntimeModelCall extends ModelCall {export type ModelCallErrorKind =/** Offline, updating or draining: retry once the Computer is back. */| "computer_offline"- /** No model invocation support or no ready Codex or Claude on the Computer. */+ /** No supported, ready Runtime on the Computer. */| "runtime_unavailable"/** No owner given and not exactly one Another Me, or the owner or Another* Me has no placement. */@@ -712,11 +711,8 @@ async function resolvePlacement(return { placement, key };}-/** Where a call on this placement runs: the placement's own Runtime when it- * can run model calls, else the other ready one on that Computer, and the- * model that Runtime runs by default, since a model invocation names none.- * With neither Runtime ready the placement's is still tried, so an offline- * Computer reports offline. */+/** Pi stays on Pi, even when it is unavailable. Codex and Claude retain+ * their same-Computer fallback. Invocations use the selected Runtime's default. */function resolveTarget(gateway: RuntimeModelGateway,placement: ModelPlacement,@@ -725,14 +721,14 @@ function resolveTarget(readonly offline: boolean;readonly model?: RuntimeModelInfo;} {- const preferred: readonly ModelInvoke["runtime_type"][] =- placement.runtimeType === "claude"- ? ["claude", "codex"]- : ["codex", "claude"];+ const preferred = placement.runtimeType;+ const fallback = preferred === "claude" ? "codex" : "claude";const runtimeType =- preferred.find((runtime) =>- gateway.supportsModelInvoke(placement.computerId, runtime),- ) ?? preferred[0]!;+ preferred !== "pi" &&+ !gateway.supportsModelInvoke(placement.computerId, preferred) &&+ gateway.supportsModelInvoke(placement.computerId, fallback)+ ? fallback+ : preferred;const models = gateway.runtimeModels(placement.computerId, runtimeType);const model = models?.find(({ isDefault }) => isDefault);return {diff --git a/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.ts b/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.tsindex 27c7160c..25b8ba2c 100644--- a/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/go-local-daemon-process.test.ts@@ -1,3 +1,5 @@+import { createRuntimeModelCall } from "../../../src/runtime-model-call.js";+import { runtimeModelGateway } from "../../../src/agent/runner-gateway/runtime-model-gateway.js";import { createLocalContextRuntimeBackend } from "../../../src/agent/executor/local-backend.js";import {createContextRuntimeActivator,@@ -277,6 +279,270 @@ const publishContextView = async (return snapshot.viewDigest;};+processTest(+ "runs Memory and Wiki through a Pi-only Daemon and a loopback model endpoint",+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "go-daemon-pi-model-"));+ const computerId = "computer-pi-background";+ const owner = {+ tenantId: "tenant-pi-background",+ ownerActorId: "human-pi-background",+ };+ const anotherMe = {+ tenantId: owner.tenantId,+ agentActorId: "actor-pi-background",+ };+ const piModel = "fixture-local/model";+ const token = runnerToken(computerId, owner.tenantId, owner.ownerActorId);+ const gateway = createTestRunnerGateway({+ computerDaemonIdentityVerifier: createComputerDaemonIdentityVerifier(),+ });+ testRegistryOf(gateway).enroll({ computerId, ...owner });+ const model = createRuntimeModelCall({+ gateway: runtimeModelGateway(gateway),+ placements: async () => [+ {+ ...owner,+ computerId,+ runtimeType: "pi",+ agentId: "agent-pi-background",+ agentActorId: anotherMe.agentActorId,+ },+ ],+ });+ const inputs: string[] = [];+ const sessionErrors: string[] = [];+ const server = createServer((request, response) => {+ if (request.method !== "POST" || request.url !== "/v1/chat/completions") {+ response.writeHead(404).end();+ return;+ }+ let input = "";+ request.setEncoding("utf8").on("data", (chunk: string) => {+ input += chunk;+ });+ request.once("end", () => {+ inputs.push(input);+ const content = input.includes("Memory fixture evidence")+ ? '{"answer":"memory"}'+ : "Wiki fixture reply.";+ const chunk = (delta: object, finish_reason: string | null) =>+ JSON.stringify({+ id: "fixture",+ object: "chat.completion.chunk",+ created: 1,+ model: "model",+ choices: [{ index: 0, delta, finish_reason }],+ });+ response+ .writeHead(200, { "content-type": "text/event-stream" })+ .end(+ `data: ${chunk({ role: "assistant", content }, null)}\n\ndata: ${chunk({}, "stop")}\n\ndata: [DONE]\n\n`,+ );+ });+ });+ const handle = attachRunnerGatewayWebSocket({+ server,+ gateway,+ onSessionError: (error) => sessionErrors.push(String(error)),+ credentialAuthenticators: [+ createTestRunnerCredentialAuthority([+ {+ runnerId: computerId,+ token,+ credentialGeneration: 0,+ tenantOwners: [owner],+ },+ ]),+ ],+ });+ let child: ChildProcess | undefined;+ try {+ await new Promise<void>((resolve) =>+ server.listen(0, "127.0.0.1", resolve),+ );+ const port = (server.address() as AddressInfo).port;+ const pi = path.resolve(+ process.cwd(),+ "../computer/node_modules/.bin/pi",+ );+ const binary = path.join(root, "bin", "linger-computer-daemon");+ const config = path.join(root, "computer.json");+ const profile = path.join(root, ".pi", "agent");+ const credential = path.join(root, "runner-token");+ const library = path.join(root, "localmodels-fixture");+ await mkdir(profile, { recursive: true });+ const report = JSON.stringify({+ schema: "localmodels.library-status/v1",+ tool_version: "fixture",+ host: {+ platform: "darwin",+ arch: "arm64",+ os_label: "fixture",+ engine_label: "fixture",+ ram_total_bytes: 1024,+ disk_free_bytes: 1024,+ gpus: [],+ },+ models: [+ {+ id: "model",+ name: "Fixture",+ description: "",+ quant: "fixture",+ context_tokens: 65536,+ vision: false,+ download_bytes: 0,+ memory_bytes: 0,+ fit: "none",+ recommended: false,+ availability: { downloadable: true },+ state: "loaded",+ pi_model: piModel,+ },+ ],+ });+ await Promise.all([+ installDaemonBinary(binary),+ writeFile(credential, token, { mode: 0o600 }),+ writeFile(+ library,+ `#!/bin/sh\n[ "$5 $6" = "library status" ] || exit 2\ncat <<'EOF'\n${report}\nEOF\n`,+ { mode: 0o700 },+ ),+ writeFile(+ path.join(profile, "settings.json"),+ JSON.stringify({+ defaultProvider: "fixture-local",+ defaultModel: "model",+ }),+ ),+ writeFile(+ path.join(profile, "models.json"),+ JSON.stringify({+ providers: {+ "fixture-local": {+ baseUrl: `http://127.0.0.1:${port}/v1`,+ api: "openai-completions",+ apiKey: "fixture",+ models: [{ id: "model" }],+ },+ },+ }),+ ),+ writeFile(+ config,+ JSON.stringify({+ runner_id: computerId,+ display_name: "Pi background fixture",+ gateway: {+ url: `ws://127.0.0.1:${port}/v1/runner-gateway`,+ token_file: credential,+ },+ state_directory: path.join(root, "daemon-state"),+ enabled_runtimes: ["pi"],+ runtime_paths: { pi },+ workspace_grants: [+ {+ grant_id: "grant-pi-fixture",+ tenant_id: owner.tenantId,+ mode: "workspace-write",+ scope: "owner",+ root_path: root,+ },+ ],+ local_models: {+ python: library,+ module_directory: root,+ state_directory: root,+ base_directory: root,+ },+ }),+ { mode: 0o600 },+ ),+ ]);+ let stderr = "";+ child = startDaemon(+ binary,+ config,+ root,+ (value) => {+ stderr += value;+ },+ [path.dirname(process.execPath), "/usr/bin", "/bin"],+ );+ await vi.waitFor(+ () => {+ if (sessionErrors.length)+ throw new Error(+ `Pi daemon Gateway error: ${sessionErrors[0]}; ${stderr}`,+ );+ expect(gateway.supportsModelInvoke(computerId, "pi"), stderr).toBe(+ true,+ );+ expect(+ testRegistryOf(gateway).localModels(computerId).at(-1)?.models[0]+ ?.pi_model,+ stderr,+ ).toBe(piModel);+ },+ { timeout: 15_000 },+ );+ expect(gateway.supportsModelInvoke(computerId, "codex")).toBe(false);+ expect(gateway.supportsModelInvoke(computerId, "claude")).toBe(false);+ const signal = AbortSignal.timeout(20_000);+ await expect(+ model.chain(+ { kind: "memory", key: "fixture-facts", owner, signal },+ (chain) =>+ chain.call({+ step: "extract",+ input: "Memory fixture evidence",+ schemaName: "fact",+ outputSchema: {+ type: "object",+ required: ["answer"],+ properties: { answer: { type: "string" } },+ },+ }),+ ),+ ).resolves.toEqual({ output: { answer: "memory" }, model: piModel });+ await expect(+ model.chain(+ { kind: "wiki", key: "fixture-wiki", anotherMe, signal },+ (chain) =>+ chain.text({ step: "write", input: "Wiki fixture evidence" }),+ ),+ ).resolves.toEqual({ output: "Wiki fixture reply.", model: piModel });+ expect(inputs).toHaveLength(2);+ expect(inputs[1]).toContain("Wiki fixture evidence");+ expect(inputs.every((input) => !input.includes('"tools":[{'))).toBe(true);+ } finally {+ model.close();+ try {+ if (child && child.exitCode === null && child.signalCode === null) {+ const exited = new Promise<void>((resolve) =>+ child!.once("exit", () => resolve()),+ );+ child.kill("SIGTERM");+ const timer = setTimeout(() => child?.kill("SIGKILL"), 3_000);+ try {+ await within(exited, "Pi daemon cleanup", 5_000);+ } finally {+ clearTimeout(timer);+ }+ }+ } finally {+ await handle.close();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await rm(root, { recursive: true, force: true });+ }+ }+ },+ 60_000,+);+// Real daemon, trusted file-install protocol and standalone CLI processes;// TeamHub HTTP and the native provider are deterministic fixtures, without PG.processTest(diff --git a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.tsindex 8c72d7ae..a5e50ead 100644--- a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts@@ -24,6 +24,7 @@ import { CURRENT_RUNNER_CAPABILITIES } from "../test-support/runner-capabilitiesimport { createTestRunnerGateway } from "../test-support/runner-gateway.js";import {acceptReadyConnection,+ defaultAgentPlacement,hello,RecordingPeer,event,@@ -98,6 +99,7 @@ const invoked = (const connect = async (value: RunnerHello = invokingHello(),+ placement = defaultAgentPlacement(),): Promise<{gateway: RunnerGateway;peer: RecordingPeer;@@ -107,11 +109,129 @@ const connect = async (createId: sequenceIds(),});const peer = new RecordingPeer();- const connection = await acceptReadyConnection(gateway, peer, value);+ const connection = await acceptReadyConnection(+ gateway,+ peer,+ value,+ placement,+ );return { gateway, peer, connection };};describe("RunnerGateway model invocation", () => {+ it("runs Memory and Wiki on a Pi-only Computer", async () => {+ const { gateway, peer, connection } = await connect(+ {+ ...invokingHello(),+ runtimes: ["pi"],+ runtime_diagnostics: runtimeDiagnostics({ ready: ["pi"], link: "api" }),+ },+ defaultAgentPlacement({+ agentId: "agent-another-me",+ runtime: { type: "pi" },+ }),+ );+ const owner = { tenantId: "tenant-acme", ownerActorId: "human-alice" };+ const anotherMe = {+ tenantId: "tenant-acme",+ agentActorId: "actor-another-me",+ };+ const model = createRuntimeModelCall({+ gateway: runtimeModelGateway(gateway),+ placements: async () => [+ {+ ...owner,+ agentId: "agent-another-me",+ agentActorId: anotherMe.agentActorId,+ computerId: "runner-local",+ runtimeType: "pi",+ },+ ],+ });+ try {+ expect(gateway.supportsModelInvoke("runner-local", "pi")).toBe(true);+ const memory = model.chain(+ { kind: "memory", key: "facts", owner },+ (chain) =>+ chain.call({+ step: "extract",+ schemaName: "facts",+ outputSchema: { type: "object" },+ input: "Room fact",+ }),+ );+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(1));+ expect(sentInvocations(peer)[0]).toMatchObject({+ runtime_type: "pi",+ mode: "structured",+ });+ await invoked(connection, sentInvocations(peer)[0]!);+ await expect(memory).resolves.toMatchObject({+ output: { summary: "ok" },+ });++ const wiki = model.chain(+ { kind: "wiki", key: "refresh", anotherMe },+ (chain) => chain.text({ step: "write", input: "Wiki evidence" }),+ );+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(2));+ expect(sentInvocations(peer)[1]).toMatchObject({+ runtime_type: "pi",+ mode: "text",+ });+ await invoked(connection, sentInvocations(peer)[1]!);+ await expect(wiki).resolves.toMatchObject({ output: '{"summary":"ok"}' });+ } finally {+ model.close();+ connection.disconnect();+ }+ });++ it.each([+ { daemonVersion: "0.54.0", piReady: true },+ { daemonVersion: "dev", piReady: false },+ ])(+ "never routes an unsupported Pi placement to ready Codex ($daemonVersion, $piReady)",+ async ({ daemonVersion, piReady }) => {+ const { gateway, peer, connection } = await connect({+ ...invokingHello(),+ daemon_version: daemonVersion,+ runtimes: piReady ? ["codex", "pi"] : ["codex"],+ runtime_diagnostics: runtimeDiagnostics({+ ready: piReady ? ["codex", "pi"] : ["codex"],+ }),+ });+ const model = createRuntimeModelCall({+ gateway: runtimeModelGateway(gateway),+ placements: async () => [],+ });+ try {+ expect(gateway.supportsModelInvoke("runner-local", "codex")).toBe(true);+ await expect(+ model.text({+ kind: "memory",+ key: "facts",+ input: "Room fact",+ placement: {+ tenantId: "tenant-acme",+ ownerActorId: "human-alice",+ agentId: "agent-reviewer",+ computerId: "runner-local",+ runtimeType: "pi",+ },+ }),+ ).rejects.toMatchObject({+ kind: "runtime_unavailable",+ message: expect.stringContaining("Pi"),+ });+ expect(sentInvocations(peer)).toEqual([]);+ } finally {+ model.close();+ connection.disconnect();+ }+ },+ );+it("sends model.invoke and resolves with the Daemon's outcome", async () => {const { gateway, peer, connection } = await connect();try {diff --git a/apps/node-services/tests/runtime-model-call.test.ts b/apps/node-services/tests/runtime-model-call.test.tsindex 7cf2f372..f1bff2ac 100644--- a/apps/node-services/tests/runtime-model-call.test.ts+++ b/apps/node-services/tests/runtime-model-call.test.ts@@ -301,9 +301,8 @@ describe("Runtime model call", () => {});it("falls back to the other ready Runtime, and tries its own when none is ready", async () => {- const pi = { ...alice, runtimeType: "pi" as const };const fallback = setup({- placements: [pi],+ placements: [alice],ready: (_computer, runtime) => runtime === "claude",});await fallback.modelCall.call({ ...ask, input: "x" });diff --git a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts b/contracts/generated/typescript/src/generated/runner-gateway/schema.tsindex 406b5e23..497f4a8b 100644--- a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts+++ b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts@@ -4594,7 +4594,7 @@ export const runnerGatewayEnvelopeSchema = {$ref: "#/$defs/Id",},runtime_type: {- enum: ["codex", "claude"],+ enum: ["codex", "claude", "pi"],},mode: {enum: ["structured", "text", "workspace"],diff --git a/contracts/generated/typescript/src/generated/runner-gateway/types.ts b/contracts/generated/typescript/src/generated/runner-gateway/types.tsindex 622ce0b0..19abad05 100644--- a/contracts/generated/typescript/src/generated/runner-gateway/types.ts+++ b/contracts/generated/typescript/src/generated/runner-gateway/types.ts@@ -1022,7 +1022,7 @@ export interface ModelInvoke {tenant_id: Id;owner_actor_id: Id;agent_id: Id;- runtime_type: "codex" | "claude";+ runtime_type: "codex" | "claude" | "pi";mode: "structured" | "text" | "workspace";reasoning_effort: "low" | "medium" | "high";instructions?: string;diff --git a/contracts/runner-gateway/asyncapi.yaml b/contracts/runner-gateway/asyncapi.yamlindex 6b76609b..6424c796 100644--- a/contracts/runner-gateway/asyncapi.yaml+++ b/contracts/runner-gateway/asyncapi.yaml@@ -41,8 +41,10 @@ info:shared_task_scope, and the Computer links the shared Task directory intothe playground.execute with kind model_invoke is a one-shot model call on the Computer's- signed-in Codex or Claude CLI that has no Context, takes no execution slot- and is not in the Operation ledger. The Agent Service's model scheduler+ Codex, Claude or Pi Runtime that has no Context, takes no execution slot+ and is not in the Operation ledger. A Pi call needs a loaded local default+ model and has no workspace tools. The service sends Pi calls only to a+ Computer release that can decode them. The Agent Service's model schedulerdecides when a call is sent; the Daemon runs every call it receives. Itsoptional session_key lets a Daemon answer the structured Codex calls ofone session in one resident thread; the result is the same either way.diff --git a/contracts/runner-gateway/envelope.schema.json b/contracts/runner-gateway/envelope.schema.jsonindex 706b2a0d..1b7f00cf 100644--- a/contracts/runner-gateway/envelope.schema.json+++ b/contracts/runner-gateway/envelope.schema.json@@ -4542,7 +4542,7 @@"$ref": "#/$defs/Id"},"runtime_type": {- "enum": ["codex", "claude"]+ "enum": ["codex", "claude", "pi"]},"mode": {"enum": ["structured", "text", "workspace"]diff --git a/docs/architecture.md b/docs/architecture.mdindex e98d19f6..57a34bb8 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -5,13 +5,13 @@ figure.-| Path | Carries | How |-| -------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Rooms / Chat → Computer Daemon → Runtime | messages / files, model calls | The Computer Daemon dials out over one WebSocket, so the computer opens no port to the network; files land in the Agent workspace, checked by SHA-256. Background work such as Memory and the wiki runs as one-shot calls on the same Runtime |-| Runtime ↔ Agent workspace | read, write | One per Context, that is one agent in one Room, Task or Document; `playground/` is writable, `agent/` is its own npm and uv package project, `memory/` and `llm-wiki/` are read-only |-| Runtime → LLM Gateway | model calls | The Runtime calls the LLM Gateway itself, local or remote; nothing passes through the Computer Daemon |-| Runtime → teamhub CLI ↔ Rooms / Chat | messages / files, tasks / routines / more actions | The CLI calls the server directly, and the server checks each call against the agent's current permissions |-| Runtime → Guardrail → Cua, Playwright, Shell | click, type · browse · commands, as you | Rule-based checks, then an LLM review; Cua, Playwright and the Shell then act as the user |+| Path | Carries | How |+| -------------------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Rooms / Chat → Computer Daemon → Runtime | messages / files, model calls | The Computer Daemon dials out over one WebSocket, so the computer opens no port to the network; files land in the Agent workspace, checked by SHA-256. Background work such as Memory and the Wiki uses [one-shot model calls](local-inference.md#background-memory-and-wiki) |+| Runtime ↔ Agent workspace | read, write | One per Context, that is one agent in one Room, Task or Document; `playground/` is writable, `agent/` is its own npm and uv package project, `memory/` and `llm-wiki/` are read-only |+| Runtime → LLM Gateway | model calls | The Runtime calls the LLM Gateway itself, local or remote; nothing passes through the Computer Daemon |+| Runtime → teamhub CLI ↔ Rooms / Chat | messages / files, tasks / routines / more actions | The CLI calls the server directly, and the server checks each call against the agent's current permissions |+| Runtime → Guardrail → Cua, Playwright, Shell | click, type · browse · commands, as you | Rule-based checks, then an LLM review; Cua, Playwright and the Shell then act as the user |<sub>Pi runs without review.</sub>diff --git a/docs/local-inference.md b/docs/local-inference.mdindex f740f872..62392c13 100644--- a/docs/local-inference.md+++ b/docs/local-inference.md@@ -36,6 +36,21 @@ model, and leaving Local model unloads the local models to free memory. When anagent is still working, the switch asks first and ends that work only if youconfirm.+## Background Memory and Wiki++Memory facts and reports, Agent Memory, and personal Wiki generation use the+Runtime on the Computer where the relevant Agent is placed. On Pi, these calls+require a Computer Daemon at 0.55.0 or later and a default Pi model loaded in+the local library and served over loopback. Downloaded is not Loaded. Use the+local model setup or **Settings › Models** to load the model and use it for+Agents. Background Pi calls run without tools or a saved Pi session. If Pi+or its loaded local default is unavailable, they wait or fail with a Runtime+error; they do not switch to Codex, Claude Code or a remote Pi model.++A Codex or Claude Code placement can still use the other ready Runtime on+that Computer. These calls use the chosen Runtime's default endpoint; if+that endpoint is remote, it receives the input needed for the task.+## PlanningThe planner chooses hardware and model settings together: layer by layer, thediff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex d4f05be4..b5bf891a 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -7,9 +7,13 @@ app, for example to serve several computers on your network.Docker Compose builds every service from this checkout and runs it, PostgreSQLand voice included. You need Docker with Compose. Linger needs no model-gateway or API key of its own: every model call, including the background work-of Memory and the personal wiki, runs on the Codex or Claude Code of the user's-own computer.+gateway or API key of its own. Model calls run through a Runtime on the+user's Computer, using its configured model endpoint. Memory and personal Wiki+work on Pi when its default model is loaded in the Computer's local library+and reached through the local gateway. This requires a Computer Daemon that+supports Pi background calls (0.55.0 or later), not a Codex or Claude Code login.+See [Local Inference](local-inference.md#background-memory-and-wiki) for the+background routing rules.```bashgit clone https://github.com/simplexai-labs/linger.git@@ -22,7 +26,7 @@ printf '%s\n' 'choose-a-password' | docker compose exec -T teamhub \Open <http://localhost:3000> and sign in. The app then shows the commands thatconnect your computer, and it opens once Claude Code, Codex or Pi is installed-and signed in there. With Pi and no model yet, open Settings › Models from+and ready there. With Pi and no model yet, open Settings › Models fromthat screen and load one; Settings stays reachable while the rest of the appwaits.diff --git a/scripts/runner-gateway-contract.test.ts b/scripts/runner-gateway-contract.test.tsindex e9cca19e..b4e84c23 100644--- a/scripts/runner-gateway-contract.test.ts+++ b/scripts/runner-gateway-contract.test.ts@@ -1449,7 +1449,7 @@ describe("Runner Gateway contract", () => {}});- it("accepts one-shot model invocations on Codex or Claude only", () => {+ it("accepts one-shot model invocations on Codex, Claude, and Pi", () => {expect(parseAgentToDaemonEnvelope({ ...modelInvoke, timeout_ms: 14_400_000 }),).toMatchObject({ timeout_ms: 14_400_000 });@@ -1468,8 +1468,18 @@ describe("Runner Gateway contract", () => {kind: "model_invoke",mode: "workspace",});+ expect(+ parseAgentToDaemonEnvelope({ ...modelInvoke, runtime_type: "pi" }),+ ).toMatchObject({ runtime_type: "pi", mode: "structured" });+ expect(+ parseAgentToDaemonEnvelope({+ ...withoutProperty(modelInvoke, "output_schema"),+ runtime_type: "pi",+ mode: "text",+ }),+ ).toMatchObject({ runtime_type: "pi", mode: "text" });for (const invalid of [- { ...modelInvoke, runtime_type: "pi" },+ { ...modelInvoke, runtime_type: "unsupported" },{ ...modelInvoke, protocol_version: "1.2" },{ ...modelInvoke, mode: "agent" },{ ...modelInvoke, reasoning_effort: "xhigh" },