From 0a8e94078270d09f292442356b95f67e4d785fcc Mon Sep 17 00:00:00 2001 From: LeoXing Date: Sat, 5 Dec 2026 23:14:51 +0800 Subject: [PATCH] feat(desktop,computer,agent): bundle PortableGit and enable dual bash+PowerShell on Windows Pi - Bundle SHA-256-verified PortableGit 2.56.0.4 into Windows Desktop packages (resources/runtime/git-bash/bin/bash.exe), prune GUI/docs, and add Git Bash smoke probes and release documentation. - Resolve non-WSL Git Bash in the Windows Local Computer Daemon (bundled PortableGit -> Program Files Git -> non-WSL PATH), pass LINGER_PI_GIT_BASH_PATH (consumed at load) into pi-mcp.mjs as shellPath, enforce MSYS_NO_PATHCONV=1 / MSYS2_ARG_CONV_EXCL=* / UTF-8 locale case-insensitively, and route teamhub to teamhub.exe in MINGW/Git Bash. - Negotiate dual-shell Windows Pi support via runner.welcome service_features (windows_git_bash) and post-welcome runner.runtime_diagnostics.windows_git_bash, keeping runner.hello.capabilities backward-compatible with older Agent Services and falling back to PowerShell-only on bash-less hosts or older Agent Services. - Harden PowerShell shell-text-hook against numeric/escaped dollar expansion across double quotes, here-strings, bare words, and multi-line pipes, and normalize MSYS drive paths in shellPaths.cd to preserve workspace symlink/junction checks. --- .../real-app-eval/lib/product_chain.mjs | 4 +- apps/computer/local-daemon/README.md | 26 ++- .../cmd/linger-computer-daemon/main.go | 75 +++++- .../cmd/linger-computer-daemon/main_test.go | 41 ++++ .../daemon/computer_permission_test.go | 7 + .../internal/daemon/connection.go | 26 ++- .../local-daemon/internal/daemon/daemon.go | 32 ++- .../daemon/dynamic_reasoning_efforts_test.go | 214 ++++++++++++++++++ .../internal/daemon/local_models.go | 8 + .../internal/daemon/prefix_warmup.go | 34 ++- .../internal/daemon/prefix_warmup_test.go | 64 +++++- .../internal/linger/context/resolver.go | 57 +++-- .../internal/linger/context/resolver_test.go | 185 ++++++++------- .../linger/localtools/installation.go | 101 ++++++++- .../linger/localtools/installation_test.go | 95 ++++++++ .../internal/linger/transport/gateway.go | 6 + .../internal/linger/transport/gateway_test.go | 38 +++- .../local-daemon/internal/permission/shell.go | 34 ++- .../internal/permission/shell_test.go | 64 ++++++ .../internal/permission/shell_text.go | 8 +- .../permission/shell_text_powershell.go | 157 +++++++++++-- .../permission/shell_text_powershell_test.go | 41 ++++ .../internal/permission/shell_text_test.go | 16 ++ .../local-daemon/internal/protocol/types.go | 1 + .../internal/provider/executor.go | 13 ++ .../internal/provider/native/pi_fake_test.go | 1 + .../internal/provider/native/pi_mcp.go | 2 + .../provider/native/pi_prefix_warmup.go | 6 +- .../provider/native/pi_prefix_warmup_test.go | 2 +- .../provider/native/pi_prestart_test.go | 2 +- .../internal/provider/native/pi_runtime.go | 27 ++- .../provider/native/pi_runtime_test.go | 46 +++- .../internal/provider/native/runtime.go | 7 +- apps/computer/tests/computer-tools.test.ts | 195 +++++++++++++++- apps/computer/tools/pi-mcp.mjs | 88 ++++++- apps/desktop/AGENTS.md | 10 +- apps/desktop/packaging/win/Dockerfile | 2 +- apps/desktop/packaging/win/package.py | 113 +++++++-- apps/desktop/packaging/win_git_bash_test.py | 123 ++++++++++ apps/desktop/scripts/teamhub.sh | 9 + .../src/agent/executor/activation.ts | 16 +- .../src/agent/executor/local-backend.ts | 26 +++ .../src/agent/prompt/environment-knowledge.ts | 14 +- .../runner-gateway/context-view-content.ts | 21 +- .../runner-gateway/runner-connections.ts | 30 +++ .../runner-gateway/runner-gateway-context.ts | 2 + .../agent/runner-gateway/runner-gateway.ts | 11 +- .../context-instructions.test.ts | 9 + .../tests/agent/executor/activation.test.ts | 90 ++++++++ .../agent/executor/local-backend.test.ts | 118 +++++++++- .../runner-connections-public.test.ts | 112 ++++++++- contracts/README.md | 14 +- .../generated/go/runnergateway/wire.gen.go | 1 + .../src/generated/runner-gateway/schema.ts | 6 + .../src/generated/runner-gateway/types.ts | 7 +- contracts/runner-gateway/envelope.schema.json | 7 +- docs/desktop-release.md | 9 +- scripts/ci/desktop-smoke-helpers.mjs | 6 +- scripts/ci/desktop-smoke.test.ts | 2 +- scripts/ci/windows-pi-smoke.mjs | 69 +++++- scripts/ci/windows-pi-smoke.test.ts | 47 +++- scripts/env-inventory.json | 4 +- 62 files changed, 2334 insertions(+), 267 deletions(-) create mode 100644 apps/desktop/packaging/win_git_bash_test.py diff --git a/apps/computer/benchmarks/real-app-eval/lib/product_chain.mjs b/apps/computer/benchmarks/real-app-eval/lib/product_chain.mjs index 1213c78805..11a62f717a 100644 --- a/apps/computer/benchmarks/real-app-eval/lib/product_chain.mjs +++ b/apps/computer/benchmarks/real-app-eval/lib/product_chain.mjs @@ -233,6 +233,7 @@ function resolveTsxImportUrl(nodeServicesDir, repoRoot) { export function exportNodeServicesDeveloperInstructions({ repoRoot = resolveLingerRepo(), platform = "macos", + windowsGitBash = true, instructionTier = "compact", roomKind = "direct", } = {}) { @@ -255,7 +256,8 @@ export function exportNodeServicesDeveloperInstructions({ ); const useDist = fs.existsSync(distModule); const targetUrl = pathToFileURL(useDist ? distModule : srcModule).href; - const shellDialect = platform === "windows" ? "windows-pi" : "posix"; + const shellDialect = + platform === "windows" && !windowsGitBash ? "windows-pi" : "posix"; const exporterScript = ` import { assembleExecutionContextDeveloperInstructions } from ${JSON.stringify(targetUrl)}; diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md index 2f5db42a59..c249228493 100644 --- a/apps/computer/local-daemon/README.md +++ b/apps/computer/local-daemon/README.md @@ -730,16 +730,24 @@ heredoc (`internal/permission/shell_text.go`). Named variables such as `"$id"`, `pipefail`, a producer killed by `SIGPIPE` when a downstream reader closes early (such as `| head`, exit `141`) or a non-zero upstream stage (such as `grep` with no matches piped to `wc -l`) fails the pipeline; a command that - wants to ignore upstream failures can run `set +o pipefail`. On Windows, Pi - uses the built-in `powershell` tool instead of `bash`, so it skips `pipefail` - and the managed extension overrides `powershell` to set UTF-8 - `$OutputEncoding` and console encodings. Windows Pi also passes + wants to ignore upstream failures can run `set +o pipefail`. On Windows, when + a non-WSL Git Bash runtime (bundled PortableGit or installed Git for Windows) + is available and the connected Agent Service advertises `windows_git_bash` in + `runner.welcome.service_features`, Pi exposes both `bash` (with `pipefail`, + explicit `shellPath` via `LINGER_PI_GIT_BASH_PATH`, `MSYS_NO_PATHCONV=1`, + `MSYS2_ARG_CONV_EXCL=*`, UTF-8 locale defaults, and `teamhub` → `teamhub.exe` + dispatch) and `powershell` (overridden to set UTF-8 `$OutputEncoding` and + console encodings); on bash-less hosts or older Agent Services, Windows Pi + falls back to `powershell` only (skipping `pipefail`). Windows Pi also passes `LINGER_PI_SHELL_TEXT_HOOK` so the extension invokes - `linger-computer-daemon shell-text-hook` with `tool_name: "powershell"` and - `powershell_51` for `teamhub` commands containing `"` or `<<`, refusing POSIX - heredocs (`<<'EOF'`) on all PowerShell versions and embedded double quotes in - native `teamhub` arguments (outside PowerShell here-strings) on Windows - PowerShell 5.1 (`powershell.exe`). Across `bash`, `powershell`, and + `linger-computer-daemon shell-text-hook` for both `bash` and `powershell` + calls (`powershell` passes `tool_name: "powershell"` and `powershell_51` for + `teamhub` commands containing `"`, `<<`, or `$`), refusing + POSIX heredocs (`<<'EOF'`), unescaped numeric dollar amounts (`$6` in + `"$6.4M"`), and bash-escaped `\$` in double quotes, double-quoted + here-strings (`@"..."@`), or bare words on all PowerShell versions, plus + embedded double quotes in native `teamhub` arguments (outside PowerShell + here-strings) on Windows PowerShell 5.1 (`powershell.exe`). Across `bash`, `powershell`, and `mcp__computer__ui_exec`, `pi-mcp.mjs` also runs a per-Run consecutive-failure loop guard (reset on `before_agent_start`, exempting `--help`/`-h`/`--schema` on shell tools and pure `ui.help(...)` on `ui_exec`, and never cleared by diff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go index f0f7bf19a1..a089a5e946 100644 --- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go +++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go @@ -184,12 +184,23 @@ func run(args []string) (resultErr error) { if err != nil { return err } + var bundledGitBashPath string if toolInstallation == nil { // Agents on this computer then have no browser or computer-control // tools; say so instead of leaving them silently missing. slog.Warn("computer_tools.missing: browser and computer-control tools are disabled", "expected", localtools.ToolsDirectory(executable)) - } else if toolInstallation.PowerShellPath != "" { - baseProviderEnvironment = withBundledPowerShellPath(baseProviderEnvironment, toolInstallation.PowerShellPath, runtime.GOOS) + } else { + if toolInstallation.PowerShellPath != "" { + baseProviderEnvironment = withBundledPowerShellPath(baseProviderEnvironment, toolInstallation.PowerShellPath, runtime.GOOS) + } + bundledGitBashPath = toolInstallation.GitBashPath + } + var resolvedGitBashPath string + if runtime.GOOS == "windows" { + resolvedGitBashPath = localtools.ResolveWindowsGitBash(bundledGitBashPath, baseProviderEnvironment) + if resolvedGitBashPath != "" { + baseProviderEnvironment = withBundledGitBashPath(baseProviderEnvironment, resolvedGitBashPath, runtime.GOOS) + } } localModelsStateDir := resolveLocalModelsStateDir(computer, environment) currentProviderEnvironment := func() map[string]string { @@ -377,12 +388,16 @@ func run(args []string) (resultErr error) { if !filepath.IsAbs(teamhubCLINodePath) { teamhubCLINodePath = "" } + windowsGitBashEnabled := func() bool { + return localDaemon != nil && localDaemon.WindowsGitBashActive() + } resolver := lingercontext.ExecutionResolver{ - ServiceCommand: serviceCommand, - TeamHubCLIBin: teamhubBin, - TeamHubCLINodePath: teamhubCLINodePath, - HostEnvironmentGuide: hostEnvironmentGuide(runtime.GOOS), - ProviderLookup: providerCatalog.Lookup, WorkspaceGrants: workspaceGrants, Views: views, + ServiceCommand: serviceCommand, + TeamHubCLIBin: teamhubBin, + TeamHubCLINodePath: teamhubCLINodePath, + HostEnvironmentGuide: hostEnvironmentGuide(runtime.GOOS), + WindowsGitBashEnabled: windowsGitBashEnabled, + ProviderLookup: providerCatalog.Lookup, WorkspaceGrants: workspaceGrants, Views: views, CLICredentials: cliCredentials, RegistrationLookup: func(ctx context.Context, registrationID string) (lingercontext.RegistrationBinding, bool, error) { items, err := registrationStore.List(ctx) @@ -482,8 +497,15 @@ func run(args []string) (resultErr error) { ToolGuide: resolver.ToolGuide, HostEnvironmentGuide: resolver.HostEnvironmentGuide, TeamHubCLI: teamhubBin != "", - TempBase: operationTempBase, - WarmupMCPServers: warmupMCPServers, + WindowsGitBashPath: resolvedGitBashPath, + WindowsGitBashReport: func() *bool { + if localDaemon == nil { + return nil + } + return localDaemon.WindowsGitBashReport() + }, + TempBase: operationTempBase, + WarmupMCPServers: warmupMCPServers, }).Warmup localSpeech := localmodels.NewSpeech(localmodels.SpeechOptions{ ToolHandle: localModelsToolHandle, @@ -539,6 +561,11 @@ func run(args []string) (resultErr error) { if localModelsTool != nil { downloadSourceFile = localmodels.RegionFile(localModelsTool.StateDirectory) } + var daemonWindowsGitBash *bool + if runtime.GOOS == "windows" { + hasGitBash := resolvedGitBashPath != "" + daemonWindowsGitBash = &hasGitBash + } localDaemon, err = daemon.New(daemon.Options{ ComputerID: computer.ComputerID, DisplayName: computer.DisplayName, Runtimes: runtimes, @@ -558,6 +585,8 @@ func run(args []string) (resultErr error) { TempBase: operationTempBase, RuntimeHomeRoot: filepath.Join(computer.StateDirectory, "runtime-homes"), CodexModelSessionHome: codexModelSessions.Home(), PiMCPExtension: piExtension, + WindowsGitBashPath: resolvedGitBashPath, + WindowsGitBashEnabled: windowsGitBashEnabled, ManagedPiRoots: managedPiRoots.Roots, WithPiSettingsSync: withPiSettingsSync, ShellTextHook: executable, @@ -568,6 +597,7 @@ func run(args []string) (resultErr error) { ComputerPermissions: localtools.NewComputerPermissions(permissionOptions), CLICredentials: cliCredentials, TeamHubCLIBin: teamhubBin, + WindowsGitBash: daemonWindowsGitBash, LocalModels: localModels, DownloadSourceFile: downloadSourceFile, DownloadSourceEnv: baseProviderEnvironment, @@ -1254,7 +1284,30 @@ func bundledRuntimePaths(installation *localtools.Installation) map[string]strin } func withBundledPowerShellPath(env map[string]string, powerShellPath, goos string) map[string]string { - if goos != "windows" || strings.TrimSpace(powerShellPath) == "" { + return withBundledWindowsRuntimeDir(env, powerShellPath, goos) +} + +func setEnvFold(env map[string]string, name, value string) { + for key := range env { + if strings.EqualFold(key, name) { + delete(env, key) + } + } + env[name] = value +} + +func withBundledGitBashPath(env map[string]string, gitBashPath, goos string) map[string]string { + if goos != "windows" || strings.TrimSpace(gitBashPath) == "" { + return env + } + updated := withBundledWindowsRuntimeDir(env, gitBashPath, goos) + setEnvFold(updated, "MSYS_NO_PATHCONV", "1") + setEnvFold(updated, "MSYS2_ARG_CONV_EXCL", "*") + return updated +} + +func withBundledWindowsRuntimeDir(env map[string]string, executablePath, goos string) map[string]string { + if goos != "windows" || strings.TrimSpace(executablePath) == "" { return env } cloned := maps.Clone(env) @@ -1277,7 +1330,7 @@ func withBundledPowerShellPath(env map[string]string, powerShellPath, goos strin existing = provider.AppendWindowsSearchPath(existing, cloned[key]) delete(cloned, key) } - cloned["PATH"] = provider.AppendWindowsSearchPath(existing, filepath.Dir(powerShellPath)) + cloned["PATH"] = provider.AppendWindowsSearchPath(existing, filepath.Dir(executablePath)) return cloned } diff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go index 001e1eaf1e..4380983bef 100644 --- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go +++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go @@ -2262,6 +2262,47 @@ func TestWithBundledPowerShellPath(t *testing.T) { } } +func TestWithBundledGitBashPath(t *testing.T) { + binDir := filepath.Join(t.TempDir(), "runtime", "git-bash", "bin") + bashPath := filepath.Join(binDir, "bash.exe") + + env := map[string]string{"Path": `C:\Windows\System32;C:\Users\alice\bin`} + updated := withBundledGitBashPath(env, bashPath, "windows") + if got, want := updated["PATH"], `C:\Windows\System32;C:\Users\alice\bin;`+binDir; got != want { + t.Fatalf("updated Windows PATH = %q, want %q", got, want) + } + if updated["MSYS_NO_PATHCONV"] != "1" || updated["MSYS2_ARG_CONV_EXCL"] != "*" { + t.Fatalf("missing MSYS pathconv disable vars: %+v", updated) + } + if env["MSYS_NO_PATHCONV"] != "" { + t.Fatalf("caller environment map mutated: %+v", env) + } + + // Inherited lowercase variants are replaced case-insensitively on Windows. + lowerEnv := map[string]string{ + "Path": `C:\Windows\System32`, + "msys_no_pathconv": "0", + "msys2_arg_conv_excl": "", + } + overridden := withBundledGitBashPath(lowerEnv, bashPath, "windows") + if overridden["MSYS_NO_PATHCONV"] != "1" || overridden["MSYS2_ARG_CONV_EXCL"] != "*" { + t.Fatalf("case-insensitive override failed: %+v", overridden) + } + if _, dup := overridden["msys_no_pathconv"]; dup { + t.Fatalf("lowercase duplicate msys_no_pathconv survived: %+v", overridden) + } + if _, dup := overridden["msys2_arg_conv_excl"]; dup { + t.Fatalf("lowercase duplicate msys2_arg_conv_excl survived: %+v", overridden) + } + + if got := withBundledGitBashPath(env, bashPath, "linux"); !reflect.DeepEqual(got, env) { + t.Fatalf("non-Windows modified env: %+v", got) + } + if got := withBundledGitBashPath(env, "", "windows"); !reflect.DeepEqual(got, env) { + t.Fatalf("empty git-bash path modified env: %+v", got) + } +} + func TestSyncManagedPiCompactionThresholdsUsesWithPiSettingsSync(t *testing.T) { stateDir := filepath.Join(t.TempDir(), "localmodels", "state") agentDir := filepath.Join(stateDir, "gateway-home", ".pi", "agent") diff --git a/apps/computer/local-daemon/internal/daemon/computer_permission_test.go b/apps/computer/local-daemon/internal/daemon/computer_permission_test.go index 33a19b1815..b91e91ca1b 100644 --- a/apps/computer/local-daemon/internal/daemon/computer_permission_test.go +++ b/apps/computer/local-daemon/internal/daemon/computer_permission_test.go @@ -124,4 +124,11 @@ func TestComputerPermissionsCapabilityIsAlwaysAdvertised(t *testing.T) { if got := d.capabilities(); len(got) != 2 || got[0] != "computer_permissions" || got[1] != "browser_connection" { t.Fatalf("capabilities = %v", got) } + // runner.hello.capabilities stays restricted to the closed legacy enum so + // older Agent Services never disconnect on an unknown capability. + enabled := true + dBash := &Daemon{browserConnections: &deadlineBrowserConnections{}, windowsGitBash: &enabled} + if got := dBash.capabilities(); len(got) != 2 || got[0] != "computer_permissions" || got[1] != "browser_connection" { + t.Fatalf("capabilities with windowsGitBash = %v, want legacy capability set only", got) + } } diff --git a/apps/computer/local-daemon/internal/daemon/connection.go b/apps/computer/local-daemon/internal/daemon/connection.go index 3912d0ef2d..46b9d17e2f 100644 --- a/apps/computer/local-daemon/internal/daemon/connection.go +++ b/apps/computer/local-daemon/internal/daemon/connection.go @@ -388,8 +388,6 @@ func (d *Daemon) acceptRunnerWelcome(ctx, connectionCtx context.Context, stream } d.connectionEpoch = command.ConnectionEpoch d.recordWelcomedEpoch(command.ConnectionEpoch) - contentURL := command.ContextContentURL - d.contentURL.Store(&contentURL) d.welcomeSeen = true d.welcomedAt = time.Now() if d.selfUpdate != nil { @@ -422,6 +420,7 @@ func (d *Daemon) acceptRunnerWelcome(ctx, connectionCtx context.Context, stream d.runtimeFailureDetail.Store(slices.Contains(command.ServiceFeatures, serviceFeatureRuntimeFailureDetail)) d.operationBackgroundWait.Store(slices.Contains(command.ServiceFeatures, serviceFeatureOperationBackgroundWait)) d.dynamicReasoningEfforts.Store(slices.Contains(command.ServiceFeatures, serviceFeatureDynamicReasoningEfforts)) + d.windowsGitBashFeature.Store(slices.Contains(command.ServiceFeatures, serviceFeatureWindowsGitBash)) d.antigravityHistory.Store(slices.Contains(command.ServiceFeatures, serviceFeatureAntigravityHistory)) d.antigravityUsageProvider.Store(slices.Contains(command.ServiceFeatures, serviceFeatureAntigravityUsageProvider)) d.piUsageProvider.Store(slices.Contains(command.ServiceFeatures, serviceFeaturePiUsageProvider)) @@ -434,6 +433,11 @@ func (d *Daemon) acceptRunnerWelcome(ctx, connectionCtx context.Context, stream if err := d.activateStreamAndReplay(ctx, stream, command.ReconcileOperationIDs, localModels, helloRev); err != nil { return err } + // Publish contentURL only after welcome service_features and post-welcome + // diagnostics have been recorded and sent, so background prefix warm-up + // never observes a new contentURL with stale feature flags. + contentURL := command.ContextContentURL + d.contentURL.Store(&contentURL) d.setLocalSpeechStream(stream, localVoiceAsr) d.setLocalTtsStream(stream, localVoiceTts) go d.heartbeatLoop(connectionCtx, stream, command.HeartbeatIntervalMs) @@ -505,7 +509,8 @@ func (d *Daemon) UpdateRuntimeInventory(ctx context.Context, runtimes []string, if err := d.diagnosticsStream.Send(ctx, protocol.Event{ Type: protocol.EventRuntimeDiagnostics, ProtocolVersion: d.protocolVersion, RunnerID: d.computerID, Revision: revision, SentAt: time.Now().UTC(), - Payload: payload, + WindowsGitBash: d.WindowsGitBashReport(), + Payload: payload, }); err != nil { return err } @@ -609,6 +614,7 @@ func (d *Daemon) clearDiagnosticsStream(stream transport.Stream) { d.runtimeFailureDetail.Store(false) d.operationBackgroundWait.Store(false) d.dynamicReasoningEfforts.Store(false) + d.windowsGitBashFeature.Store(false) d.antigravityHistory.Store(false) d.antigravityUsageProvider.Store(false) d.piUsageProvider.Store(false) @@ -775,9 +781,10 @@ func (d *Daemon) setLocalTtsStream(stream transport.Stream, enabled bool) { // activateStreamAndReplay makes stream the live connection; localModels says // whether its Agent Service accepts runner.local_models. It publishes the -// latest runtime diagnostics when inventory advanced after runner.hello or -// when the Agent Service advertises dynamic_reasoning_efforts and runner.hello -// filtered out non-legacy efforts. +// latest runtime diagnostics when inventory advanced after runner.hello, when +// the Agent Service advertises dynamic_reasoning_efforts and runner.hello +// filtered out non-legacy efforts, or when a Windows Computer reports +// negotiated windows_git_bash availability. func (d *Daemon) activateStreamAndReplay(ctx context.Context, stream transport.Stream, operationIDs []string, localModels bool, helloRev uint64) error { d.connectionMu.Lock() defer d.connectionMu.Unlock() @@ -792,6 +799,7 @@ func (d *Daemon) activateStreamAndReplay(ctx context.Context, stream transport.S return err } allowDynamicEfforts := d.dynamicReasoningEfforts.Load() + reportWindowsGitBash := d.WindowsGitBashReport() // Lock order is strictly connectionMu -> inventoryMu; never invert. d.inventoryMu.Lock() latestRev := d.diagnosticsRevision @@ -799,7 +807,8 @@ func (d *Daemon) activateStreamAndReplay(ctx context.Context, stream transport.S _, filtered := filterLegacyReasoningEffortsJSON(d.runtimeDiagnostics) needPublish := len(latestDiag) > 0 && ((helloRev != 0 && latestRev > d.sentDiagnosticsRevision) || - (allowDynamicEfforts && filtered)) + (allowDynamicEfforts && filtered) || + reportWindowsGitBash != nil) if needPublish && latestRev <= d.sentDiagnosticsRevision { d.diagnosticsRevision = nextRevisionAbove(saturatingIncrement(d.diagnosticsRevision), d.runtimeObservations) latestRev = d.diagnosticsRevision @@ -812,7 +821,8 @@ func (d *Daemon) activateStreamAndReplay(ctx context.Context, stream transport.S if err := stream.Send(ctx, protocol.Event{ Type: protocol.EventRuntimeDiagnostics, ProtocolVersion: d.protocolVersion, RunnerID: d.computerID, Revision: latestRev, SentAt: time.Now().UTC(), - Payload: latestDiag, + WindowsGitBash: reportWindowsGitBash, + Payload: latestDiag, }); err != nil { return err } diff --git a/apps/computer/local-daemon/internal/daemon/daemon.go b/apps/computer/local-daemon/internal/daemon/daemon.go index 8e897186fb..70bd318fe2 100644 --- a/apps/computer/local-daemon/internal/daemon/daemon.go +++ b/apps/computer/local-daemon/internal/daemon/daemon.go @@ -47,7 +47,10 @@ type Options struct { CLICredentials *clicredential.Store // TeamHubCLIBin is the bundled TeamHub CLI directory; live voice cards // post through it as the Agent. - TeamHubCLIBin string + TeamHubCLIBin string + // WindowsGitBash reports whether a usable non-WSL Git Bash executable is + // available on this Windows Computer. Nil indicates a non-Windows Computer. + WindowsGitBash *bool ComputerID string OperationResolver OperationResolver RetryDelay func(attempt int) time.Duration @@ -133,6 +136,7 @@ type Daemon struct { computerPermissions ComputerPermissions owners []ComputerOwner cliCredentials *clicredential.Store + windowsGitBash *bool teamhubCLIBin string onModelUnavailable func(runtimeType, modelID string) modelInvokeUnready func(runtimeType string) bool @@ -214,6 +218,9 @@ type Daemon struct { // dynamicReasoningEfforts holds whether the current Agent Service declared // serviceFeatureDynamicReasoningEfforts in its welcome. dynamicReasoningEfforts atomic.Bool + // windowsGitBashFeature holds whether the current Agent Service declared + // serviceFeatureWindowsGitBash in its welcome. + windowsGitBashFeature atomic.Bool // antigravityHistory holds whether the current Agent Service declared // serviceFeatureAntigravityHistory in its welcome. antigravityHistory atomic.Bool @@ -359,6 +366,11 @@ func New(options Options) (*Daemon, error) { if options.Ledger == nil || options.Registrations == nil || options.Assignments == nil { return nil, errors.New("daemon requires Operation, Registration and Assignment stores") } + var windowsGitBash *bool + if options.WindowsGitBash != nil { + enabled := *options.WindowsGitBash + windowsGitBash = &enabled + } return &Daemon{ controlPlane: options.ControlPlane, identityStore: options.IdentityStore, @@ -409,6 +421,7 @@ func New(options Options) (*Daemon, error) { computerPermissions: options.ComputerPermissions, owners: options.Owners, cliCredentials: options.CLICredentials, + windowsGitBash: windowsGitBash, teamhubCLIBin: options.TeamHubCLIBin, openMCPProxies: mcpproxy.Open, onModelUnavailable: options.OnModelUnavailable, @@ -416,6 +429,23 @@ func New(options Options) (*Daemon, error) { }, nil } +// WindowsGitBashActive reports whether this Computer has a usable non-WSL Git +// Bash executable and the connected Agent Service negotiated windows_git_bash. +func (d *Daemon) WindowsGitBashActive() bool { + return d.windowsGitBash != nil && *d.windowsGitBash && d.windowsGitBashFeature.Load() +} + +// WindowsGitBashReport returns the negotiated windows_git_bash state to +// advertise on Windows Computers, or nil on non-Windows Computers or when the +// connected Agent Service did not advertise windows_git_bash. +func (d *Daemon) WindowsGitBashReport() *bool { + if d.windowsGitBash == nil || !d.windowsGitBashFeature.Load() { + return nil + } + enabled := *d.windowsGitBash + return &enabled +} + // Run loads or creates the Daemon Identity and keeps the Gateway stream // connected until ctx ends or a terminal configuration error stops redials. func (d *Daemon) Run(ctx context.Context) error { diff --git a/apps/computer/local-daemon/internal/daemon/dynamic_reasoning_efforts_test.go b/apps/computer/local-daemon/internal/daemon/dynamic_reasoning_efforts_test.go index 76f38302f8..c0387aa8fc 100644 --- a/apps/computer/local-daemon/internal/daemon/dynamic_reasoning_efforts_test.go +++ b/apps/computer/local-daemon/internal/daemon/dynamic_reasoning_efforts_test.go @@ -6,6 +6,7 @@ import ( "errors" "io" "reflect" + "slices" "sync" "testing" "time" @@ -87,6 +88,219 @@ func TestDaemonFiltersDynamicReasoningEffortsForLegacyServicesAndPublishesAfterW } }) + t.Run("welcome negotiates windows_git_bash post-welcome without mutating runner.hello capabilities", func(t *testing.T) { + piDiagnostics := json.RawMessage(`[{"type":"pi","status":"ready","protocol":"rpc","checked_at":"2026-11-25T00:00:00Z","models":[{"id":"local/qwen","label":"Qwen"}]}]`) + boolPtr := func(value bool) *bool { return &value } + + t.Run("with windows_git_bash service feature", func(t *testing.T) { + device, err := transport.GenerateIdentity() + if err != nil { + t.Fatal(err) + } + stream := &fakeStream{commands: []protocol.Command{ + {Type: protocol.CommandRunnerWelcome, ConnectionEpoch: 1, ServiceFeatures: []string{serviceFeatureWindowsGitBash}}, + }} + cp := &recordingControlPlane{stream: stream} + d, err := newTestDaemon(t, Options{ + ComputerID: "computer-1", + OperationResolver: fakeOperationResolver{}, + ControlPlane: cp, + IdentityStore: fakeStore{value: device}, + Runtimes: []string{"pi"}, + RuntimeDiagnostics: piDiagnostics, + WindowsGitBash: boolPtr(true), + }) + if err != nil { + t.Fatal(err) + } + d.daemonID = device.DaemonID + if err := d.runConnection(context.Background(), device); !errors.Is(err, io.EOF) { + t.Fatalf("runConnection() = %v, want EOF", err) + } + if d.WindowsGitBashActive() || d.WindowsGitBashReport() != nil { + t.Fatal("WindowsGitBash state was not cleared after disconnect") + } + if len(cp.hellos) != 1 || slices.Contains(cp.hellos[0].Capabilities, serviceFeatureWindowsGitBash) { + t.Fatalf("runner.hello capabilities leaked windows_git_bash: %+v", cp.hellos) + } + var diagEvents []protocol.Event + for _, event := range stream.snapshotEvents() { + if event.Type == protocol.EventRuntimeDiagnostics { + diagEvents = append(diagEvents, event) + } + } + if len(diagEvents) != 1 || diagEvents[0].WindowsGitBash == nil || !*diagEvents[0].WindowsGitBash { + t.Fatalf("post-welcome runtime_diagnostics = %+v, want 1 event with WindowsGitBash=true", diagEvents) + } + }) + + t.Run("with windows_git_bash service feature and Git Bash unavailable reports false", func(t *testing.T) { + device, err := transport.GenerateIdentity() + if err != nil { + t.Fatal(err) + } + release := make(chan struct{}) + stream := &fakeStream{ + commands: []protocol.Command{ + {Type: protocol.CommandRunnerWelcome, ConnectionEpoch: 1, ServiceFeatures: []string{serviceFeatureWindowsGitBash}}, + }, + wait: release, + } + cp := &recordingControlPlane{stream: stream} + d, err := newTestDaemon(t, Options{ + ComputerID: "computer-1", + OperationResolver: fakeOperationResolver{}, + ControlPlane: cp, + IdentityStore: fakeStore{value: device}, + Runtimes: []string{"pi"}, + RuntimeDiagnostics: piDiagnostics, + WindowsGitBash: boolPtr(false), + }) + if err != nil { + t.Fatal(err) + } + d.daemonID = device.DaemonID + done := make(chan error, 1) + go func() { done <- d.runConnection(context.Background(), device) }() + waitForEvents(t, stream, 2) + if d.WindowsGitBashActive() { + t.Fatal("WindowsGitBashActive = true when host has no Git Bash") + } + if report := d.WindowsGitBashReport(); report == nil || *report { + t.Fatalf("WindowsGitBashReport() = %v, want false", report) + } + if err := d.UpdateRuntimeInventory(context.Background(), []string{"pi"}, piDiagnostics, nil); err != nil { + t.Fatal(err) + } + waitForEvents(t, stream, 3) + var diagEvents []protocol.Event + for _, event := range stream.snapshotEvents() { + if event.Type == protocol.EventRuntimeDiagnostics { + diagEvents = append(diagEvents, event) + } + } + if len(diagEvents) != 2 { + t.Fatalf("runtime_diagnostics event count = %d, want 2", len(diagEvents)) + } + for i, event := range diagEvents { + if event.WindowsGitBash == nil || *event.WindowsGitBash { + t.Fatalf("diagEvents[%d].WindowsGitBash = %v, want explicit false", i, event.WindowsGitBash) + } + } + close(release) + if err := <-done; !errors.Is(err, io.EOF) { + t.Fatalf("runConnection() = %v, want EOF", err) + } + }) + + t.Run("without windows_git_bash service feature stays PowerShell-only", func(t *testing.T) { + device, err := transport.GenerateIdentity() + if err != nil { + t.Fatal(err) + } + release := make(chan struct{}) + stream := &fakeStream{ + commands: []protocol.Command{ + {Type: protocol.CommandRunnerWelcome, ConnectionEpoch: 1}, + }, + wait: release, + } + cp := &recordingControlPlane{stream: stream} + d, err := newTestDaemon(t, Options{ + ComputerID: "computer-1", + OperationResolver: fakeOperationResolver{}, + ControlPlane: cp, + IdentityStore: fakeStore{value: device}, + Runtimes: []string{"pi"}, + RuntimeDiagnostics: piDiagnostics, + WindowsGitBash: boolPtr(true), + }) + if err != nil { + t.Fatal(err) + } + d.daemonID = device.DaemonID + done := make(chan error, 1) + go func() { done <- d.runConnection(context.Background(), device) }() + waitForEvents(t, stream, 1) + if d.WindowsGitBashActive() || d.WindowsGitBashReport() != nil { + t.Fatal("WindowsGitBash active/reported against legacy Agent Service without windows_git_bash") + } + if err := d.UpdateRuntimeInventory(context.Background(), []string{"pi"}, piDiagnostics, nil); err != nil { + t.Fatal(err) + } + waitForEvents(t, stream, 2) + var diagCount int + for _, event := range stream.snapshotEvents() { + if event.Type == protocol.EventRuntimeDiagnostics { + diagCount++ + if event.WindowsGitBash != nil { + t.Fatalf("legacy Agent Service unexpectedly received windows_git_bash: %+v", event) + } + } + } + if diagCount != 1 { + t.Fatalf("runtime_diagnostics event count = %d, want 1 (update only)", diagCount) + } + close(release) + if err := <-done; !errors.Is(err, io.EOF) { + t.Fatalf("runConnection() = %v, want EOF", err) + } + }) + + t.Run("non-Windows Computer omits windows_git_bash even when service feature is advertised", func(t *testing.T) { + device, err := transport.GenerateIdentity() + if err != nil { + t.Fatal(err) + } + release := make(chan struct{}) + stream := &fakeStream{ + commands: []protocol.Command{ + {Type: protocol.CommandRunnerWelcome, ConnectionEpoch: 1, ServiceFeatures: []string{serviceFeatureWindowsGitBash}}, + }, + wait: release, + } + cp := &recordingControlPlane{stream: stream} + d, err := newTestDaemon(t, Options{ + ComputerID: "computer-1", + OperationResolver: fakeOperationResolver{}, + ControlPlane: cp, + IdentityStore: fakeStore{value: device}, + Runtimes: []string{"pi"}, + RuntimeDiagnostics: piDiagnostics, + }) + if err != nil { + t.Fatal(err) + } + d.daemonID = device.DaemonID + done := make(chan error, 1) + go func() { done <- d.runConnection(context.Background(), device) }() + waitForEvents(t, stream, 1) + if d.WindowsGitBashActive() || d.WindowsGitBashReport() != nil { + t.Fatal("non-Windows Computer unexpectedly reported windows_git_bash") + } + if err := d.UpdateRuntimeInventory(context.Background(), []string{"pi"}, piDiagnostics, nil); err != nil { + t.Fatal(err) + } + waitForEvents(t, stream, 2) + var diagCount int + for _, event := range stream.snapshotEvents() { + if event.Type == protocol.EventRuntimeDiagnostics { + diagCount++ + if event.WindowsGitBash != nil { + t.Fatalf("non-Windows Computer leaked windows_git_bash: %+v", event) + } + } + } + if diagCount != 1 { + t.Fatalf("runtime_diagnostics event count = %d, want 1 (update only)", diagCount) + } + close(release) + if err := <-done; !errors.Is(err, io.EOF) { + t.Fatalf("runConnection() = %v, want EOF", err) + } + }) + }) + t.Run("welcome without dynamic_reasoning_efforts keeps legacy filtering", func(t *testing.T) { device, err := transport.GenerateIdentity() if err != nil { diff --git a/apps/computer/local-daemon/internal/daemon/local_models.go b/apps/computer/local-daemon/internal/daemon/local_models.go index a12276fd2e..e66c8839e8 100644 --- a/apps/computer/local-daemon/internal/daemon/local_models.go +++ b/apps/computer/local-daemon/internal/daemon/local_models.go @@ -131,6 +131,14 @@ const legacyLocalModelsSnapshotMaxItems = 256 // stage loading_local_model while EnsureLoaded wakes a standby model. const serviceFeatureLocalModelLoadingStatus = "local_model_loading_status" +// serviceFeatureWindowsGitBash in runner.welcome's service_features says the +// Agent Service accepts windows_git_bash on post-welcome +// runner.runtime_diagnostics frames and serves POSIX-dialect prompts for +// Windows Pi when reported true. Older Agent Services close the connection on +// unknown runner.hello capabilities or runner.runtime_diagnostics fields, so +// Windows Pi stays on PowerShell-only unless this feature is advertised. +const serviceFeatureWindowsGitBash = "windows_git_bash" + // LocalModelLibrary runs the actions a Computer owner chooses on this // Computer's localmodels library. The Daemon never picks a model: on its // own it loads only the downloaded model a Run's Agent already names, and it diff --git a/apps/computer/local-daemon/internal/daemon/prefix_warmup.go b/apps/computer/local-daemon/internal/daemon/prefix_warmup.go index e886fe8a71..f0788fb989 100644 --- a/apps/computer/local-daemon/internal/daemon/prefix_warmup.go +++ b/apps/computer/local-daemon/internal/daemon/prefix_warmup.go @@ -57,6 +57,8 @@ type PrefixWarmupRunner struct { ToolGuide string HostEnvironmentGuide string TeamHubCLI bool + WindowsGitBashPath string + WindowsGitBashReport func() *bool TempBase string HTTPClient *http.Client Timeout time.Duration @@ -83,7 +85,22 @@ func (r *PrefixWarmupRunner) Warmup(ctx context.Context, target localmodels.Pref return false, nil } - bundle, supported, err := r.staticPrefixes(ctx, contentURL) + activeGitBashPath := strings.TrimSpace(r.WindowsGitBashPath) + var queryGitBash *bool + if r.WindowsGitBashReport != nil { + report := r.WindowsGitBashReport() + if report == nil || !*report { + activeGitBashPath = "" + } + if report != nil { + enabled := *report && activeGitBashPath != "" + queryGitBash = &enabled + } + } else if activeGitBashPath != "" { + enabled := true + queryGitBash = &enabled + } + bundle, supported, err := r.staticPrefixes(ctx, contentURL, queryGitBash) if err != nil { return false, err } @@ -106,7 +123,7 @@ func (r *PrefixWarmupRunner) Warmup(ctx context.Context, target localmodels.Pref alterEgoPrefix = bundle.Prefixes.AlterEgo.Compact } - guides := lingercontext.PiDaemonStaticGuides(r.ServiceCommand, r.ToolGuide, r.HostEnvironmentGuide, true, true, r.TeamHubCLI) + guides := lingercontext.PiDaemonStaticGuides(r.ServiceCommand, r.ToolGuide, r.HostEnvironmentGuide, true, true, r.TeamHubCLI, activeGitBashPath != "") if r.TempBase != "" { if err := os.MkdirAll(r.TempBase, 0o700); err != nil { return false, fmt.Errorf("create prefix warm-up temp root: %w", err) @@ -142,6 +159,7 @@ func (r *PrefixWarmupRunner) Warmup(ctx context.Context, target localmodels.Pref Env: install.Environment, Logger: slog.Default(), ManagedMCPExtension: r.ManagedMCPExtension, + WindowsGitBashPath: activeGitBashPath, } run := r.RunWarmup if run == nil { @@ -183,10 +201,18 @@ func (r *PrefixWarmupRunner) httpClient() *http.Client { return defaultPrefixFetchClient } -func (r *PrefixWarmupRunner) staticPrefixes(ctx context.Context, contentURL string) (staticPrefixBundle, bool, error) { +func (r *PrefixWarmupRunner) staticPrefixes(ctx context.Context, contentURL string, windowsGitBash *bool) (staticPrefixBundle, bool, error) { reqCtx, cancel := context.WithTimeout(ctx, defaultPrefixFetchTimeout) defer cancel() - request, err := http.NewRequestWithContext(reqCtx, http.MethodGet, contentURL+"/static-prefixes/v1", nil) + endpoint := contentURL + "/static-prefixes/v1" + if windowsGitBash != nil { + if *windowsGitBash { + endpoint += "?windows_git_bash=1" + } else { + endpoint += "?windows_git_bash=0" + } + } + request, err := http.NewRequestWithContext(reqCtx, http.MethodGet, endpoint, nil) if err != nil { return staticPrefixBundle{}, false, err } diff --git a/apps/computer/local-daemon/internal/daemon/prefix_warmup_test.go b/apps/computer/local-daemon/internal/daemon/prefix_warmup_test.go index fc803fa478..bf0068c36c 100644 --- a/apps/computer/local-daemon/internal/daemon/prefix_warmup_test.go +++ b/apps/computer/local-daemon/internal/daemon/prefix_warmup_test.go @@ -234,7 +234,7 @@ func TestPrefixWarmupRunnerSelectsVariantAndCleansTempDir(t *testing.T) { }, } - guides := lingercontext.PiDaemonStaticGuides(serviceCommand, toolGuide, hostGuide, true, true, true) + guides := lingercontext.PiDaemonStaticGuides(serviceCommand, toolGuide, hostGuide, true, true, true, false) // <= 128K selects compact variants. done, err := runner.Warmup(t.Context(), localmodels.PrefixWarmupTarget{ @@ -353,7 +353,7 @@ func TestPrefixWarmupRunnerSelectsMinimalVariantWithCompactFallback(t *testing.T }, } - guides := lingercontext.PiDaemonStaticGuides(nil, "ToolGuide", "", true, true, true) + guides := lingercontext.PiDaemonStaticGuides(nil, "ToolGuide", "", true, true, true, false) done, err := runner.Warmup(t.Context(), localmodels.PrefixWarmupTarget{ ModelID: "model-16k", PiModel: "localmodels/model-16k", @@ -450,3 +450,63 @@ func TestPrefixWarmupRunnerOpensAndClosesMCPServersOnce(t *testing.T) { t.Fatalf("mcpConfigs = %q, want %s for both pins", seenConfigs, wantMCP) } } + +func TestPrefixWarmupRunnerPassesWindowsGitBashQueryParamWhenNegotiated(t *testing.T) { + var seenQueries []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/conn/static-prefixes/v1" { + http.NotFound(w, r) + return + } + seenQueries = append(seenQueries, r.URL.RawQuery) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "version": 1, + "marker": lingercontext.StaticPrefixEndMarker, + "compact_max_context_tokens": 128 * 1024, + "prefixes": map[string]any{ + "meta": map[string]any{"full": "META", "compact": "META"}, + "alter_ego": map[string]any{"full": "ALTER", "compact": "ALTER"}, + }, + }) + })) + defer server.Close() + + var report *bool + var seenBashPaths []string + runner := &PrefixWarmupRunner{ + ContentURL: func() string { return server.URL + "/conn" }, + PiInstallation: func() (lingercontext.ProviderInstallation, bool) { + return lingercontext.ProviderInstallation{ExecutablePath: "/usr/local/bin/pi"}, true + }, + ManagedMCPExtension: "/opt/tools/pi-mcp.mjs", + WindowsGitBashPath: `C:\Linger\resources\runtime\git-bash\bin\bash.exe`, + WindowsGitBashReport: func() *bool { return report }, + HTTPClient: server.Client(), + RunWarmup: func(_ context.Context, profile native.Profile, _ string, _ string, _ string, _ native.StrataPinSpec, _ json.RawMessage) error { + seenBashPaths = append(seenBashPaths, profile.WindowsGitBashPath) + return nil + }, + } + + if done, err := runner.Warmup(t.Context(), localmodels.PrefixWarmupTarget{ModelID: "m1", PiModel: "localmodels/m1", Engine: "polystrata"}); err != nil || !done { + t.Fatalf("unnegotiated Warmup = (%t, %v)", done, err) + } + disabled := false + report = &disabled + if done, err := runner.Warmup(t.Context(), localmodels.PrefixWarmupTarget{ModelID: "m1", PiModel: "localmodels/m1", Engine: "polystrata"}); err != nil || !done { + t.Fatalf("windows_git_bash=0 Warmup = (%t, %v)", done, err) + } + enabled := true + report = &enabled + if done, err := runner.Warmup(t.Context(), localmodels.PrefixWarmupTarget{ModelID: "m1", PiModel: "localmodels/m1", Engine: "polystrata"}); err != nil || !done { + t.Fatalf("windows_git_bash=1 Warmup = (%t, %v)", done, err) + } + + if len(seenQueries) != 3 || seenQueries[0] != "" || seenQueries[1] != "windows_git_bash=0" || seenQueries[2] != "windows_git_bash=1" { + t.Fatalf("queries = %q, want [\"\", \"windows_git_bash=0\", \"windows_git_bash=1\"]", seenQueries) + } + if len(seenBashPaths) != 6 || seenBashPaths[0] != "" || seenBashPaths[2] != "" || seenBashPaths[4] != runner.WindowsGitBashPath { + t.Fatalf("profile WindowsGitBashPaths = %q", seenBashPaths) + } +} diff --git a/apps/computer/local-daemon/internal/linger/context/resolver.go b/apps/computer/local-daemon/internal/linger/context/resolver.go index af3c7ab4ac..8af35beb99 100644 --- a/apps/computer/local-daemon/internal/linger/context/resolver.go +++ b/apps/computer/local-daemon/internal/linger/context/resolver.go @@ -82,10 +82,20 @@ const explicitBrowserSearchOverride = "When the user explicitly asks to search i // link that still has its own web tools. const teamHubWebOverOwnTools = "Use them instead of your built-in web search and fetch tools, which may not work through the API this model is served by." -// piWindowsPowerShellGuide tells Windows Pi Agents to use PowerShell syntax -// and file/here-string inputs that avoid Windows PowerShell 5.1 argument -// corruption. -const piWindowsPowerShellGuide = "Shell on Windows: your shell tool is `powershell` (PowerShell), not bash; do not use `<<'EOF'`, `&&`/`||`, or inline `VAR=val cmd`. Use single quotes `'...'` for short args (double quotes expand `$` like `\"$6.4M\"`, and PowerShell strips embedded `\"` from native args and `$var` JSON args). Prefer writing a UTF-8 file with `write` (never `>`, `Out-File`, or `Set-Content` without `-Encoding utf8`) and passing `--file `, `--message-file `, `--questions-file `, or `--arguments-file ` (e.g. `teamhub message send --file `). The one allowed stdin pipe form is a single-quoted here-string (`@'` on its own line, content, then `'@ | teamhub message send --file -` with `'@` at column 0). Quote commas or repeat flags like `--message-id`." +// piWindowsPowerShellGuide tells Windows Pi Agents on bash-less hosts (where +// only PowerShell is available) to quote TeamHub text safely in PowerShell. +const piWindowsPowerShellGuide = "Shell on Windows: your `powershell` tool runs PowerShell (not bash) with UTF-8 stdin/stdout. Never use `<<'EOF'` or bash `\\$` escapes (backslash is not an escape character and double-quoted `$` expands to empty). Use single quotes `'...'` for short args (e.g. `teamhub message send --content 'ARR is $6.4M'`). For multi-line text, JSON, or text with quotes/backticks/`$`, pipe a single-quoted here-string (`@'` on its own line, the text, then `'@` at column 0 `| teamhub message send --file -`) or write a UTF-8 file with `write` and pass `--file ` / `--message-file ` / `--questions-file ` (never `>`, `Out-File`, or `Set-Content` without `-Encoding utf8`). Quote commas or repeat flags like `--message-id`." + +// piWindowsDualShellGuide tells Windows Pi Agents how to choose between the +// primary bash tool (Git Bash) and the secondary powershell tool (pwsh) +// without mixing dialects. +const piWindowsDualShellGuide = "Shell on Windows: you have two shell tools — `bash` (Git Bash / MSYS2 with `MSYS_NO_PATHCONV=1`) and `powershell` (`pwsh`). Never mix their syntax:\n" + + "- Default to `bash` for `teamhub`, git, Python/Node, and ordinary file/text commands. Use single quotes `'...'` for short literal strings with `$` (for example `'ARR is $6.4M'`), quoted heredocs (`<<'EOF'`) for multi-line text, backticks, `$`, or JSON piped to `--file -` / `--questions-file -` / `--message-file -`, and relative (`./playground/...`) or forward-slash Windows drive paths (`C:/Users/...`) for native Windows programs rather than `/c/...`. Example (`bash`):\n" + + " teamhub message send --file - <<'EOF'\n" + + " ARR is $6.4M (200 seats @ $540).\n" + + " EOF\n" + + "- Use `powershell` only for Windows-native administration (Registry, WMI/CIM, COM/Office automation, Windows services, ACLs, .NET APIs). In `powershell`, never use `<<'EOF'` or bash `\\$` escapes (backslash is not an escape character and double-quoted `$` expands to empty); use single quotes `'...'`, a single-quoted here-string (`@'` ... `'@ | ...`), or the `write` tool plus `--file `. Example (`powershell`):\n" + + " Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version" // codexWindowsPowerShellGuide tells Windows Codex Agents to avoid PowerShell // 5.1 argument quote stripping and default ASCII stdin piping when invoking @@ -107,11 +117,11 @@ const StaticPrefixEndMarker = "" // PiDaemonStaticGuides returns the trusted Daemon static guides added before // StaticPrefixEndMarker for managed Pi Runs, keeping warm-up aligned byte for byte. -func PiDaemonStaticGuides(serviceCommand []string, toolGuide, hostEnvironmentGuide string, apiLink, modelGateway, teamHubCLI bool) []string { - return daemonStaticGuidesFor("trusted", "pi", runtime.GOOS, serviceCommand, toolGuide, hostEnvironmentGuide, apiLink, modelGateway, teamHubCLI) +func PiDaemonStaticGuides(serviceCommand []string, toolGuide, hostEnvironmentGuide string, apiLink, modelGateway, teamHubCLI, windowsGitBash bool) []string { + return daemonStaticGuidesFor("trusted", "pi", runtime.GOOS, serviceCommand, toolGuide, hostEnvironmentGuide, apiLink, modelGateway, teamHubCLI, windowsGitBash) } -func daemonStaticGuidesFor(hostAccess, runtimeType, goos string, serviceCommand []string, toolGuide, hostEnvironmentGuide string, apiLink, modelGateway, teamHubCLI bool) []string { +func daemonStaticGuidesFor(hostAccess, runtimeType, goos string, serviceCommand []string, toolGuide, hostEnvironmentGuide string, apiLink, modelGateway, teamHubCLI, windowsGitBash bool) []string { var guides []string if hostAccess == "trusted" { guides = append(guides, trustedHostServiceInstructions, boundServiceInstructions(serviceCommand)) @@ -120,7 +130,7 @@ func daemonStaticGuidesFor(hostAccess, runtimeType, goos string, serviceCommand guides = append(guides, toolGuide) } if hostEnvironmentGuide != "" { - if goos == "windows" && runtimeType == "claude" && hostEnvironmentGuide == WindowsHostEnvironmentGuide { + if goos == "windows" && (runtimeType == "claude" || (runtimeType == "pi" && windowsGitBash)) && hostEnvironmentGuide == WindowsHostEnvironmentGuide { guides = append(guides, windowsBashHostEnvironmentGuide) } else { guides = append(guides, hostEnvironmentGuide) @@ -129,7 +139,7 @@ func daemonStaticGuidesFor(hostAccess, runtimeType, goos string, serviceCommand if webGuide := webToolGuide(runtimeType, apiLink, modelGateway, teamHubCLI); webGuide != "" { guides = append(guides, webGuide) } - if shellGuide := shellToolGuide(runtimeType, goos, teamHubCLI); shellGuide != "" { + if shellGuide := shellToolGuide(runtimeType, goos, teamHubCLI, windowsGitBash); shellGuide != "" { guides = append(guides, shellGuide) } return guides @@ -146,12 +156,15 @@ func AssembleWarmupSystemPrompt(staticPart string, daemonStaticGuides []string) return staticSection + "\n\n" + StaticPrefixEndMarker } -func shellToolGuide(runtimeType, goos string, teamHubCLI bool) string { +func shellToolGuide(runtimeType, goos string, teamHubCLI, windowsGitBash bool) string { if goos != "windows" || !teamHubCLI { return "" } switch runtimeType { case "pi": + if windowsGitBash { + return piWindowsDualShellGuide + } return piWindowsPowerShellGuide case "codex": return codexWindowsPowerShellGuide @@ -190,11 +203,17 @@ type ExecutionResolver struct { TeamHubCLINodePath string ToolGuide string // describes the Computer's local tools to every Operation HostEnvironmentGuide string // describes host OS environment caveats to every Operation - Providers map[string]ProviderInstallation - ProviderLookup func(context.Context, string) (ProviderInstallation, bool, error) - WorkspaceGrants map[string]WorkspaceGrant - Registrations map[string]RegistrationBinding - RegistrationLookup func(context.Context, string) (RegistrationBinding, bool, error) + // WindowsGitBash reports whether a usable non-WSL Git Bash binary is + // available for Windows Pi Runs, enabling dual bash+powershell guidance. + // When WindowsGitBashEnabled is non-nil it takes precedence so Daemon + // connections can gate dual-shell mode on welcome-negotiated service_features. + WindowsGitBash bool + WindowsGitBashEnabled func() bool + Providers map[string]ProviderInstallation + ProviderLookup func(context.Context, string) (ProviderInstallation, bool, error) + WorkspaceGrants map[string]WorkspaceGrant + Registrations map[string]RegistrationBinding + RegistrationLookup func(context.Context, string) (RegistrationBinding, bool, error) // CLICredentials finds the Agent-level TeamHub CLI credential the Daemon // stored. Nil leaves every Operation without a TeamHub CLI profile. CLICredentials CLICredentialLookup @@ -205,6 +224,13 @@ type ExecutionResolver struct { goos string } +func (r ExecutionResolver) windowsGitBashEnabled() bool { + if r.WindowsGitBashEnabled != nil { + return r.WindowsGitBashEnabled() + } + return r.WindowsGitBash +} + func (r ExecutionResolver) targetOS() string { if r.goos != "" { return r.goos @@ -296,6 +322,7 @@ func (r ExecutionResolver) Resolve(ctx context.Context, command protocol.Command installation.APILink, installation.ModelGateway, cliInstalled && r.TeamHubCLIBin != "", + r.windowsGitBashEnabled(), ) resolvedBase, resolvedDeveloper, systemPrompt, baseHadMarker, devHadMarker := assembleResolvedInstructions( instructionValue(request.SessionOptions.BaseInstructions), diff --git a/apps/computer/local-daemon/internal/linger/context/resolver_test.go b/apps/computer/local-daemon/internal/linger/context/resolver_test.go index af0f47606d..61b975c53d 100644 --- a/apps/computer/local-daemon/internal/linger/context/resolver_test.go +++ b/apps/computer/local-daemon/internal/linger/context/resolver_test.go @@ -586,32 +586,19 @@ func TestExecutionResolverPlacesStaticGuidesInCodexBaseInstructionsAndStripsMark } func TestShellToolGuideAndWindowsStaticPrefixPlacement(t *testing.T) { - if got := shellToolGuide("pi", "windows", true); got != piWindowsPowerShellGuide { - t.Fatalf("shellToolGuide(pi, windows, true) = %q", got) + if got := shellToolGuide("pi", "windows", true, true); got != piWindowsDualShellGuide { + t.Fatalf("shellToolGuide(pi, windows, true, true) = %q", got) } - if got := shellToolGuide("codex", "windows", true); got != codexWindowsPowerShellGuide { - t.Fatalf("shellToolGuide(codex, windows, true) = %q", got) + if got := shellToolGuide("pi", "windows", true, false); got != piWindowsPowerShellGuide { + t.Fatalf("shellToolGuide(pi, windows, true, false) = %q", got) } - for _, want := range []string{ - "powershell", - "(PowerShell)", - "$6.4M", - "teamhub message send --file ", - "--message-file ", - "--questions-file ", - "--arguments-file ", - "--file -", - "one allowed stdin pipe form", - "write", - "-Encoding utf8", - "--message-id", - } { - if !strings.Contains(piWindowsPowerShellGuide, want) { - t.Errorf("piWindowsPowerShellGuide missing %q", want) - } + if got := shellToolGuide("codex", "windows", true, false); got != codexWindowsPowerShellGuide { + t.Fatalf("shellToolGuide(codex, windows, true, false) = %q", got) } - if strings.Contains(piWindowsPowerShellGuide, "---file") { - t.Errorf("piWindowsPowerShellGuide should use concrete flags instead of abstract ---file: %q", piWindowsPowerShellGuide) + for _, want := range []string{"`bash`", "`powershell`", "MSYS_NO_PATHCONV=1", "<<'EOF'", "$6.4M", "@'", "Get-CimInstance"} { + if !strings.Contains(piWindowsDualShellGuide, want) { + t.Errorf("piWindowsDualShellGuide missing %q", want) + } } for _, want := range []string{ "runs PowerShell, not bash", @@ -643,8 +630,11 @@ func TestShellToolGuideAndWindowsStaticPrefixPlacement(t *testing.T) { {"codex", "darwin", true}, {"claude", "windows", true}, } { - if got := shellToolGuide(tc.runtimeType, tc.goos, tc.cli); got != "" { - t.Errorf("shellToolGuide(%q, %q, %v) = %q, want empty", tc.runtimeType, tc.goos, tc.cli, got) + if got := shellToolGuide(tc.runtimeType, tc.goos, tc.cli, true); got != "" { + t.Errorf("shellToolGuide(%q, %q, %v, true) = %q, want empty", tc.runtimeType, tc.goos, tc.cli, got) + } + if got := shellToolGuide(tc.runtimeType, tc.goos, tc.cli, false); got != "" { + t.Errorf("shellToolGuide(%q, %q, %v, false) = %q, want empty", tc.runtimeType, tc.goos, tc.cli, got) } } @@ -654,6 +644,7 @@ func TestShellToolGuideAndWindowsStaticPrefixPlacement(t *testing.T) { TeamHubCLIBin: "/trusted/release/cli", CLICredentials: store, ToolGuide: "StaticToolGuide", + WindowsGitBash: true, Providers: map[string]ProviderInstallation{ "pi": {Type: "pi", ExecutablePath: "/local/bin/pi", ModelGateway: true, APILink: true}, "codex": {Type: "codex", ExecutablePath: "/local/bin/codex", ModelGateway: true, APILink: true}, @@ -688,7 +679,7 @@ func TestShellToolGuideAndWindowsStaticPrefixPlacement(t *testing.T) { "StaticCore", "StaticToolGuide", teamHubWebToolGuide, - piWindowsPowerShellGuide, + piWindowsDualShellGuide, }, "\n\n") wantPiSystem := wantPiPrefix + "\n\nAgent A Prompt\n\nDynamicTail" if piSpec.SystemPrompt != wantPiSystem { @@ -699,6 +690,17 @@ func TestShellToolGuideAndWindowsStaticPrefixPlacement(t *testing.T) { t.Fatalf("Pi DeveloperInstructions = %v, want %q", piSpec.DeveloperInstructions, wantPiDev) } + // Without Windows Git Bash, Windows Pi falls back to PowerShell-only guide. + resolver.WindowsGitBash = false + piPowerShellSpec, err := resolver.Resolve(context.Background(), piCmd, piReq) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(piPowerShellSpec.SystemPrompt, piWindowsPowerShellGuide) || strings.Contains(piPowerShellSpec.SystemPrompt, piWindowsDualShellGuide) { + t.Fatalf("bash-less Windows Pi SystemPrompt = %q, want piWindowsPowerShellGuide", piPowerShellSpec.SystemPrompt) + } + resolver.WindowsGitBash = true + codexCmd := protocol.Command{ TenantID: "tenant", AgentID: "agent", RegistrationID: "registration-codex", AssignmentRevision: 1, WorkspaceGrantID: "grant-local", RuntimeType: "codex", @@ -771,6 +773,7 @@ func TestExecutionResolverPlacesHostEnvironmentGuideInStaticPrefix(t *testing.T) resolver := ExecutionResolver{ ToolGuide: "StaticToolGuide", HostEnvironmentGuide: WindowsHostEnvironmentGuide, + WindowsGitBash: true, Providers: map[string]ProviderInstallation{ "codex": {Type: "codex", ExecutablePath: "/local/bin/codex"}, }, @@ -821,6 +824,7 @@ func TestWindowsHostEnvironmentGuideFollowsRuntimeShell(t *testing.T) { resolver := ExecutionResolver{ ToolGuide: "StaticToolGuide", HostEnvironmentGuide: WindowsHostEnvironmentGuide, + WindowsGitBash: true, Providers: map[string]ProviderInstallation{ "claude": {Type: "claude", ExecutablePath: `/local/bin/claude`}, "pi": {Type: "pi", ExecutablePath: `/local/bin/pi`}, @@ -858,12 +862,14 @@ func TestWindowsHostEnvironmentGuideFollowsRuntimeShell(t *testing.T) { return spec } - claudeSpec := resolveFor("claude", `{}`) - if !strings.Contains(claudeSpec.SystemPrompt, windowsBashHostEnvironmentGuide) { - t.Fatalf("Windows claude SystemPrompt missing windowsBashHostEnvironmentGuide: %q", claudeSpec.SystemPrompt) - } - if strings.Contains(claudeSpec.SystemPrompt, WindowsHostEnvironmentGuide) { - t.Fatalf("Windows claude SystemPrompt unexpectedly got PowerShell WindowsHostEnvironmentGuide: %q", claudeSpec.SystemPrompt) + for _, runtimeType := range []string{"claude", "pi"} { + spec := resolveFor(runtimeType, `{}`) + if !strings.Contains(spec.SystemPrompt, windowsBashHostEnvironmentGuide) { + t.Fatalf("Windows %s SystemPrompt missing windowsBashHostEnvironmentGuide: %q", runtimeType, spec.SystemPrompt) + } + if strings.Contains(spec.SystemPrompt, WindowsHostEnvironmentGuide) { + t.Fatalf("Windows %s SystemPrompt unexpectedly got PowerShell WindowsHostEnvironmentGuide: %q", runtimeType, spec.SystemPrompt) + } } for _, want := range []string{"Bash on Windows", "command -v", "find -L", `NODE_PATH="$(pwd)/agent/node_modules"`} { if !strings.Contains(windowsBashHostEnvironmentGuide, want) { @@ -871,25 +877,35 @@ func TestWindowsHostEnvironmentGuideFollowsRuntimeShell(t *testing.T) { } } - for _, runtimeType := range []string{"pi", "codex"} { - sessionJSON := `{}` - if runtimeType == "codex" { - sessionJSON = `{"threadId":""}` - } - spec := resolveFor(runtimeType, sessionJSON) - if !strings.Contains(spec.SystemPrompt, WindowsHostEnvironmentGuide) { - t.Fatalf("Windows %s SystemPrompt missing WindowsHostEnvironmentGuide: %q", runtimeType, spec.SystemPrompt) - } - if strings.Contains(spec.SystemPrompt, windowsBashHostEnvironmentGuide) { - t.Fatalf("Windows %s SystemPrompt unexpectedly got windowsBashHostEnvironmentGuide: %q", runtimeType, spec.SystemPrompt) - } + codexSpec := resolveFor("codex", `{"threadId":""}`) + if !strings.Contains(codexSpec.SystemPrompt, WindowsHostEnvironmentGuide) { + t.Fatalf("Windows codex SystemPrompt missing WindowsHostEnvironmentGuide: %q", codexSpec.SystemPrompt) + } + if strings.Contains(codexSpec.SystemPrompt, windowsBashHostEnvironmentGuide) { + t.Fatalf("Windows codex SystemPrompt unexpectedly got windowsBashHostEnvironmentGuide: %q", codexSpec.SystemPrompt) } - piDirect := daemonStaticGuidesFor("trusted", "pi", "windows", nil, "Tool", WindowsHostEnvironmentGuide, false, false, false) - if !slices.Contains(piDirect, WindowsHostEnvironmentGuide) { - t.Fatalf("daemonStaticGuidesFor(pi, windows) = %v, want WindowsHostEnvironmentGuide", piDirect) + // Without Windows Git Bash, Pi falls back to WindowsHostEnvironmentGuide while Claude stays on Git Bash. + resolver.WindowsGitBash = false + piNoBashSpec := resolveFor("pi", `{}`) + if !strings.Contains(piNoBashSpec.SystemPrompt, WindowsHostEnvironmentGuide) || strings.Contains(piNoBashSpec.SystemPrompt, windowsBashHostEnvironmentGuide) { + t.Fatalf("bash-less Windows pi SystemPrompt = %q, want WindowsHostEnvironmentGuide", piNoBashSpec.SystemPrompt) + } + claudeNoBashSpec := resolveFor("claude", `{}`) + if !strings.Contains(claudeNoBashSpec.SystemPrompt, windowsBashHostEnvironmentGuide) { + t.Fatalf("Windows claude SystemPrompt missing windowsBashHostEnvironmentGuide: %q", claudeNoBashSpec.SystemPrompt) } - customClaude := daemonStaticGuidesFor("trusted", "claude", "windows", nil, "Tool", "CustomGuide", false, false, false) + resolver.WindowsGitBash = true + + piDirect := daemonStaticGuidesFor("trusted", "pi", "windows", nil, "Tool", WindowsHostEnvironmentGuide, false, false, false, true) + if !slices.Contains(piDirect, windowsBashHostEnvironmentGuide) { + t.Fatalf("daemonStaticGuidesFor(pi, windows, gitBash=true) = %v, want windowsBashHostEnvironmentGuide", piDirect) + } + piDirectNoBash := daemonStaticGuidesFor("trusted", "pi", "windows", nil, "Tool", WindowsHostEnvironmentGuide, false, false, false, false) + if !slices.Contains(piDirectNoBash, WindowsHostEnvironmentGuide) { + t.Fatalf("daemonStaticGuidesFor(pi, windows, gitBash=false) = %v, want WindowsHostEnvironmentGuide", piDirectNoBash) + } + customClaude := daemonStaticGuidesFor("trusted", "claude", "windows", nil, "Tool", "CustomGuide", false, false, false, false) if !slices.Contains(customClaude, "CustomGuide") { t.Fatalf("daemonStaticGuidesFor(claude, windows, custom) = %v, want CustomGuide", customClaude) } @@ -944,7 +960,7 @@ func TestAssembleWarmupSystemPromptMatchesExecutionResolverPrefix(t *testing.T) t.Fatal(err) } - guides := PiDaemonStaticGuides(serviceCommand, toolGuide, WindowsHostEnvironmentGuide, true, true, true) + guides := PiDaemonStaticGuides(serviceCommand, toolGuide, WindowsHostEnvironmentGuide, true, true, true, false) warmup := AssembleWarmupSystemPrompt(staticPart, guides) if !strings.HasSuffix(warmup, "\n\n"+StaticPrefixEndMarker) { t.Fatalf("warmup prompt missing trailing marker: %q", warmup) @@ -955,42 +971,51 @@ func TestAssembleWarmupSystemPromptMatchesExecutionResolverPrefix(t *testing.T) } // Verify byte-for-byte warmup prefix alignment across OS (posix vs windows), - // context kind (meta vs alter_ego), and all 3 tiers (full, compact, minimal). + // Windows Git Bash availability, context kind (meta vs alter_ego), and all 3 tiers. for _, goos := range []string{"linux", "darwin", "windows"} { hostGuide := "" if goos == "windows" { hostGuide = WindowsHostEnvironmentGuide } - resolver.goos = goos - resolver.HostEnvironmentGuide = hostGuide - guidesForOS := daemonStaticGuidesFor("trusted", "pi", goos, serviceCommand, toolGuide, hostGuide, true, true, true) - for _, contextKind := range []string{"meta", "alter_ego"} { - for _, tier := range []string{"full", "compact", "minimal"} { - variantStatic := fmt.Sprintf("StaticCore:%s:%s:%s", goos, contextKind, tier) - variantReq := json.RawMessage(`{ - "kind":"run.start", - "runtime":{"type":"pi","model":"localmodels/model-a"}, - "session_options":{"thread_name":"Agent A","base_instructions":"Agent A Prompt","developer_instructions":"` + variantStatic + `\n\n` + StaticPrefixEndMarker + `\n\nDynamicA"}, - "session":{}, - "input":{"type":"text","text":"Hi"} - }`) - variantSpec, err := resolver.Resolve(context.Background(), cmd, variantReq) - if err != nil { - t.Fatalf("Resolve(%s, %s, %s) error: %v", goos, contextKind, tier, err) - } - variantWarmup := AssembleWarmupSystemPrompt(variantStatic, guidesForOS) - if !strings.HasSuffix(variantWarmup, "\n\n"+StaticPrefixEndMarker) { - t.Fatalf("warmup (%s, %s, %s) missing trailing marker: %q", goos, contextKind, tier, variantWarmup) - } - variantPrefix := strings.TrimSuffix(variantWarmup, StaticPrefixEndMarker) - if !strings.HasPrefix(variantSpec.SystemPrompt, variantPrefix) { - t.Fatalf("warmup prefix mismatch (%s, %s, %s):\nwarmup=%q\nsystem=%q", goos, contextKind, tier, variantPrefix, variantSpec.SystemPrompt) - } - if goos == "windows" && !strings.Contains(variantPrefix, piWindowsPowerShellGuide) { - t.Fatalf("windows warmup (%s, %s) missing piWindowsPowerShellGuide", contextKind, tier) - } - if goos != "windows" && strings.Contains(variantPrefix, piWindowsPowerShellGuide) { - t.Fatalf("posix warmup (%s, %s, %s) unexpectedly contained piWindowsPowerShellGuide", goos, contextKind, tier) + for _, windowsGitBash := range []bool{false, true} { + if goos != "windows" && windowsGitBash { + continue + } + resolver.goos = goos + resolver.HostEnvironmentGuide = hostGuide + resolver.WindowsGitBash = windowsGitBash + guidesForOS := daemonStaticGuidesFor("trusted", "pi", goos, serviceCommand, toolGuide, hostGuide, true, true, true, windowsGitBash) + for _, contextKind := range []string{"meta", "alter_ego"} { + for _, tier := range []string{"full", "compact", "minimal"} { + variantStatic := fmt.Sprintf("StaticCore:%s:%t:%s:%s", goos, windowsGitBash, contextKind, tier) + variantReq := json.RawMessage(`{ + "kind":"run.start", + "runtime":{"type":"pi","model":"localmodels/model-a"}, + "session_options":{"thread_name":"Agent A","base_instructions":"Agent A Prompt","developer_instructions":"` + variantStatic + `\n\n` + StaticPrefixEndMarker + `\n\nDynamicA"}, + "session":{}, + "input":{"type":"text","text":"Hi"} + }`) + variantSpec, err := resolver.Resolve(context.Background(), cmd, variantReq) + if err != nil { + t.Fatalf("Resolve(%s, gitBash=%t, %s, %s) error: %v", goos, windowsGitBash, contextKind, tier, err) + } + variantWarmup := AssembleWarmupSystemPrompt(variantStatic, guidesForOS) + if !strings.HasSuffix(variantWarmup, "\n\n"+StaticPrefixEndMarker) { + t.Fatalf("warmup (%s, gitBash=%t, %s, %s) missing trailing marker: %q", goos, windowsGitBash, contextKind, tier, variantWarmup) + } + variantPrefix := strings.TrimSuffix(variantWarmup, StaticPrefixEndMarker) + if !strings.HasPrefix(variantSpec.SystemPrompt, variantPrefix) { + t.Fatalf("warmup prefix mismatch (%s, gitBash=%t, %s, %s):\nwarmup=%q\nsystem=%q", goos, windowsGitBash, contextKind, tier, variantPrefix, variantSpec.SystemPrompt) + } + if goos == "windows" && windowsGitBash && !strings.Contains(variantPrefix, piWindowsDualShellGuide) { + t.Fatalf("windows dual-shell warmup (%s, %s) missing piWindowsDualShellGuide", contextKind, tier) + } + if goos == "windows" && !windowsGitBash && !strings.Contains(variantPrefix, piWindowsPowerShellGuide) { + t.Fatalf("windows powershell-only warmup (%s, %s) missing piWindowsPowerShellGuide", contextKind, tier) + } + if goos != "windows" && (strings.Contains(variantPrefix, piWindowsDualShellGuide) || strings.Contains(variantPrefix, piWindowsPowerShellGuide)) { + t.Fatalf("posix warmup (%s, %s, %s) unexpectedly contained Windows guide", goos, contextKind, tier) + } } } } diff --git a/apps/computer/local-daemon/internal/linger/localtools/installation.go b/apps/computer/local-daemon/internal/linger/localtools/installation.go index e020782436..44a6411fd4 100644 --- a/apps/computer/local-daemon/internal/linger/localtools/installation.go +++ b/apps/computer/local-daemon/internal/linger/localtools/installation.go @@ -22,6 +22,9 @@ type Installation struct { // PowerShellPath holds the bundled PowerShell 7 executable on Windows when // present under resources/runtime/pwsh/pwsh.exe. PowerShellPath string + // GitBashPath holds the bundled PortableGit bash.exe on Windows when + // present under resources/runtime/git-bash/bin/bash.exe. + GitBashPath string } func cuaEntry(executable string) string { @@ -162,19 +165,27 @@ func Installed(executable string) (*Installation, error) { PiVersion: manifest.Versions.Pi, } if strings.HasSuffix(strings.ToLower(executable), ".exe") { - candidates := []string{filepath.Join(root, "runtime", "pwsh", "pwsh.exe")} + roots := []string{root} // When the daemon runs from an externalized V2 store directory and // LINGER_COMPUTER_TOOLS_DIR points back to resources/cli/computer-tools, - // keep resolving the Shell-bundled PowerShell 7 under resources/runtime/pwsh. + // keep resolving Shell-bundled runtimes under resources/runtime/. if toolsRoot := filepath.Dir(filepath.Dir(tools)); toolsRoot != root { - candidates = append(candidates, filepath.Join(toolsRoot, "runtime", "pwsh", "pwsh.exe")) + roots = append(roots, toolsRoot) } - for _, pwsh := range candidates { + for _, candidateRoot := range roots { + pwsh := filepath.Join(candidateRoot, "runtime", "pwsh", "pwsh.exe") if info, e := os.Stat(pwsh); e == nil && info.Mode().IsRegular() { installed.PowerShellPath = pwsh break } } + for _, candidateRoot := range roots { + gitBash := filepath.Join(candidateRoot, "runtime", "git-bash", "bin", "bash.exe") + if info, e := os.Stat(gitBash); e == nil && info.Mode().IsRegular() { + installed.GitBashPath = gitBash + break + } + } } if manifest.Cua != "" { // macOS drives the desktop through the signed application. @@ -185,3 +196,85 @@ func Installed(executable string) (*Installation, error) { } return installed, nil } + +// IsLegacyWSLBashPath reports whether path points to a Windows WSL shim +// (`System32\bash.exe`, `SysWOW64\bash.exe`, or `WindowsApps\bash.exe`) +// rather than a native Git for Windows / MSYS2 bash binary. +func IsLegacyWSLBashPath(path string) bool { + normalized := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(path), "/", `\`)) + return strings.HasSuffix(normalized, `\windows\system32\bash.exe`) || + strings.HasSuffix(normalized, `\windows\syswow64\bash.exe`) || + strings.HasSuffix(normalized, `\microsoft\windowsapps\bash.exe`) +} + +// ResolveWindowsGitBash returns the highest-priority usable native Git Bash +// executable on Windows: bundled PortableGit first, then standard Git for +// Windows install directories, then the first non-WSL bash.exe on PATH. +// Returns "" when no usable Git Bash is available. +func ResolveWindowsGitBash(bundledPath string, env map[string]string) string { + return resolveWindowsGitBashWithStat(bundledPath, env, isRegularFile) +} + +func isRegularFile(path string) bool { + info, err := os.Stat(path) + return err == nil && info.Mode().IsRegular() +} + +func envLookupFold(env map[string]string, target string) string { + if value, ok := env[target]; ok && strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + for key, value := range env { + if strings.EqualFold(key, target) && strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +func joinWindowsChildPath(base string, parts ...string) string { + trimmed := strings.TrimRight(base, `\/`) + sep := `\` + if strings.Contains(base, "/") && !strings.Contains(base, `\`) { + sep = "/" + } + return strings.Join(append([]string{trimmed}, parts...), sep) +} + +func resolveWindowsGitBashWithStat(bundledPath string, env map[string]string, exists func(string) bool) string { + if trimmed := strings.TrimSpace(bundledPath); trimmed != "" && !IsLegacyWSLBashPath(trimmed) && exists(trimmed) { + return trimmed + } + for _, rootKey := range []string{"ProgramFiles", "ProgramFiles(x86)"} { + root := envLookupFold(env, rootKey) + if root == "" { + continue + } + candidate := joinWindowsChildPath(root, "Git", "bin", "bash.exe") + if exists(candidate) { + return candidate + } + } + pathValue := envLookupFold(env, "PATH") + if pathValue == "" { + return "" + } + sep := ";" + if !strings.Contains(pathValue, ";") && strings.Contains(pathValue, ":") && !strings.Contains(pathValue, `\`) { + sep = ":" + } + for _, entry := range strings.Split(pathValue, sep) { + dir := strings.Trim(strings.TrimSpace(entry), `"`) + if dir == "" { + continue + } + candidate := joinWindowsChildPath(dir, "bash.exe") + if IsLegacyWSLBashPath(candidate) { + continue + } + if exists(candidate) { + return candidate + } + } + return "" +} diff --git a/apps/computer/local-daemon/internal/linger/localtools/installation_test.go b/apps/computer/local-daemon/internal/linger/localtools/installation_test.go index b97a2450d6..5895a26670 100644 --- a/apps/computer/local-daemon/internal/linger/localtools/installation_test.go +++ b/apps/computer/local-daemon/internal/linger/localtools/installation_test.go @@ -433,4 +433,99 @@ func TestInstalledToolsDetectsBundledWindowsPowerShell(t *testing.T) { if err != nil || result == nil || result.PowerShellPath != "" { t.Fatalf("non-Windows daemon unexpectedly set PowerShellPath: %+v, err=%v", result, err) } + + gitBash := filepath.Join(filepath.Dir(filepath.Dir(winExecutable)), "runtime", "git-bash", "bin", "bash.exe") + if err := os.MkdirAll(filepath.Dir(gitBash), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(gitBash, []byte("MZ"), 0o700); err != nil { + t.Fatal(err) + } + result, err = Installed(winExecutable) + if err != nil || result == nil || result.GitBashPath != gitBash { + t.Fatalf("with bundled git-bash = %+v, want %q, err=%v", result, gitBash, err) + } + t.Run("externalized V2 Windows daemon resolves Shell git-bash via LINGER_COMPUTER_TOOLS_DIR", func(t *testing.T) { + shellTools := filepath.Join(filepath.Dir(filepath.Dir(winExecutable)), "cli", "computer-tools") + shellNode := filepath.Join(filepath.Dir(filepath.Dir(winExecutable)), "runtime", "bin", "node.exe") + t.Setenv("LINGER_COMPUTER_TOOLS_DIR", shellTools) + t.Setenv("LINGER_TOOLS_NODE_PATH", shellNode) + storeExe := filepath.Join(resources, "store", "backend", "abc123", "computer-daemon", "linger-computer-daemon.exe") + got, err := Installed(storeExe) + if err != nil || got == nil || got.GitBashPath != gitBash { + t.Fatalf("externalized Windows git-bash = %+v, want %q, err=%v", got, gitBash, err) + } + }) + posixGitBash := filepath.Join(filepath.Dir(filepath.Dir(posixExecutable)), "runtime", "git-bash", "bin", "bash.exe") + if err := os.MkdirAll(filepath.Dir(posixGitBash), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(posixGitBash, []byte("MZ"), 0o700); err != nil { + t.Fatal(err) + } + result, err = Installed(posixExecutable) + if err != nil || result == nil || result.GitBashPath != "" { + t.Fatalf("non-Windows daemon unexpectedly set GitBashPath: %+v, err=%v", result, err) + } +} + +func TestIsLegacyWSLBashPath(t *testing.T) { + for _, path := range []string{ + `C:\Windows\System32\bash.exe`, + `c:/windows/system32/bash.exe`, + `C:\Windows\SysWOW64\bash.exe`, + `C:\Users\alice\AppData\Local\Microsoft\WindowsApps\bash.exe`, + } { + if !IsLegacyWSLBashPath(path) { + t.Errorf("IsLegacyWSLBashPath(%q) = false, want true", path) + } + } + for _, path := range []string{ + `C:\Program Files\Git\bin\bash.exe`, + `C:\Users\alice\AppData\Local\Programs\Linger\resources\runtime\git-bash\bin\bash.exe`, + "", + } { + if IsLegacyWSLBashPath(path) { + t.Errorf("IsLegacyWSLBashPath(%q) = true, want false", path) + } + } +} + +func TestResolveWindowsGitBashPriorityAndWSLExclusion(t *testing.T) { + existing := map[string]bool{} + stat := func(path string) bool { return existing[strings.ToLower(path)] } + + bundled := `C:\Linger\resources\runtime\git-bash\bin\bash.exe` + progGit := `C:\Program Files\Git\bin\bash.exe` + wslBash := `C:\Windows\System32\bash.exe` + customGit := `D:\Tools\Git\bin\bash.exe` + + env := map[string]string{ + "ProgramFiles": `C:\Program Files`, + "Path": `C:\Windows\System32;D:\Tools\Git\bin`, + } + + // Only WSL bash exists: must return empty (never pick WSL shim). + existing[strings.ToLower(wslBash)] = true + if got := resolveWindowsGitBashWithStat("", env, stat); got != "" { + t.Fatalf("WSL-only resolve = %q, want empty", got) + } + + // Non-WSL bash on PATH beats WSL bash earlier on PATH. + existing[strings.ToLower(customGit)] = true + if got := resolveWindowsGitBashWithStat("", env, stat); got != customGit { + t.Fatalf("PATH fallback resolve = %q, want %q", got, customGit) + } + + // Standard Program Files Git Bash beats arbitrary PATH entry. + existing[strings.ToLower(progGit)] = true + if got := resolveWindowsGitBashWithStat("", env, stat); got != progGit { + t.Fatalf("ProgramFiles resolve = %q, want %q", got, progGit) + } + + // Bundled PortableGit beats system Git Bash. + existing[strings.ToLower(bundled)] = true + if got := resolveWindowsGitBashWithStat(bundled, env, stat); got != bundled { + t.Fatalf("bundled resolve = %q, want %q", got, bundled) + } } diff --git a/apps/computer/local-daemon/internal/linger/transport/gateway.go b/apps/computer/local-daemon/internal/linger/transport/gateway.go index de36af434d..36c1878650 100644 --- a/apps/computer/local-daemon/internal/linger/transport/gateway.go +++ b/apps/computer/local-daemon/internal/linger/transport/gateway.go @@ -478,10 +478,16 @@ func (s *gatewayStream) Send(ctx context.Context, event protocol.Event) error { if err := json.Unmarshal(event.Payload, &diagnostics); err != nil { return fmt.Errorf("decode Runtime diagnostics: %w", err) } + var windowsGitBash *bool + if event.WindowsGitBash != nil { + enabled := *event.WindowsGitBash + windowsGitBash = &enabled + } value = wire.RunnerRuntimeDiagnostics{ Type: wire.TypeRunnerRuntimeDiagnostics, ProtocolVersion: protocol.Version, RunnerID: event.RunnerID, SentAt: event.SentAt.Format(time.RFC3339Nano), Revision: event.Revision, RuntimeDiagnostics: diagnostics, + WindowsGitBash: windowsGitBash, } case event.Type == protocol.EventRunnerHeartbeat: var payload struct { diff --git a/apps/computer/local-daemon/internal/linger/transport/gateway_test.go b/apps/computer/local-daemon/internal/linger/transport/gateway_test.go index 04b893e4aa..f7104b22d5 100644 --- a/apps/computer/local-daemon/internal/linger/transport/gateway_test.go +++ b/apps/computer/local-daemon/internal/linger/transport/gateway_test.go @@ -361,7 +361,7 @@ func TestGatewayStreamEncodesStrictOperationEvent(t *testing.T) { func TestGatewayStreamEncodesRuntimeDiagnosticsRevision(t *testing.T) { upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} - received := make(chan map[string]any, 1) + received := make(chan map[string]any, 3) server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { socket, err := upgrader.Upgrade(writer, request, nil) if err != nil { @@ -369,8 +369,11 @@ func TestGatewayStreamEncodesRuntimeDiagnosticsRevision(t *testing.T) { return } defer socket.Close() - var envelope map[string]any - if err := socket.ReadJSON(&envelope); err == nil { + for { + var envelope map[string]any + if err := socket.ReadJSON(&envelope); err != nil { + return + } received <- envelope } })) @@ -397,6 +400,35 @@ func TestGatewayStreamEncodesRuntimeDiagnosticsRevision(t *testing.T) { if _, leaked := envelope["payload"]; leaked { t.Fatal("Runtime diagnostics envelope leaked local payload wrapper") } + if _, leaked := envelope["windows_git_bash"]; leaked { + t.Fatalf("Runtime diagnostics envelope unexpectedly included windows_git_bash when nil: %+v", envelope) + } + + enabledTrue := true + if err := stream.Send(context.Background(), protocol.Event{ + Type: protocol.EventRuntimeDiagnostics, ProtocolVersion: "2", RunnerID: "computer-local", + Revision: 3, SentAt: time.Date(2026, 9, 1, 0, 0, 16, 0, time.UTC), Payload: diagnostics, + WindowsGitBash: &enabledTrue, + }); err != nil { + t.Fatal(err) + } + withBash := <-received + if withBash["windows_git_bash"] != true { + t.Fatalf("Runtime diagnostics envelope missing windows_git_bash=true: %+v", withBash) + } + + enabledFalse := false + if err := stream.Send(context.Background(), protocol.Event{ + Type: protocol.EventRuntimeDiagnostics, ProtocolVersion: "2", RunnerID: "computer-local", + Revision: 4, SentAt: time.Date(2026, 9, 1, 0, 0, 17, 0, time.UTC), Payload: diagnostics, + WindowsGitBash: &enabledFalse, + }); err != nil { + t.Fatal(err) + } + withoutBash := <-received + if val, present := withoutBash["windows_git_bash"]; !present || val != false { + t.Fatalf("Runtime diagnostics envelope missing explicit windows_git_bash=false: %+v", withoutBash) + } } func TestHelloCarriesDeviceIdentityWithoutCredential(t *testing.T) { diff --git a/apps/computer/local-daemon/internal/permission/shell.go b/apps/computer/local-daemon/internal/permission/shell.go index 50c54fcc3e..118a045510 100644 --- a/apps/computer/local-daemon/internal/permission/shell.go +++ b/apps/computer/local-daemon/internal/permission/shell.go @@ -47,7 +47,7 @@ func Shell(command, cwd, workspace string, commands []TeamHubCommand) (ShellDeci teamhub, writes, review, confirm := false, false, false, "" for _, step := range steps { switch { - case step.words[0] == "teamhub": + case isBareShellTeamHub(step.words[0]): teamhub = true allowed := teamhubCommand(step.words, commands) switch { @@ -78,6 +78,13 @@ func Shell(command, cwd, workspace string, commands []TeamHubCommand) (ShellDeci return ShellAllow, "" } +// isBareShellTeamHub reports whether word names the native TeamHub CLI in a +// POSIX or Git Bash command. Unlike ShellPowerShell, Shell does not reject +// cmd.exe metacharacters, so teamhub.cmd must always go to review. +func isBareShellTeamHub(word string) bool { + return word == "teamhub" || strings.EqualFold(word, "teamhub.exe") +} + // tccutil resets privacy grants; an AppleScript aimed at System Settings can // switch a grant on. The check matches program names and bundle ids, never // prose, and reads the raw command because a heredoc or a nested shell hides @@ -344,10 +351,28 @@ type shellPaths struct { places []string } +// normalizeMSYSDrivePath converts a Git Bash / MSYS drive path such as +// "/c/Users/alice/work" into "C:\Users\alice\work" when workspace is a +// Windows drive path, leaving POSIX paths and non-drive paths untouched. +func normalizeMSYSDrivePath(path, workspace string) string { + if len(workspace) < 3 || workspace[1] != ':' || (workspace[2] != '\\' && workspace[2] != '/') { + return path + } + if len(path) < 3 || path[0] != '/' || path[2] != '/' { + return path + } + drive := path[1] + if !((drive >= 'a' && drive <= 'z') || (drive >= 'A' && drive <= 'Z')) { + return path + } + return strings.ToUpper(string(drive)) + ":" + strings.ReplaceAll(path[2:], "/", `\`) +} + func (p *shellPaths) inside(path string) bool { if path == "" || slices.Contains(strings.Split(filepath.ToSlash(path), "/"), "..") { return false } + path = normalizeMSYSDrivePath(path, p.workspace) // A leading slash or backslash is rooted in POSIX/Git Bash shells and // drive-relative on Windows, never a path relative to the workspace. if (strings.HasPrefix(path, "/") || strings.HasPrefix(path, `\`)) && !filepath.IsAbs(path) { @@ -385,12 +410,13 @@ func (p *shellPaths) cd(step shellStep) bool { if words[0] != "cd" || len(words) != 2 || step.pipeIn || step.pipeOut || step.heredoc || len(step.redirects) > 0 || !p.inside(words[1]) { return false } + target := normalizeMSYSDrivePath(words[1], p.workspace) for _, place := range p.places { - if filepath.IsAbs(words[1]) { - p.places = append(p.places, filepath.Clean(words[1])) + if filepath.IsAbs(target) { + p.places = append(p.places, filepath.Clean(target)) break } - p.places = append(p.places, filepath.Join(place, words[1])) + p.places = append(p.places, filepath.Join(place, target)) } return true } diff --git a/apps/computer/local-daemon/internal/permission/shell_test.go b/apps/computer/local-daemon/internal/permission/shell_test.go index 91cc9d59be..b97b4c5808 100644 --- a/apps/computer/local-daemon/internal/permission/shell_test.go +++ b/apps/computer/local-daemon/internal/permission/shell_test.go @@ -232,3 +232,67 @@ func TestShellNeverAllowsPowerShellHereStrings(t *testing.T) { } } } + +func TestShellAllowsTeamHubExeAndNormalizesMSYSDrivePaths(t *testing.T) { + workspace, _ := shellWorkspace(t) + for _, command := range []string{ + "teamhub.exe message list", + "TEAMHUB.EXE message list", + } { + if decision, _ := Shell(command, workspace, workspace, shellCommands); decision != ShellAllow { + t.Fatalf("Shell(%q) = %d, want ShellAllow", command, decision) + } + } + if got := normalizeMSYSDrivePath("/c/Users/alice/work/a.md", `C:\Users\alice\work`); got != `C:\Users\alice\work\a.md` { + t.Fatalf("normalizeMSYSDrivePath = %q, want Windows path", got) + } + if got := normalizeMSYSDrivePath("/tmp/out.md", `C:\Users\alice\work`); got != "/tmp/out.md" { + t.Fatalf("normalizeMSYSDrivePath non-drive = %q, want /tmp/out.md", got) + } + if got := normalizeMSYSDrivePath("/c/Users/alice/work", "/Users/alice/work"); got != "/c/Users/alice/work" { + t.Fatalf("normalizeMSYSDrivePath on POSIX workspace = %q", got) + } +} + +func TestShellReviewsTeamHubCmd(t *testing.T) { + workspace, _ := shellWorkspace(t) + for _, command := range []string{ + "teamhub.cmd message send --content 'x&calc.exe'", + "teamhub.cmd message list", + "TEAMHUB.CMD message list", + "TEAMHUB message list", + } { + if decision, confirm := Shell(command, workspace, workspace, shellCommands); decision != ShellReview || confirm != "" { + t.Errorf("Shell(%q) = (%d, %q), want (%d, \"\")", command, decision, confirm, ShellReview) + } + } +} + +func TestShellCDNormalizesMSYSDrivePathAndBlocksLinkEscape(t *testing.T) { + ws, hasOutsideLink := shellWorkspace(t) + if !hasOutsideLink { + t.Skip("environment cannot create directory links") + } + sub := filepath.Join(ws, "notes") + subLink := filepath.Join(sub, "escape") + if err := workspace.CreateDirectoryLink(t.TempDir(), subLink); err != nil { + t.Fatal(err) + } + // On Windows, exercise the MSYS /c/... form; on POSIX, exercise the + // equivalent absolute subdirectory path. + cdTarget := sub + if runtime.GOOS == "windows" && len(sub) >= 3 && sub[1] == ':' { + drive := strings.ToLower(string(sub[0])) + cdTarget = "/" + drive + filepath.ToSlash(sub[2:]) + } + cmd := "cd '" + cdTarget + "' && cat <<'EOF' > escape/evil.txt\nhi\nEOF\nteamhub message list" + if decision, _ := Shell(cmd, ws, ws, shellCommands); decision != ShellReview { + t.Fatalf("Shell(%q) = %d, want ShellReview", cmd, decision) + } + + // Safe write inside the cd target remains allowed. + safe := "cd '" + cdTarget + "' && cat <<'EOF' > safe.txt\nhi\nEOF\nteamhub message list" + if decision, _ := Shell(safe, ws, ws, shellCommands); decision != ShellAllow { + t.Fatalf("Shell(%q) = %d, want ShellAllow", safe, decision) + } +} diff --git a/apps/computer/local-daemon/internal/permission/shell_text.go b/apps/computer/local-daemon/internal/permission/shell_text.go index 701631171f..1ed8ce5bcd 100644 --- a/apps/computer/local-daemon/internal/permission/shell_text.go +++ b/apps/computer/local-daemon/internal/permission/shell_text.go @@ -28,7 +28,7 @@ const ShellTextMessage = "Not run: the shell would change this teamhub command's // parameters are its arguments, so functions are not checked. A command the // parser cannot read is not judged. func ShellTextRewritten(command string) bool { - if !strings.Contains(command, "teamhub") || !strings.ContainsAny(command, "$`") { + if !strings.Contains(strings.ToLower(command), "teamhub") || !strings.ContainsAny(command, "$`") { return false } file, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(command), "") @@ -74,7 +74,11 @@ func pipelineStages(command *syntax.BinaryCmd, stages []*syntax.Stmt) []*syntax. func runsTeamHub(stmt *syntax.Stmt) bool { call, ok := stmt.Cmd.(*syntax.CallExpr) - return ok && len(call.Args) > 0 && path.Base(call.Args[0].Lit()) == "teamhub" + if !ok || len(call.Args) == 0 { + return false + } + base := path.Base(strings.ReplaceAll(call.Args[0].Lit(), `\`, "/")) + return isBarePowerShellTeamHub(base) } // stageRewritten reports a rewrite in a simple command's arguments or in the diff --git a/apps/computer/local-daemon/internal/permission/shell_text_powershell.go b/apps/computer/local-daemon/internal/permission/shell_text_powershell.go index 3723a78537..fe3377c532 100644 --- a/apps/computer/local-daemon/internal/permission/shell_text_powershell.go +++ b/apps/computer/local-daemon/internal/permission/shell_text_powershell.go @@ -10,6 +10,16 @@ import ( // heredoc to teamhub. const PowerShellHeredocMessage = "Not run: PowerShell does not support POSIX heredocs (<<'EOF'). Pipe a PowerShell single-quoted here-string instead (@' on its own line, the text, then '@ at column 0 | teamhub ... --file -)." +// PowerShellDollarMessage refuses a PowerShell command whose double quotes, +// double-quoted here-strings, or bare words would expand a numeric dollar +// amount or leave a stray backslash before $ in teamhub text. +const PowerShellDollarMessage = "Not run: PowerShell would rewrite this teamhub command's text before teamhub reads it. " + + "In double quotes, double-quoted here-strings (@\"...\"@), or bare words, PowerShell expands $ (such as $6 in \"$6.4M\") to empty, " + + "and backslash is not an escape character (so \"\\$28,080\" arrives as \"\\,080\"). " + + "Use single quotes ('ARR is $6.4M') for short literal text, or pass multi-line text on stdin with a single-quoted here-string:\n" + + "@'\nThe quote is $180/store.\n'@ | teamhub message send --file -\n" + + "Or write a UTF-8 file with the write tool and pass its path." + // PowerShell51QuotesMessage refuses a Windows PowerShell 5.1 command that // passes embedded double quotes in native teamhub arguments. const PowerShell51QuotesMessage = "Not run: Windows PowerShell 5.1 strips embedded double quotes from native command arguments, corrupting inline JSON and quoted text. Assigning JSON to a PowerShell variable (such as $q or @args) and passing it to an inline flag is corrupted the same way. Pass JSON or quoted text via the command's --*-file - flag using a PowerShell single-quoted here-string (@' on its own line, the content, then '@ at column 0 | teamhub ... --questions-file - / --message-file - / --file -), or write a UTF-8 file with the write tool (do not use PowerShell '>' or Set-Content without -Encoding utf8) and pass its path." @@ -48,26 +58,31 @@ type psDoubleQuote struct { } type psSegment struct { - tokens []psToken - singleQuotes []string - doubleQuotes []psDoubleQuote + pipelineID int + tokens []psToken + singleQuotes []string + doubleQuotes []psDoubleQuote + hasCorruptedDollar bool } // PowerShellTextProblem reports a refusal reason when a PowerShell command -// passes a POSIX heredoc to teamhub (invalid on all PowerShell versions) or, -// when powerShell51 is true, passes embedded double quotes in native teamhub -// arguments that Windows PowerShell 5.1 strips before teamhub reads them. -// Clean commands return "". +// passes a POSIX heredoc to teamhub, would expand numeric dollar amounts or +// bash-escaped \$ in double quotes / double-quoted here-strings / bare words +// fed to teamhub (on all PowerShell versions), or when powerShell51 is true, +// passes embedded double quotes in native teamhub arguments that Windows +// PowerShell 5.1 strips before teamhub reads them. Clean commands return "". func PowerShellTextProblem(command string, powerShell51 bool) string { if !strings.Contains(strings.ToLower(command), "teamhub") || - (!strings.Contains(command, "<<") && (!powerShell51 || !strings.Contains(command, `"`))) { + (!strings.Contains(command, "<<") && !strings.Contains(command, "$") && (!powerShell51 || !strings.Contains(command, `"`))) { return "" } segments, hasUnquotedHeredoc := scanPowerShellSegments(command) var teamHubSegments []psSegment + teamHubPipelines := map[int]bool{} for _, segment := range segments { if hasPowerShellTeamHubInvocation(segment.tokens) { teamHubSegments = append(teamHubSegments, segment) + teamHubPipelines[segment.pipelineID] = true } } if len(teamHubSegments) == 0 { @@ -76,6 +91,11 @@ func PowerShellTextProblem(command string, powerShell51 bool) string { if hasUnquotedHeredoc { return PowerShellHeredocMessage } + for _, segment := range segments { + if teamHubPipelines[segment.pipelineID] && segment.hasCorruptedDollar { + return PowerShellDollarMessage + } + } if !powerShell51 { return "" } @@ -114,30 +134,83 @@ func isPSBoundaryByte(b byte) bool { return b == ' ' || b == '\t' || b == '\r' || b == '\n' || strings.IndexByte(";|&)+,}", b) >= 0 } -func skipPSHereString(script string, start int) int { +func skipPSHereString(script string, start int) (int, bool) { if start+2 > len(script) || script[start] != '@' || (script[start+1] != '\'' && script[start+1] != '"') { - return -1 + return -1, false } + doubleQuoted := script[start+1] == '"' closing := string([]byte{script[start+1], '@'}) pos := start + 2 for pos < len(script) && (script[pos] == ' ' || script[pos] == '\t' || script[pos] == '\r') { pos++ } if pos >= len(script) || script[pos] != '\n' { - return -1 + return -1, false } pos++ + bodyStart := pos for pos < len(script) { if strings.HasPrefix(script[pos:], closing) { - return pos + 2 + body := script[bodyStart:pos] + return pos + 2, doubleQuoted && hasPowerShellCorruptedDollar(body) } nl := strings.IndexByte(script[pos:], '\n') if nl < 0 { - return len(script) + body := script[bodyStart:] + return len(script), doubleQuoted && hasPowerShellCorruptedDollar(body) } pos += nl + 1 } - return len(script) + return len(script), doubleQuoted && hasPowerShellCorruptedDollar(script[bodyStart:]) +} + +func isASCIIByteDigit(b byte) bool { + return b >= '0' && b <= '9' +} + +func isPSDollarFollowByte(b byte) bool { + return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_' || b == '{' || b == '(' +} + +// isPowerShellCorruptedDollarAt reports whether s[i] (which must be '$') is an +// unescaped numeric dollar expansion (such as $6 in "$6.4M") or a bash-escaped +// \$ sequence that PowerShell does not treat as an escape. +func isPowerShellCorruptedDollarAt(s string, i int) bool { + if i+1 >= len(s) { + return false + } + next := s[i+1] + if isASCIIByteDigit(next) { + return true + } + if i > 0 && s[i-1] == '\\' && (i < 2 || s[i-2] != ':') && isPSDollarFollowByte(next) { + return true + } + return false +} + +// hasPowerShellCorruptedDollar scans the body of a double-quoted PowerShell +// string or double-quoted here-string, respecting backtick escapes and $(...) +// subexpressions. +func hasPowerShellCorruptedDollar(body string) bool { + for i := 0; i < len(body); i++ { + if body[i] == '`' && i+1 < len(body) { + _, size := utf8.DecodeRuneInString(body[i+1:]) + i += size + continue + } + if strings.HasPrefix(body[i:], "$(") { + if isPowerShellCorruptedDollarAt(body, i) { + return true + } + i = skipPSSubexpression(body, i) - 1 + continue + } + if body[i] == '$' && isPowerShellCorruptedDollarAt(body, i) { + return true + } + } + return false } func skipPSSubexpression(script string, start int) int { @@ -203,13 +276,15 @@ func skipPSSubexpression(script string, start int) int { func scanPowerShellSegments(script string) ([]psSegment, bool) { var segments []psSegment hasUnquotedHeredoc := false - var current psSegment + pipelineID := 0 + current := psSegment{pipelineID: pipelineID} var tokenText strings.Builder tokenKind := psTokenBare tokenDoubleQuoteSpans := 0 tokenHasBackslashQuoteBoundary := false tokenHasEscapedBareQuote := false inToken := false + afterPipe := false scriptBlockDepth := 0 literalBraceDepth := 0 @@ -238,13 +313,16 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { kind: psTokenBare, }) } - flushSegment := func() { + flushSegment := func(endPipeline bool) { flushToken() literalBraceDepth = 0 - if len(current.tokens) > 0 || len(current.singleQuotes) > 0 || len(current.doubleQuotes) > 0 { + if len(current.tokens) > 0 || len(current.singleQuotes) > 0 || len(current.doubleQuotes) > 0 || current.hasCorruptedDollar { segments = append(segments, current) - current = psSegment{} } + if endPipeline { + pipelineID++ + } + current = psSegment{pipelineID: pipelineID} } for i := 0; i < len(script); i++ { @@ -255,8 +333,12 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { } if (!inToken || strings.HasSuffix(tokenText.String(), "=") || strings.HasSuffix(tokenText.String(), ",")) && (strings.HasPrefix(script[i:], "@'") || strings.HasPrefix(script[i:], `@"`)) { - if end := skipPSHereString(script, i); end >= 0 { + if end, corruptedDollar := skipPSHereString(script, i); end >= 0 { flushToken() + afterPipe = false + if corruptedDollar { + current.hasCorruptedDollar = true + } i = end - 1 continue } @@ -287,24 +369,33 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { } tokenText.WriteRune(r) inToken = true + afterPipe = false i += size continue } } if ch == '\n' { - flushSegment() + // PowerShell allows a newline directly after a pipe operator to + // continue the same pipeline on the next line. + flushSegment(!afterPipe) continue } if ch == ';' || ch == '|' { - flushSegment() if ch == '|' && i+1 < len(script) && (script[i+1] == '|' || script[i+1] == '&') { + endPipeline := script[i+1] == '|' + flushSegment(endPipeline) + afterPipe = !endPipeline i++ + } else { + flushSegment(ch == ';') + afterPipe = ch == '|' } continue } + afterPipe = false if ch == '{' { if !inToken && !hasPowerShellTeamHubInvocation(current.tokens) { - flushSegment() + flushSegment(true) scriptBlockDepth++ continue } @@ -322,7 +413,7 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { } if scriptBlockDepth > 0 { scriptBlockDepth-- - flushSegment() + flushSegment(true) continue } tokenText.WriteByte(ch) @@ -330,6 +421,9 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { continue } if strings.HasPrefix(script[i:], "$(") { + if isPowerShellCorruptedDollarAt(script, i) { + current.hasCorruptedDollar = true + } pushBareToken("$(") i++ continue @@ -345,7 +439,7 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { } if ch == '&' { if i+1 < len(script) && script[i+1] == '&' { - flushSegment() + flushSegment(true) i++ continue } @@ -393,6 +487,7 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { } var inner strings.Builder hasEscapedQuote := false + hasCorruptedDollar := false i++ for i < len(script) { if script[i] == '`' && i+1 < len(script) { @@ -405,11 +500,17 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { continue } if strings.HasPrefix(script[i:], "$(") { + if isPowerShellCorruptedDollarAt(script, i) { + hasCorruptedDollar = true + } subEnd := skipPSSubexpression(script, i) inner.WriteString(script[i:subEnd]) i = subEnd continue } + if script[i] == '$' && isPowerShellCorruptedDollarAt(script, i) { + hasCorruptedDollar = true + } if script[i] == '"' { if i+1 < len(script) && script[i+1] == '"' { hasEscapedQuote = true @@ -427,6 +528,9 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { text: innerText, hasEscapedQuote: hasEscapedQuote, }) + if hasCorruptedDollar { + current.hasCorruptedDollar = true + } tokenDoubleQuoteSpans++ if i < len(script) && script[i] == '"' && strings.HasSuffix(innerText, `\`) && @@ -440,10 +544,13 @@ func scanPowerShellSegments(script string) ([]psSegment, bool) { inToken = true continue } + if ch == '$' && isPowerShellCorruptedDollarAt(script, i) { + current.hasCorruptedDollar = true + } tokenText.WriteByte(ch) inToken = true } - flushSegment() + flushSegment(true) return segments, hasUnquotedHeredoc } diff --git a/apps/computer/local-daemon/internal/permission/shell_text_powershell_test.go b/apps/computer/local-daemon/internal/permission/shell_text_powershell_test.go index 31718d3c46..88824b4af1 100644 --- a/apps/computer/local-daemon/internal/permission/shell_text_powershell_test.go +++ b/apps/computer/local-daemon/internal/permission/shell_text_powershell_test.go @@ -87,3 +87,44 @@ func TestPowerShellTextProblemAllowsSafeCommandsAndPS7(t *testing.T) { t.Errorf("PowerShellTextProblem(..., false) = %q, want empty", got) } } + +func TestPowerShellTextProblemBlocksCorruptedDollarsOnAllVersions(t *testing.T) { + for _, command := range []string{ + `teamhub message send --content "ARR is $6.4M"`, + `teamhub message send --content "200 seats @ \$540"`, + `teamhub message send --content "\$28,080"`, + `teamhub message send --content "Total \$ARR"`, + `teamhub message send --content "Computed \$(Get-Date)"`, + `teamhub message send --content $180`, + `Write-Output "Quote: $180" | teamhub message send --file -`, + "@\"\nARR is $6.4M\n\"@ | teamhub message send --file -", + "@\"\nARR is $6.4M\n\"@ |\nteamhub message send --file -", + "Write-Output \"Quote: $180\" |&\n# comment\nteamhub message send --file -", + "@\"\nPrice is \\$28,080\n\"@ | teamhub message send --file -", + } { + for _, ps51 := range []bool{false, true} { + if got := PowerShellTextProblem(command, ps51); got != PowerShellDollarMessage { + t.Errorf("PowerShellTextProblem(%q, %v) = %q, want PowerShellDollarMessage", command, ps51, got) + } + } + } + + // Single quotes, backtick-escaped $, single-quoted here-strings, named + // variables, drive paths, and separate statements remain allowed. + for _, command := range []string{ + `teamhub message send --content 'ARR is $6.4M and \$28,080'`, + "teamhub message send --content \"Price is `$180\"", + "@'\nARR is $6.4M and \\$28,080\n'@ | teamhub message send --file -", + `teamhub message send --content "Total: $total"`, + `teamhub message send --content "Date: $(Get-Date -Format 'yyyy-MM-dd')"`, + `teamhub docs create --title "Path: C:\$Recycle.Bin"`, + `Write-Output "$180"; teamhub message send --content "Done."`, + `node -e 'console.log("$180")'`, + } { + for _, ps51 := range []bool{false, true} { + if got := PowerShellTextProblem(command, ps51); got != "" { + t.Errorf("PowerShellTextProblem(%q, %v) = %q, want empty", command, ps51, got) + } + } + } +} diff --git a/apps/computer/local-daemon/internal/permission/shell_text_test.go b/apps/computer/local-daemon/internal/permission/shell_text_test.go index 11b9be45b4..0425c62050 100644 --- a/apps/computer/local-daemon/internal/permission/shell_text_test.go +++ b/apps/computer/local-daemon/internal/permission/shell_text_test.go @@ -111,9 +111,25 @@ func TestShellTextHookPowerShellAndPosixRouting(t *testing.T) { t.Fatalf("ps7 quotes = %d with %q, want 0", code, stderr.String()) } + // Both PowerShell 7 and 5.1 refuse numeric dollar amounts and \$ in double quotes. + for _, psDollar := range []string{ + `{"tool_name":"powershell","powershell_51":false,"tool_input":{"command":"teamhub message send --content \"ARR $6.4M\""}}`, + `{"tool_name":"powershell","powershell_51":false,"tool_input":{"command":"teamhub message send --content \"\\$28,080\""}}`, + `{"tool_name":"powershell","powershell_51":true,"tool_input":{"command":"teamhub message send --content \"ARR $6.4M\""}}`, + } { + stderr.Reset() + if code := ShellTextHook(strings.NewReader(psDollar), &stderr); code != 2 { + t.Errorf("ShellTextHook(%q) = %d, want 2", psDollar, code) + } + if strings.TrimSpace(stderr.String()) != PowerShellDollarMessage { + t.Errorf("ShellTextHook(%q) stderr = %q, want PowerShellDollarMessage", psDollar, stderr.String()) + } + } + // Bash and omitted tool_name remain routed to POSIX ShellTextRewritten. for _, posix := range []string{ `{"tool_name":"bash","tool_input":{"command":"teamhub message send --content \"$180\""}}`, + `{"tool_name":"bash","tool_input":{"command":"teamhub.exe message send --content \"$180\""}}`, `{"tool_input":{"command":"teamhub message send --content \"$180\""}}`, } { stderr.Reset() diff --git a/apps/computer/local-daemon/internal/protocol/types.go b/apps/computer/local-daemon/internal/protocol/types.go index cce4a1f935..74cc3d986c 100644 --- a/apps/computer/local-daemon/internal/protocol/types.go +++ b/apps/computer/local-daemon/internal/protocol/types.go @@ -91,6 +91,7 @@ type Event struct { ThroughSequence uint64 `json:"through_seq,omitempty"` Sequence uint64 `json:"seq,omitempty"` Revision uint64 `json:"revision,omitempty"` + WindowsGitBash *bool `json:"windows_git_bash,omitempty"` SentAt time.Time `json:"sent_at"` Payload json.RawMessage `json:"payload,omitempty"` } diff --git a/apps/computer/local-daemon/internal/provider/executor.go b/apps/computer/local-daemon/internal/provider/executor.go index 1805ae53d7..dd47a293f6 100644 --- a/apps/computer/local-daemon/internal/provider/executor.go +++ b/apps/computer/local-daemon/internal/provider/executor.go @@ -131,6 +131,11 @@ type Executor struct { // of a models cache for a Context's new home. CodexModelSessionHome string PiMCPExtension string + WindowsGitBashPath string + // WindowsGitBashEnabled gates WindowsGitBashPath dynamically on whether the + // connected Agent Service negotiated windows_git_bash. Nil enables + // WindowsGitBashPath whenever non-empty. + WindowsGitBashEnabled func() bool // ManagedPiRoots resolves the verified Linger-managed Pi profile roots // for syncing managed Pi settings. ManagedPiRoots func() []string @@ -142,6 +147,13 @@ type Executor struct { ShellTextHook string } +func (e Executor) activeWindowsGitBashPath() string { + if e.WindowsGitBashEnabled != nil && !e.WindowsGitBashEnabled() { + return "" + } + return e.WindowsGitBashPath +} + // SyncPiCompactionSettings updates Linger-managed Pi compaction overrides for // spec.Model and spec.ContextWindow off the Daemon admission lock. func (e Executor) SyncPiCompactionSettings(spec OperationSpec) { @@ -538,6 +550,7 @@ func (e Executor) Start(ctx context.Context, spec OperationSpec, emit EmitFunc) backend, err := newBackend(spec.Provider, native.Profile{ Program: spec.ExecutablePath, ManagedMCPExtension: e.PiMCPExtension, + WindowsGitBashPath: e.activeWindowsGitBashPath(), Env: environment, RetainProcessTemp: retainProcessTemp, TempBase: e.TempBase, diff --git a/apps/computer/local-daemon/internal/provider/native/pi_fake_test.go b/apps/computer/local-daemon/internal/provider/native/pi_fake_test.go index 7acd563884..01c5da64a6 100644 --- a/apps/computer/local-daemon/internal/provider/native/pi_fake_test.go +++ b/apps/computer/local-daemon/internal/provider/native/pi_fake_test.go @@ -145,6 +145,7 @@ func piFake(mode string, args []string) int { _ = os.WriteFile(path, []byte(strings.Join(args, "\n")), 0o600) _ = os.WriteFile(path+".node_path", []byte(os.Getenv(piNodePathKey)), 0o600) _ = os.WriteFile(path+".shell_text_hook", []byte(os.Getenv(piShellTextHookEnvKey)), 0o600) + _ = os.WriteFile(path+".git_bash_path", []byte(os.Getenv(piGitBashPathEnvKey)), 0o600) } reader := bufio.NewReader(os.Stdin) for { diff --git a/apps/computer/local-daemon/internal/provider/native/pi_mcp.go b/apps/computer/local-daemon/internal/provider/native/pi_mcp.go index 1911fcce06..ccaed47419 100644 --- a/apps/computer/local-daemon/internal/provider/native/pi_mcp.go +++ b/apps/computer/local-daemon/internal/provider/native/pi_mcp.go @@ -16,6 +16,8 @@ const ( piInheritedNodePathKey = "LINGER_PI_INHERITED_NODE_PATH" // The Daemon executable the managed extension runs as shell-text-hook. piShellTextHookEnvKey = "LINGER_PI_SHELL_TEXT_HOOK" + // The resolved non-WSL Git Bash executable on Windows passed to Pi's bash tool. + piGitBashPathEnvKey = "LINGER_PI_GIT_BASH_PATH" ) // piMCPWiring is the managed MCP set prepared for one Pi process. A zero diff --git a/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup.go b/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup.go index 277271388e..d4b248a472 100644 --- a/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup.go +++ b/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup.go @@ -68,7 +68,11 @@ func WarmupPiPrefix(ctx context.Context, profile Profile, dir, instructionsFile, } env[piStrataPinEnvKey] = string(pinJSON) piExtensionNodePath(env, profile.ManagedMCPExtension) - tools := piBaseToolsFor(runtime.GOOS) + hasWindowsGitBash := runtime.GOOS == "windows" && strings.TrimSpace(profile.WindowsGitBashPath) != "" + if hasWindowsGitBash { + env[piGitBashPathEnvKey] = strings.TrimSpace(profile.WindowsGitBashPath) + } + tools := piBaseToolsFor(runtime.GOOS, hasWindowsGitBash) if mcp.wired() { env[piMCPConfigEnvKey] = mcp.configPath tools += ",tool_search,mcp__*" diff --git a/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup_test.go b/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup_test.go index 922464baea..1e80288b50 100644 --- a/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup_test.go +++ b/apps/computer/local-daemon/internal/provider/native/pi_prefix_warmup_test.go @@ -37,7 +37,7 @@ func TestWarmupPiPrefix(t *testing.T) { Anchor: "", } - baseTools := piBaseToolsFor(runtime.GOOS) + baseTools := piBaseToolsFor(runtime.GOOS, false) for _, tc := range []struct { name string mcpConfig json.RawMessage diff --git a/apps/computer/local-daemon/internal/provider/native/pi_prestart_test.go b/apps/computer/local-daemon/internal/provider/native/pi_prestart_test.go index caf6c22560..21c3acec9e 100644 --- a/apps/computer/local-daemon/internal/provider/native/pi_prestart_test.go +++ b/apps/computer/local-daemon/internal/provider/native/pi_prestart_test.go @@ -63,7 +63,7 @@ func TestPiPrestartAdoptedByCreateRunAndAttachesMCP(t *testing.T) { t.Fatal(err) } argv := strings.Split(strings.TrimSpace(string(argvData)), "\n") - if !slices.Contains(argv, "--extension") || !slices.Contains(argv, extension) || !slices.Contains(argv, piBaseToolsFor(runtime.GOOS)+",tool_search,mcp__*") { + if !slices.Contains(argv, "--extension") || !slices.Contains(argv, extension) || !slices.Contains(argv, piBaseToolsFor(runtime.GOOS, false)+",tool_search,mcp__*") { t.Fatalf("pre-start argv = %q", argv) } diff --git a/apps/computer/local-daemon/internal/provider/native/pi_runtime.go b/apps/computer/local-daemon/internal/provider/native/pi_runtime.go index d5423166f8..fe89b83967 100644 --- a/apps/computer/local-daemon/internal/provider/native/pi_runtime.go +++ b/apps/computer/local-daemon/internal/provider/native/pi_runtime.go @@ -13,23 +13,23 @@ import ( ) const ( - piDefaultModel = "pi-default" - piBaseTools = "read,bash,edit,write,grep,find,ls" - piWindowsBaseTools = "read,powershell,edit,write,grep,find,ls" - piChildPipeDrain = time.Second + piDefaultModel = "pi-default" + piBaseTools = "read,bash,edit,write,grep,find,ls" + piWindowsPowerShellBaseTools = "read,powershell,edit,write,grep,find,ls" + piWindowsBaseTools = "read,bash,powershell,edit,write,grep,find,ls" + piChildPipeDrain = time.Second ) // piAuthCheckTimeout bounds the pre-flight `pi auth check`. A var so tests can // shorten it without waiting the production budget. var piAuthCheckTimeout = 15 * time.Second -func piUsesPowerShell(goos string) bool { - return goos == "windows" -} - -func piBaseToolsFor(goos string) string { - if piUsesPowerShell(goos) { - return piWindowsBaseTools +func piBaseToolsFor(goos string, hasWindowsGitBash bool) string { + if goos == "windows" { + if hasWindowsGitBash { + return piWindowsBaseTools + } + return piWindowsPowerShellBaseTools } return piBaseTools } @@ -308,6 +308,9 @@ func (p *piRuntime) launchProcess(ctx context.Context, plan piLaunchPlan, lock * } if p.profile.ManagedMCPExtension != "" { piExtensionNodePath(env, p.profile.ManagedMCPExtension) + if p.goos() == "windows" && strings.TrimSpace(p.profile.WindowsGitBashPath) != "" { + env[piGitBashPathEnvKey] = strings.TrimSpace(p.profile.WindowsGitBashPath) + } } if p.guardsShellText(spec) { env[piShellTextHookEnvKey] = spec.ShellTextHook @@ -401,7 +404,7 @@ func (p *piRuntime) args(plan piLaunchPlan, instructions string, wired bool) []s // guard, permission review, and the Windows PowerShell UTF-8 override. Its // tool_call hook asks the Daemon over RPC for each bash, powershell, and // MCP call, which the Daemon allows when permission review is off. - tools := piBaseToolsFor(p.goos()) + tools := piBaseToolsFor(p.goos(), strings.TrimSpace(p.profile.WindowsGitBashPath) != "") if p.profile.ManagedMCPExtension != "" { args = append(args, "--extension", p.profile.ManagedMCPExtension) } diff --git a/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.go b/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.go index a56e625074..cdecfc8984 100644 --- a/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.go +++ b/apps/computer/local-daemon/internal/provider/native/pi_runtime_test.go @@ -607,7 +607,7 @@ func TestPiLaunchArguments(t *testing.T) { t.Fatalf("outcome = %+v", outcome) } data, _ := os.ReadFile(argv) - baseTools := piBaseToolsFor(runtime.GOOS) + baseTools := piBaseToolsFor(runtime.GOOS, false) sessionDir := filepath.Join(h.root, "args-session") want := append([]string{"--mode", "rpc", "--session-dir", sessionDir, "--session-id", "args-session"}, PiRPCResourceArgs(filepath.Join(sessionDir, piInstructionsName))...) want = append(want, "--model", "fixture/model", "--thinking", "off", "--name", "Title", @@ -636,18 +636,14 @@ func TestPiLaunchArguments(t *testing.T) { t.Fatalf("default NODE_PATH = %q, want %q", nodePath, wantNodePath) } - // On POSIX the managed extension runs the shell-text-hook without MCP servers; - // on Windows PowerShell skips the POSIX shell text check while still loading - // the managed extension for UTF-8 encoding. + // The managed extension runs shell-text-hook on both POSIX and Windows + // (covering bash and powershell) without MCP servers. _, outcome = piCollect(t, h.start(t.Context(), "go", RunSpec{Model: piDefaultModel, ShellTextHook: "/opt/linger/linger-computer-daemon"})) data, _ = os.ReadFile(argv) if outcome.Status != statusCompleted || !strings.HasSuffix(string(data), "--extension\n"+extension+"\n--tools\n"+baseTools) { t.Fatalf("shell text argv = %q (%+v)", data, outcome) } wantHook := "/opt/linger/linger-computer-daemon" - if piUsesPowerShell(runtime.GOOS) { - wantHook = "" - } if hook, _ := os.ReadFile(argv + ".shell_text_hook"); string(hook) != wantHook { t.Fatalf("%s = %q, want %q", piShellTextHookEnvKey, hook, wantHook) } @@ -745,11 +741,17 @@ func TestPiPlatformLaunchArgumentsAndEnvironment(t *testing.T) { } wantNodePath := filepath.Join(filepath.Dir(filepath.Dir(extension)), "node_modules") - t.Run("windows with managed extension", func(t *testing.T) { + t.Run("windows with managed extension and git bash", func(t *testing.T) { argv := filepath.Join(t.TempDir(), "argv") h := piNewHarness(t, "finish", map[string]string{piFakeArgvEnv: argv}) + const gitBash = `C:\Linger\resources\runtime\git-bash\bin\bash.exe` rt := &piRuntime{ - profile: Profile{Program: h.runtime.(*piRuntime).profile.Program, Env: h.env, ManagedMCPExtension: extension}, + profile: Profile{ + Program: h.runtime.(*piRuntime).profile.Program, + Env: h.env, + ManagedMCPExtension: extension, + WindowsGitBashPath: gitBash, + }, goosOverride: "windows", } h.runtime = rt @@ -764,6 +766,9 @@ func TestPiPlatformLaunchArgumentsAndEnvironment(t *testing.T) { if hook, _ := os.ReadFile(argv + ".shell_text_hook"); len(hook) != 0 { t.Fatalf("windows default %s = %q, want empty", piShellTextHookEnvKey, hook) } + if bashPath, _ := os.ReadFile(argv + ".git_bash_path"); string(bashPath) != gitBash { + t.Fatalf("windows %s = %q, want %q", piGitBashPathEnvKey, bashPath, gitBash) + } spec := RunSpec{Model: piDefaultModel, ShellTextHook: "/opt/linger/linger-computer-daemon"} if !rt.guardsShellText(spec) { @@ -817,6 +822,27 @@ func TestPiPlatformLaunchArgumentsAndEnvironment(t *testing.T) { } }) + t.Run("windows without git bash falls back to powershell only", func(t *testing.T) { + argv := filepath.Join(t.TempDir(), "argv") + h := piNewHarness(t, "finish", map[string]string{piFakeArgvEnv: argv}) + rt := &piRuntime{ + profile: Profile{Program: h.runtime.(*piRuntime).profile.Program, Env: h.env, ManagedMCPExtension: extension}, + goosOverride: "windows", + } + h.runtime = rt + + if _, outcome := piCollect(t, h.start(t.Context(), "go", RunSpec{Model: piDefaultModel})); outcome.Status != statusCompleted { + t.Fatalf("outcome = %+v", outcome) + } + data, _ := os.ReadFile(argv) + if !strings.HasSuffix(string(data), "--extension\n"+extension+"\n--tools\n"+piWindowsPowerShellBaseTools) { + t.Fatalf("bash-less windows argv = %q", data) + } + if bashPath, _ := os.ReadFile(argv + ".git_bash_path"); len(bashPath) != 0 { + t.Fatalf("bash-less windows %s = %q, want empty", piGitBashPathEnvKey, bashPath) + } + }) + t.Run("windows without managed extension", func(t *testing.T) { argv := filepath.Join(t.TempDir(), "argv") h := piNewHarness(t, "finish", map[string]string{piFakeArgvEnv: argv}) @@ -830,7 +856,7 @@ func TestPiPlatformLaunchArgumentsAndEnvironment(t *testing.T) { t.Fatalf("outcome = %+v", outcome) } data, _ := os.ReadFile(argv) - if strings.Contains(string(data), "--extension") || !strings.HasSuffix(string(data), "--tools\n"+piWindowsBaseTools) { + if strings.Contains(string(data), "--extension") || !strings.HasSuffix(string(data), "--tools\n"+piWindowsPowerShellBaseTools) { t.Fatalf("windows without extension argv = %q", data) } if nodePath, _ := os.ReadFile(argv + ".node_path"); len(nodePath) != 0 { diff --git a/apps/computer/local-daemon/internal/provider/native/runtime.go b/apps/computer/local-daemon/internal/provider/native/runtime.go index b4ef6720c0..3be8967615 100644 --- a/apps/computer/local-daemon/internal/provider/native/runtime.go +++ b/apps/computer/local-daemon/internal/provider/native/runtime.go @@ -79,7 +79,12 @@ type Profile struct { ContextKey string AgentID string ManagedMCPExtension string - CodexConfigArgs []string + // WindowsGitBashPath holds the resolved non-WSL Git Bash executable on + // Windows when available. Non-empty enables dual bash+powershell tools on + // Windows Pi and passes shellPath explicitly to the managed Pi extension; + // empty keeps Windows Pi in PowerShell-only mode. + WindowsGitBashPath string + CodexConfigArgs []string // ResidentSkillDigest identifies the Skills the Daemon delivered to this // Operation. A parked process serves only the same digest. ResidentSkillDigest string diff --git a/apps/computer/tests/computer-tools.test.ts b/apps/computer/tests/computer-tools.test.ts index defb5349bb..b956a8467e 100644 --- a/apps/computer/tests/computer-tools.test.ts +++ b/apps/computer/tests/computer-tools.test.ts @@ -116,7 +116,10 @@ process.stdin.on("end", () => { assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "Total $TOTAL"'), hook), undefined); assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "Done."'), hook), undefined); assert.equal(await refuseRewrittenShellText({ toolName: "read", input: { path: "$1" } }, hook), undefined); - assert.equal(await refuseRewrittenShellText({ toolName: "powershell", input: { command: 'teamhub message send --content "Quote: $180"' } }, hook), undefined); + assert.deepEqual( + await refuseRewrittenShellText({ toolName: "powershell", input: { command: 'teamhub message send --content "Quote: $180"' } }, hook), + { block: true, reason: "Not run: use a quoted heredoc" }, + ); assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "$180"'), ${JSON.stringify(path.join(root, "missing"))}), undefined); assert.equal(await refuseRewrittenShellText(bash('teamhub message send --content "$180"'), undefined), undefined); console.log("shell text check passed"); @@ -268,6 +271,173 @@ it("registers the UTF-8 PowerShell override only on Windows", async () => { ]); }); +it("registers the Windows Git Bash override only on Windows with MSYS_NO_PATHCONV", async () => { + const entry = new URL("../tools/pi-mcp.mjs", import.meta.url).href; + const { + WINDOWS_BASH_ENV, + WINDOWS_BASH_PREFIX, + applyWindowsBashEnv, + registerWindowsBashTool, + } = (await import(entry)) as { + WINDOWS_BASH_ENV: Record; + WINDOWS_BASH_PREFIX: string; + applyWindowsBashEnv: ( + env?: Record, + ) => Record; + registerWindowsBashTool: ( + pi: { registerTool?: (tool: Record) => void }, + options?: { + platform?: string; + cwd?: string; + shellPath?: string; + createToolDefinition?: ( + cwd: string, + opts?: Record, + ) => Record; + operations?: { + exec: ( + command: string, + cwd: string, + options: { + onData: (data: Buffer) => void; + env?: Record; + }, + ) => Promise<{ exitCode: number }>; + }; + }, + ) => boolean; + }; + + const registered: Array> = []; + const fakePi = { + registerTool: (tool: Record) => { + registered.push(tool); + }, + }; + + expect(registerWindowsBashTool(fakePi, { platform: "darwin" })).toBe(false); + expect(registerWindowsBashTool(fakePi, { platform: "linux" })).toBe(false); + expect(registerWindowsBashTool({}, { platform: "win32" })).toBe(false); + expect(registered).toEqual([]); + + // Inherited MSYS/locale overrides lose to WINDOWS_BASH_ENV case-insensitively. + const mergedEnv = applyWindowsBashEnv({ + msys_no_pathconv: "0", + MSYS2_ARG_CONV_EXCL: "", + lc_all: "C", + LANG: "C", + KEEP_ME: "yes", + }); + expect(mergedEnv).toEqual({ + KEEP_ME: "yes", + ...WINDOWS_BASH_ENV, + }); + + // Verify shellPath forwarding without passing custom operations (which would + // bypass createLocalBashOperations({ shellPath })). + const capturedCalls: Array<{ + cwd: string; + opts?: Record; + }> = []; + const stubOk = registerWindowsBashTool(fakePi, { + platform: "win32", + cwd: "C:\\workspace", + shellPath: " C:\\Linger\\resources\\runtime\\git-bash\\bin\\bash.exe ", + createToolDefinition: (cwd, opts) => { + capturedCalls.push({ cwd, opts }); + return { name: "bash", stub: true }; + }, + }); + expect(stubOk).toBe(true); + expect(capturedCalls).toHaveLength(1); + expect(capturedCalls[0]?.cwd).toBe("C:\\workspace"); + expect(capturedCalls[0]?.opts?.shellPath).toBe( + "C:\\Linger\\resources\\runtime\\git-bash\\bin\\bash.exe", + ); + expect(capturedCalls[0]?.opts?.commandPrefix).toBe(WINDOWS_BASH_PREFIX); + expect(capturedCalls[0]?.opts?.operations).toBeUndefined(); + registered.length = 0; + + // Verify module-load consumption and deletion of LINGER_PI_GIT_BASH_PATH in a + // fresh child process so child commands never inherit the env var. + const envBashPath = "C:\\Linger\\resources\\runtime\\git-bash\\bin\\bash.exe"; + const child = await run( + process.execPath, + [ + "--input-type=module", + "--eval", + ` + import assert from "node:assert/strict"; + const mod = await import(${JSON.stringify(entry)}); + assert.equal(process.env.LINGER_PI_GIT_BASH_PATH, undefined); + let seenOpts; + const ok = mod.registerWindowsBashTool( + { registerTool() {} }, + { + platform: "win32", + cwd: "C:\\\\workspace", + createToolDefinition: (_cwd, opts) => { + seenOpts = opts; + return { name: "bash" }; + }, + }, + ); + assert.equal(ok, true); + assert.equal(seenOpts?.shellPath, ${JSON.stringify(envBashPath)}); + process.stdout.write("git-bash-env-consumed"); + `, + ], + { + timeout: 20_000, + env: { + ...process.env, + LINGER_PI_GIT_BASH_PATH: envBashPath, + }, + }, + ); + expect(child.stdout).toBe("git-bash-env-consumed"); + + const executed: Array<{ + command: string; + cwd: string; + env?: Record; + }> = []; + const ok = registerWindowsBashTool(fakePi, { + platform: "win32", + cwd: "C:\\workspace", + shellPath: envBashPath, + operations: { + exec: async (command, cwd, { onData, env }) => { + executed.push({ command, cwd, env }); + onData(Buffer.from("ok\n", "utf8")); + return { exitCode: 0 }; + }, + }, + }); + expect(ok).toBe(true); + expect(registered).toHaveLength(1); + const tool = registered[0]; + expect(tool?.name).toBe("bash"); + const execute = tool?.execute as ( + toolCallId: string, + params: { command: string }, + ) => Promise; + await execute("call_1", { + command: 'teamhub message send --content "/plan"', + }); + expect(executed).toHaveLength(1); + expect(executed[0]?.command).toBe( + `${WINDOWS_BASH_PREFIX}\nteamhub message send --content "/plan"`, + ); + expect(executed[0]?.cwd).toBe("C:\\workspace"); + expect(executed[0]?.env).toMatchObject({ + MSYS_NO_PATHCONV: WINDOWS_BASH_ENV.MSYS_NO_PATHCONV, + MSYS2_ARG_CONV_EXCL: WINDOWS_BASH_ENV.MSYS2_ARG_CONV_EXCL, + LC_ALL: WINDOWS_BASH_ENV.LC_ALL, + }); + expect(executed[0]?.env?.LANG).toContain("UTF-8"); +}); + it("synchronizes managed MCP servers dynamically and reports structured verdicts", async () => { const root = await mkdtemp(path.join(tmpdir(), "linger-pi-sync-mcp-")); try { @@ -1364,6 +1534,10 @@ process.stdin.on("end", () => { process.stderr.write("Not run: PowerShell does not support POSIX heredocs\\n"); process.exit(2); } + if (payload.tool_input.command.includes("$6")) { + process.stderr.write("Not run: PowerShell would rewrite numeric dollar text\\n"); + process.exit(2); + } if (payload.powershell_51 && payload.tool_input.command.includes("'[{")) { process.stderr.write("Not run: Windows PowerShell 5.1 strips embedded double quotes\\n"); process.exit(2); @@ -1462,6 +1636,17 @@ process.stdin.on("end", () => { reason: "Not run: PowerShell does not support POSIX heredocs", }); + // PowerShell 7 with $ invokes shell-text-hook with powershell_51: false. + const dollarCmd = 'teamhub message send --content "ARR $6.4M"'; + expect( + await refuseRewrittenShellText(ps(dollarCmd), hook, { + isPowerShell51: isPs51False, + }), + ).toEqual({ + block: true, + reason: "Not run: PowerShell would rewrite numeric dollar text", + }); + // Missing or unset hook fails open. expect( await refuseRewrittenShellText( @@ -1507,6 +1692,14 @@ process.stdin.on("end", () => { tool_input: { command: heredocCmd }, }, }, + { + argv: ["shell-text-hook"], + payload: { + tool_name: "powershell", + powershell_51: false, + tool_input: { command: dollarCmd }, + }, + }, ]); } finally { await rm(root, { recursive: true, force: true }); diff --git a/apps/computer/tools/pi-mcp.mjs b/apps/computer/tools/pi-mcp.mjs index ea4f7ac380..07a858509a 100644 --- a/apps/computer/tools/pi-mcp.mjs +++ b/apps/computer/tools/pi-mcp.mjs @@ -14,6 +14,10 @@ if (process.env.LINGER_PI_INHERITED_NODE_PATH !== undefined) { // before Pi runs it; the commands Pi starts do not inherit it. const shellTextHook = process.env.LINGER_PI_SHELL_TEXT_HOOK; delete process.env.LINGER_PI_SHELL_TEXT_HOOK; +// The resolved non-WSL Git Bash executable on Windows; consumed at load so +// child processes never inherit it and WSL System32\bash.exe cannot hijack Pi. +const windowsGitBashPath = process.env.LINGER_PI_GIT_BASH_PATH; +delete process.env.LINGER_PI_GIT_BASH_PATH; // One-shot prefix warm-up pin metadata consumed at extension load; cleared // immediately so child processes never observe it. const strataPinEnvRaw = process.env.LINGER_PI_STRATA_PIN; @@ -24,6 +28,7 @@ const { SettingsManager, compact, convertToLlm, + createBashToolDefinition, createMcpExtension, createPowerShellToolDefinition, createToolSearchExtension, @@ -70,6 +75,80 @@ export function registerWindowsPowerShellTool( return true; } +// Defaults applied to Windows Git Bash invocations so MSYS2 does not rewrite +// native CLI flags such as "/plan" or "/api/v1" into Git install paths and +// stdio stays UTF-8. +export const WINDOWS_BASH_ENV = Object.freeze({ + MSYS_NO_PATHCONV: "1", + MSYS2_ARG_CONV_EXCL: "*", + LANG: "C.UTF-8", + LC_ALL: "C.UTF-8", +}); + +const WINDOWS_BASH_ENV_KEYS_LOWER = new Set( + Object.keys(WINDOWS_BASH_ENV).map((key) => key.toLowerCase()), +); + +export function applyWindowsBashEnv(env) { + const cleaned = {}; + for (const [key, value] of Object.entries(env ?? {})) { + if (!WINDOWS_BASH_ENV_KEYS_LOWER.has(key.toLowerCase())) { + cleaned[key] = value; + } + } + return { + ...cleaned, + ...WINDOWS_BASH_ENV, + }; +} + +// Git Bash resolves extensionless `teamhub` before `teamhub.exe`; when +// MSYS_NO_PATHCONV=1 is active, older POSIX `teamhub` shims pass `/c/...` +// script paths to native Windows Node/Electron and fail. Routing `teamhub` +// directly to `teamhub.exe` keeps Git Bash invocations fast and immune to path +// conversion issues across Desktop versions. +export const WINDOWS_BASH_PREFIX = + 'if command -v teamhub.exe >/dev/null 2>&1; then teamhub() { command teamhub.exe "$@"; }; export -f teamhub; fi'; + +// Overrides Pi's built-in bash tool on Windows so Git Bash runs with MSYS2 +// path conversion disabled, UTF-8 locale defaults, explicit shellPath (preventing +// WSL System32\bash.exe hijacking), and direct teamhub.exe dispatch. Pi activates +// the tool only when --tools allows "bash". +export function registerWindowsBashTool( + pi, + { + platform = process.platform, + cwd = process.cwd(), + createToolDefinition = createBashToolDefinition, + shellPath = windowsGitBashPath, + operations, + } = {}, +) { + if ( + platform !== "win32" || + typeof pi?.registerTool !== "function" || + typeof createToolDefinition !== "function" + ) { + return false; + } + const resolvedShellPath = + typeof shellPath === "string" && shellPath.trim() + ? shellPath.trim() + : undefined; + pi.registerTool( + createToolDefinition(cwd, { + commandPrefix: WINDOWS_BASH_PREFIX, + ...(resolvedShellPath ? { shellPath: resolvedShellPath } : {}), + ...(operations ? { operations } : {}), + spawnHook: (context) => ({ + ...context, + env: applyWindowsBashEnv(context.env), + }), + }), + ); + return true; +} + // This explicit extension uses Pi's public MCP implementation. It does not // discover ambient configuration or create another Agent execution loop. // Managed loopback MCP servers (including `computer`) default to direct @@ -220,14 +299,16 @@ export async function refuseRewrittenShellText( } let payload; if (event.toolName === "bash") { - if (!command.includes("teamhub") || !/[$`]/u.test(command)) { + if (!TEAMHUB_PROGRAM_PATTERN.test(command) || !/[$`]/u.test(command)) { return undefined; } payload = { tool_name: "bash", tool_input: { command } }; } else if (event.toolName === "powershell") { + const hasDollar = command.includes("$"); + const hasHeredoc = command.includes("<<"); if ( !TEAMHUB_PROGRAM_PATTERN.test(command) || - (!command.includes('"') && !command.includes("<<")) + (!command.includes('"') && !hasHeredoc && !hasDollar) ) { return undefined; } @@ -235,7 +316,7 @@ export async function refuseRewrittenShellText( typeof isPowerShell51 === "function" ? Boolean(isPowerShell51()) : isWindowsPowerShell51(); - if (!ps51 && !command.includes("<<")) { + if (!ps51 && !hasHeredoc && !hasDollar) { return undefined; } payload = { @@ -2909,6 +2990,7 @@ export function registerIncompleteResponseGuard(pi) { // neither run nor rewritten. export default async function managedExtension(pi) { registerWindowsPowerShellTool(pi); + registerWindowsBashTool(pi); const strataPinConfig = parseStrataPinConfig(strataPinEnvRaw); registerProviderRequestTelemetry(pi); registerKvCacheTelemetry(pi, { strataPinActive: Boolean(strataPinConfig) }); diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.md index 249ad41ba8..ba5928a15a 100644 --- a/apps/desktop/AGENTS.md +++ b/apps/desktop/AGENTS.md @@ -1171,9 +1171,13 @@ Gateway and runs Agents. The daemon exits with the app. On Windows, `packaging/win/package.py` also stages a pinned portable PowerShell 7 LTS runtime (`PowerShell-7.6.10-win-x64.zip`, verified by SHA-256 and reused from `~/.cache/linger-desktop` or `PWSH_MIRROR`) into - `resources/runtime/pwsh/`; the Daemon appends that directory to the end of - Windows Runtime `PATH` so Agents resolve `pwsh.exe` without overriding user - installs or system DLLs. + `resources/runtime/pwsh/` and a pinned PortableGit runtime + (`PortableGit-2.56.0.4-64-bit.7z.exe`, verified by SHA-256 and reused from + `~/.cache/linger-desktop` or `GIT_BASH_MIRROR`, with GUI/doc files pruned) + into `resources/runtime/git-bash/`; the Daemon appends those directories to + the end of Windows Runtime `PATH` (and sets `MSYS_NO_PATHCONV=1`) so Agents + resolve `pwsh.exe` and `bash.exe` without overriding user installs or system + DLLs. `scripts/build-native-runtime.mjs` pins that shared `resources/runtime/bin/node(.exe)` digest in `manifest.json` (`node.shared: true`) instead of duplicating Node.js inside `dist/installer/native/runtime-/`, and `packaging/mac/package.py` diff --git a/apps/desktop/packaging/win/Dockerfile b/apps/desktop/packaging/win/Dockerfile index 3bc7e2c391..7b1d1cd3b1 100644 --- a/apps/desktop/packaging/win/Dockerfile +++ b/apps/desktop/packaging/win/Dockerfile @@ -1,7 +1,7 @@ FROM ubuntu:24.04 RUN apt-get -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 -o Acquire::Retries=3 update && \ apt-get -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 -o Acquire::Retries=3 install -y --no-install-recommends \ - ca-certificates nsis nodejs npm && \ + ca-certificates nsis nodejs npm p7zip-full && \ rm -rf /var/lib/apt/lists/* # resources.mjs writes the icon and version into Linger.exe. RUN npm install -g --fetch-timeout=30000 --fetch-retries=3 resedit@3.1.0 && npm cache clean --force diff --git a/apps/desktop/packaging/win/package.py b/apps/desktop/packaging/win/package.py index 616123f7ba..2e02262cde 100644 --- a/apps/desktop/packaging/win/package.py +++ b/apps/desktop/packaging/win/package.py @@ -21,7 +21,8 @@ The Go daemon goes to resources/computer/ and the browser and computer-control tools it loads to resources/cli/ and resources/runtime/ (../computer_tools.py); -a portable PowerShell 7 runtime goes to resources/runtime/pwsh/ on Windows, and +a portable PowerShell 7 runtime goes to resources/runtime/pwsh/ and a portable +Git Bash runtime goes to resources/runtime/git-bash/ on Windows, and the finished zip is checked for them. With a bundled source package, the TeamHub binaries and the Native runtime build.mjs built from it must be there and match their manifests and that package (../native_bundle.py). @@ -53,6 +54,22 @@ PWSH_ARCHIVE_ENTRY = "Linger/resources/runtime/pwsh/pwsh.exe" PWSH_DEFAULT_MIRROR = "https://github.com/PowerShell/PowerShell/releases/download/" +GIT_BASH_VERSION = "2.56.0.4" +GIT_BASH_TAG = "v2.56.0.windows.4" +GIT_BASH_ARCHIVE = f"PortableGit-{GIT_BASH_VERSION}-64-bit.7z.exe" +GIT_BASH_SHA256 = "b1f3e52216e2ed6882d1bebfd4d3fdf319bec40d2edbbf9fd26ec4fd3fce7ed1" +GIT_BASH_ARCHIVE_ENTRY = "Linger/resources/runtime/git-bash/bin/bash.exe" +GIT_BASH_DEFAULT_MIRROR = "https://github.com/git-for-windows/git/releases/download/" +GIT_BASH_PRUNE_PATHS = ( + "mingw64/share/doc", + "mingw64/libexec/git-core/git-gui", + "mingw64/libexec/git-core/git-gui--askpass", + "mingw64/libexec/git-core/gitk", + "cmd/git-gui.exe", + "git-bash.exe", + "ReleaseNotes.html", +) + def verify_teamhub_cli_archive(archive): """Exits unless the finished zip holds a non-empty teamhub.exe and no teamhub.cmd.""" @@ -68,16 +85,26 @@ def verify_teamhub_cli_archive(archive): sys.exit(f"{os.path.basename(archive)} must not contain {TEAMHUB_ARCHIVE_LEGACY_CMD}") -def verify_pwsh_archive(archive): - """Exits unless the finished zip holds a non-empty bundled pwsh.exe.""" +def _verify_archive_entry(archive, entry): + """Exits unless the finished zip holds a non-empty entry.""" with zipfile.ZipFile(archive) as source: sizes = { info.filename.replace("\\", "/"): info.file_size for info in source.infolist() if not info.is_dir() } - if not sizes.get(PWSH_ARCHIVE_ENTRY): - sys.exit(f"{os.path.basename(archive)} is missing non-empty {PWSH_ARCHIVE_ENTRY}") + if not sizes.get(entry): + sys.exit(f"{os.path.basename(archive)} is missing non-empty {entry}") + + +def verify_pwsh_archive(archive): + """Exits unless the finished zip holds a non-empty bundled pwsh.exe.""" + _verify_archive_entry(archive, PWSH_ARCHIVE_ENTRY) + + +def verify_git_bash_archive(archive): + """Exits unless the finished zip holds a non-empty bundled Git Bash bash.exe.""" + _verify_archive_entry(archive, GIT_BASH_ARCHIVE_ENTRY) def run(*args, **kwargs): @@ -102,26 +129,26 @@ def electron_zip(version, cache): return path -def pwsh_zip(cache): - """Returns the cached PowerShell 7 archive path after verifying SHA-256.""" +def _cached_verified_archive(cache, filename, expected_sha256, mirror_env, default_mirror, release_tag): + """Returns a cached archive path after verifying its SHA-256 digest.""" os.makedirs(cache, exist_ok=True) - path = os.path.join(cache, PWSH_ARCHIVE) + path = os.path.join(cache, filename) if os.path.exists(path): - if sha256(path) == PWSH_SHA256: + if sha256(path) == expected_sha256: return path os.remove(path) - mirror = os.environ.get("PWSH_MIRROR", PWSH_DEFAULT_MIRROR) + mirror = os.environ.get(mirror_env, default_mirror) if mirror and not mirror.endswith("/"): mirror += "/" - url = f"{mirror}v{PWSH_VERSION}/{PWSH_ARCHIVE}" + url = f"{mirror}{release_tag}/{filename}" part = path + ".part" print(f"downloading {url}") try: with urllib.request.urlopen(url) as response, open(part, "wb") as out: shutil.copyfileobj(response, out) actual = sha256(part) - if actual != PWSH_SHA256: - sys.exit(f"{PWSH_ARCHIVE} sha256 mismatch: expected {PWSH_SHA256}, got {actual}") + if actual != expected_sha256: + sys.exit(f"{filename} sha256 mismatch: expected {expected_sha256}, got {actual}") os.replace(part, path) except BaseException: if os.path.exists(part): @@ -130,6 +157,18 @@ def pwsh_zip(cache): return path +def pwsh_zip(cache): + """Returns the cached PowerShell 7 archive path after verifying SHA-256.""" + return _cached_verified_archive( + cache, + PWSH_ARCHIVE, + PWSH_SHA256, + "PWSH_MIRROR", + PWSH_DEFAULT_MIRROR, + f"v{PWSH_VERSION}", + ) + + def extract_pwsh(archive_path, destination): """Extracts the SHA-256-verified PowerShell archive into destination.""" os.makedirs(destination, exist_ok=True) @@ -140,6 +179,52 @@ def extract_pwsh(archive_path, destination): sys.exit(f"{os.path.basename(archive_path)} is missing non-empty pwsh.exe") +def git_bash_archive(cache): + """Returns the cached PortableGit archive path after verifying SHA-256.""" + return _cached_verified_archive( + cache, + GIT_BASH_ARCHIVE, + GIT_BASH_SHA256, + "GIT_BASH_MIRROR", + GIT_BASH_DEFAULT_MIRROR, + GIT_BASH_TAG, + ) + + +def _unpack_7z(archive_path, destination): + """Unpacks a PortableGit self-extracting 7z archive via host 7z or wintool.""" + seven_zip = next((shutil.which(name) for name in ("7z", "7zz", "7za") if shutil.which(name)), None) + if seven_zip: + run(seven_zip, "x", "-y", f"-o{destination}", archive_path) + return + scratch = tempfile.mkdtemp(prefix="linger-gitbash-") + try: + staged_archive = os.path.join(scratch, os.path.basename(archive_path)) + shutil.copy2(archive_path, staged_archive) + out_dir = os.path.join(scratch, "out") + os.makedirs(out_dir) + wintool(scratch, "7z", "x", "-y", "-oout", os.path.basename(archive_path)) + shutil.copytree(out_dir, destination, dirs_exist_ok=True) + finally: + shutil.rmtree(scratch, ignore_errors=True) + + +def extract_git_bash(archive_path, destination): + """Extracts the SHA-256-verified PortableGit archive, trims GUI/docs, and verifies bash.exe.""" + os.makedirs(destination, exist_ok=True) + _unpack_7z(archive_path, destination) + for relative in GIT_BASH_PRUNE_PATHS: + target = os.path.join(destination, *relative.split("/")) + if os.path.isdir(target): + shutil.rmtree(target) + elif os.path.exists(target): + os.remove(target) + for required in (("bin", "bash.exe"), ("usr", "bin", "bash.exe")): + exe = os.path.join(destination, *required) + if not os.path.isfile(exe) or os.path.getsize(exe) <= 0: + sys.exit(f"{os.path.basename(archive_path)} is missing non-empty {'/'.join(required)}") + + def write_icon(output): """The logo's Windows icon (apps/assets/logo/windows), 16 to 256 px.""" shutil.copy(os.path.join(DESKTOP, "resources", "linger.ico"), output) @@ -178,6 +263,7 @@ def stage_app(version, electron_version, workdir, cache): shutil.copy2(DAEMON, computer) computer_tools.copy(resources, "win32-x64") extract_pwsh(pwsh_zip(cache), os.path.join(resources, "runtime", "pwsh")) + extract_git_bash(git_bash_archive(cache), os.path.join(resources, "runtime", "git-bash")) write_icon(os.path.join(resources, "linger.ico")) os.rename(os.path.join(stage, "electron.exe"), os.path.join(stage, "Linger.exe")) @@ -266,6 +352,7 @@ def make_zip(): computer_tools.check_archive(archive, "Linger/resources/", "win32-x64") verify_teamhub_cli_archive(archive) verify_pwsh_archive(archive) + verify_git_bash_archive(archive) report(archive) # Both read the finalized stage folder and write distinct outputs. diff --git a/apps/desktop/packaging/win_git_bash_test.py b/apps/desktop/packaging/win_git_bash_test.py new file mode 100644 index 0000000000..e12e114f3c --- /dev/null +++ b/apps/desktop/packaging/win_git_bash_test.py @@ -0,0 +1,123 @@ +"""Checks for Windows Desktop PortableGit archive caching, extraction, and zip verification. + + python3 -m unittest discover -s apps/desktop/packaging -p '*_test.py' +""" +import hashlib +import importlib.util +import io +import os +import shutil +import tempfile +import unittest +from unittest import mock +import zipfile + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def load_module(name, relative_path): + spec = importlib.util.spec_from_file_location(name, os.path.join(HERE, *relative_path)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class WindowsGitBashPackagingTest(unittest.TestCase): + def setUp(self): + self.win = load_module("win_package_git_bash", ("win", "package.py")) + self.root = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.root) + + def test_git_bash_archive_reuses_verified_cache_and_rejects_mismatched_download(self): + cache = os.path.join(self.root, "cache") + os.makedirs(cache) + cached = os.path.join(cache, self.win.GIT_BASH_ARCHIVE) + payload = b"valid-portable-git-archive" + payload_sha = hashlib.sha256(payload).hexdigest() + + with mock.patch.object(self.win, "GIT_BASH_SHA256", payload_sha): + with open(cached, "wb") as out: + out.write(payload) + with mock.patch.object(self.win.urllib.request, "urlopen", side_effect=AssertionError("unexpected fetch")): + self.assertEqual(self.win.git_bash_archive(cache), cached) + + with open(cached, "wb") as out: + out.write(b"corrupt-cache") + with mock.patch.object(self.win.urllib.request, "urlopen", return_value=io.BytesIO(payload)) as fetch: + self.assertEqual(self.win.git_bash_archive(cache), cached) + self.assertEqual(fetch.call_count, 1) + with open(cached, "rb") as cached_file: + self.assertEqual(hashlib.sha256(cached_file.read()).hexdigest(), payload_sha) + + os.remove(cached) + with mock.patch.object(self.win.urllib.request, "urlopen", return_value=io.BytesIO(b"bad-download")): + with self.assertRaises(SystemExit) as stopped: + self.win.git_bash_archive(cache) + self.assertIn("sha256 mismatch", str(stopped.exception)) + self.assertFalse(os.path.exists(cached + ".part")) + self.assertFalse(os.path.exists(cached)) + + def test_extract_git_bash_prunes_gui_docs_and_requires_bash_executables(self): + dest = os.path.join(self.root, "stage", "resources", "runtime", "git-bash") + + def fake_unpack(_archive_path, target): + for relative, content in ( + ("bin/bash.exe", b"MZ-bash-launcher"), + ("usr/bin/bash.exe", b"MZ-bash"), + ("usr/bin/grep.exe", b"MZ-grep"), + ("mingw64/share/doc/git-doc/index.html", b"doc"), + ("cmd/git-gui.exe", b"MZ-gui"), + ("git-bash.exe", b"MZ-mintty"), + ("ReleaseNotes.html", b"notes"), + ): + full = os.path.join(target, *relative.split("/")) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "wb") as out: + out.write(content) + + with mock.patch.object(self.win, "_unpack_7z", side_effect=fake_unpack): + self.win.extract_git_bash("PortableGit.7z.exe", dest) + + self.assertTrue(os.path.isfile(os.path.join(dest, "bin", "bash.exe"))) + self.assertTrue(os.path.isfile(os.path.join(dest, "usr", "bin", "bash.exe"))) + self.assertTrue(os.path.isfile(os.path.join(dest, "usr", "bin", "grep.exe"))) + self.assertFalse(os.path.exists(os.path.join(dest, "mingw64", "share", "doc"))) + self.assertFalse(os.path.exists(os.path.join(dest, "cmd", "git-gui.exe"))) + self.assertFalse(os.path.exists(os.path.join(dest, "git-bash.exe"))) + self.assertFalse(os.path.exists(os.path.join(dest, "ReleaseNotes.html"))) + + missing_dest = os.path.join(self.root, "missing-dest") + + def fake_missing(_archive_path, target): + os.makedirs(os.path.join(target, "bin"), exist_ok=True) + with open(os.path.join(target, "bin", "git.exe"), "wb") as out: + out.write(b"MZ-git") + + with mock.patch.object(self.win, "_unpack_7z", side_effect=fake_missing): + with self.assertRaises(SystemExit) as stopped: + self.win.extract_git_bash("PortableGit.7z.exe", missing_dest) + self.assertIn("bin/bash.exe", str(stopped.exception)) + + def test_verify_git_bash_archive_requires_non_empty_bundled_executable(self): + good_zip = os.path.join(self.root, "good.zip") + with zipfile.ZipFile(good_zip, "w") as archive: + archive.writestr(self.win.GIT_BASH_ARCHIVE_ENTRY, b"MZ-bash") + self.win.verify_git_bash_archive(good_zip) + + missing_zip = os.path.join(self.root, "missing.zip") + with zipfile.ZipFile(missing_zip, "w") as archive: + archive.writestr("Linger/resources/runtime/pwsh/pwsh.exe", b"MZ-pwsh") + with self.assertRaises(SystemExit) as stopped: + self.win.verify_git_bash_archive(missing_zip) + self.assertIn("bash.exe", str(stopped.exception)) + + empty_zip = os.path.join(self.root, "empty.zip") + with zipfile.ZipFile(empty_zip, "w") as archive: + archive.writestr(self.win.GIT_BASH_ARCHIVE_ENTRY, b"") + with self.assertRaises(SystemExit) as stopped: + self.win.verify_git_bash_archive(empty_zip) + self.assertIn("bash.exe", str(stopped.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/desktop/scripts/teamhub.sh b/apps/desktop/scripts/teamhub.sh index c3cf289f2f..8559b54037 100644 --- a/apps/desktop/scripts/teamhub.sh +++ b/apps/desktop/scripts/teamhub.sh @@ -1,6 +1,15 @@ #!/bin/sh # Runs the bundled teamhub CLI with the Node built into Linger. dir=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +case "$(uname -s 2>/dev/null || true)" in + MINGW*|MSYS*|CYGWIN*) + # Git Bash resolves extensionless "teamhub" before "teamhub.exe", and + # MSYS_NO_PATHCONV=1 leaves POSIX $dir paths unreadable by native Node/Electron. + if [ -x "$dir/teamhub.exe" ]; then + exec "$dir/teamhub.exe" "$@" + fi + ;; +esac app="" if [ -n "${LINGER_CLI_NODE_PATH:-}" ] && [ -x "$LINGER_CLI_NODE_PATH" ]; then app="$LINGER_CLI_NODE_PATH" diff --git a/apps/node-services/src/agent/executor/activation.ts b/apps/node-services/src/agent/executor/activation.ts index e1c484d1fa..4002705896 100644 --- a/apps/node-services/src/agent/executor/activation.ts +++ b/apps/node-services/src/agent/executor/activation.ts @@ -123,6 +123,8 @@ export interface ContextRuntimeBackendActivation { signal: AbortSignal, options?: { readonly onLoadingLocalModel?: () => void }, ): Promise; + /** Re-resolves the shell dialect before starting a new Run when host shell capabilities may have changed; returns undefined when the host platform is currently unavailable. */ + resolveShellDialect?(): ShellDialect | undefined; setActiveRunContext(context: ToolRunContext | null): void; /** Installs the Agent CLI credential and attaches the per-Run CLI context. */ prepareRunInput?(input: AgentInput, signal: AbortSignal): Promise; @@ -554,6 +556,7 @@ async function activateContextRuntime( activationView, backend: backendActivation, instructionTier, + shellDialect, activationFeatures: acquired.activationFeatures, featureChecks: featurePreparation.checks, viewSession: acquired.viewSession!, @@ -848,6 +851,7 @@ interface ActiveContextRuntimeScope { readonly activationView: ActivationFeatureView; readonly backend: ContextRuntimeBackendActivation; readonly instructionTier: InstructionTier; + readonly shellDialect: ShellDialect | undefined; readonly activationFeatures: ComposedActivationFeatures | null; readonly featureChecks: readonly (( signal: AbortSignal, @@ -921,6 +925,7 @@ function createActivatedContextRuntime( agentResourcesResolver && ordinaryMeta && executionResources, ); const checksInstructionTier = backend.resolveInstructionTier !== undefined; + const checksShellDialect = backend.resolveShellDialect !== undefined; return Object.freeze({ ref: request.ref, provider, @@ -928,12 +933,21 @@ function createActivatedContextRuntime( runtimeSession: scope.runtimeSession, sessionSpec: backend.sessionSpec, ...(executionResources ? { executionResources } : {}), - ...(checksExecutionResources || checksInstructionTier + ...(checksExecutionResources || checksInstructionTier || checksShellDialect ? { async prepareNextRun( nextSignal: AbortSignal, nextOptions?: { readonly onLoadingLocalModel?: () => void }, ): Promise { + if (backend.resolveShellDialect) { + const nextDialect = backend.resolveShellDialect(); + if ( + nextDialect !== undefined && + nextDialect !== (scope.shellDialect ?? "posix") + ) { + return false; + } + } if (backend.resolveInstructionTier) { const nextTier = await backend.resolveInstructionTier( nextSignal, diff --git a/apps/node-services/src/agent/executor/local-backend.ts b/apps/node-services/src/agent/executor/local-backend.ts index 4bcd170977..f479415b79 100644 --- a/apps/node-services/src/agent/executor/local-backend.ts +++ b/apps/node-services/src/agent/executor/local-backend.ts @@ -51,6 +51,7 @@ import { import { isWindowsShellDialect, shellDialectFromPlatform, + type ShellDialect, } from "../prompt/index.js"; type CliRunContextScope = CliRunContext["scope"]; @@ -195,6 +196,7 @@ export interface LocalContextRuntimeGateway > { readonly readReadyLocalAgentRunnerRevision?: RunnerGateway["readReadyLocalAgentRunnerRevision"]; readonly localComputerPlatform?: RunnerGateway["localComputerPlatform"]; + readonly localComputerHasWindowsGitBash?: RunnerGateway["localComputerHasWindowsGitBash"]; readonly contextViewContent?: ContextViewContent; readonly awaitLocalComputerReconnect?: RunnerGateway["awaitLocalComputerReconnect"]; readonly inspectDetachedLocalHistory?: RunnerContextDebugInspector["inspectDetachedLocalHistory"]; @@ -244,6 +246,12 @@ export function createLocalContextRuntimeBackend( request.runtime.placement.computerId, ), request.runtime.placement.runtimeType, + { + windowsGitBash: + options.gateway.localComputerHasWindowsGitBash?.( + request.runtime.placement.computerId, + ) === true, + }, ); return { instructionTier, @@ -679,6 +687,24 @@ async function activateLocalContextRuntime( ...(cliRuntimeConfiguration ? { prepareRunInput: cliRuntimeConfiguration.prepareRunInput } : {}), + resolveShellDialect(): ShellDialect | undefined { + const platform = options.gateway.localComputerPlatform?.( + request.runtime.placement.computerId, + ); + if (!platform) { + return undefined; + } + return shellDialectFromPlatform( + platform, + request.runtime.placement.runtimeType, + { + windowsGitBash: + options.gateway.localComputerHasWindowsGitBash?.( + request.runtime.placement.computerId, + ) === true, + }, + ); + }, async resolveInstructionTier( nextSignal: AbortSignal, tierOptions?: { readonly onLoadingLocalModel?: () => void }, diff --git a/apps/node-services/src/agent/prompt/environment-knowledge.ts b/apps/node-services/src/agent/prompt/environment-knowledge.ts index 8d56049321..8a5fea8f5b 100644 --- a/apps/node-services/src/agent/prompt/environment-knowledge.ts +++ b/apps/node-services/src/agent/prompt/environment-knowledge.ts @@ -2,8 +2,8 @@ import type { InstructionTier } from "./instruction-tier.js"; /** * Shell syntax dialect injected into deployment-static instruction prefixes: - * - "posix": macOS/Linux shells and Windows Claude (Git Bash) - * - "windows-pi": Windows Pi (`powershell` tool, UTF-8 `$OutputEncoding`, `@'...'@ | teamhub --file -`) + * - "posix": macOS/Linux shells, Windows Claude (Git Bash), and Windows Pi when the Computer advertises `windows_git_bash` + * - "windows-pi": Windows Pi PowerShell-only dialect (bash-less hosts and older Daemons without `windows_git_bash`) * - "windows": other Windows PowerShell Runtimes (Codex, Antigravity) without Pi-only tool name or stdin pipe */ export type ShellDialect = "posix" | "windows" | "windows-pi"; @@ -13,17 +13,25 @@ export function isWindowsShellDialect(dialect?: ShellDialect): boolean { return dialect === "windows" || dialect === "windows-pi"; } +/** Optional host shell capabilities advertised by a Local Computer. */ +export interface PlatformShellCapabilities { + readonly windowsGitBash?: boolean; +} + /** Maps a Local Computer `hello.platform` and Runtime type to its prompt shell dialect. */ export function shellDialectFromPlatform( platform?: string, runtimeType?: string, + capabilities?: PlatformShellCapabilities, ): ShellDialect { const normalized = platform?.trim().toLowerCase(); const isWindows = normalized === "win32" || normalized === "windows"; if (!isWindows) return "posix"; const runtime = runtimeType?.trim().toLowerCase(); if (runtime === "claude") return "posix"; - if (runtime === "pi") return "windows-pi"; + if (runtime === "pi") { + return capabilities?.windowsGitBash ? "posix" : "windows-pi"; + } return "windows"; } diff --git a/apps/node-services/src/agent/runner-gateway/context-view-content.ts b/apps/node-services/src/agent/runner-gateway/context-view-content.ts index be8b89b557..b61a223015 100644 --- a/apps/node-services/src/agent/runner-gateway/context-view-content.ts +++ b/apps/node-services/src/agent/runner-gateway/context-view-content.ts @@ -128,7 +128,10 @@ export function createContextViewContent(options: { connectionEpoch: number, ) => boolean; /** Optional deployment-wide static system-prompt prefixes for warm-up. */ - readonly staticPrefixes?: (computerId: string) => StaticPrefixBundle; + readonly staticPrefixes?: ( + computerId: string, + options?: { readonly windowsGitBash?: boolean }, + ) => StaticPrefixBundle; }): ContextViewContent { const publicOrigin = new URL(options.publicOrigin).origin; if (Buffer.byteLength(options.signingKey) < 32) @@ -351,8 +354,22 @@ export function createContextViewContent(options: { if (!principal) return notFound(); if (kind === "static-prefixes" && id === "v1") { if (!options.staticPrefixes) return notFound(); + const rawGitBash = new URL(request.url).searchParams.get( + "windows_git_bash", + ); + const windowsGitBash = + rawGitBash === "1" || rawGitBash === "true" + ? true + : rawGitBash === "0" || rawGitBash === "false" + ? false + : undefined; return new Response( - JSON.stringify(options.staticPrefixes(principal.computerId)), + JSON.stringify( + options.staticPrefixes( + principal.computerId, + windowsGitBash === undefined ? undefined : { windowsGitBash }, + ), + ), { headers: { "content-type": "application/json", diff --git a/apps/node-services/src/agent/runner-gateway/runner-connections.ts b/apps/node-services/src/agent/runner-gateway/runner-connections.ts index ebf5e7efad..8fe24fcea3 100644 --- a/apps/node-services/src/agent/runner-gateway/runner-connections.ts +++ b/apps/node-services/src/agent/runner-gateway/runner-connections.ts @@ -92,6 +92,15 @@ export class RunnerConnections { readonly #connectionEpochs = new Map(); + readonly #lastWindowsGitBash = new Map< + string, + { + readonly platform: string; + readonly daemonVersion: string; + readonly enabled: boolean; + } + >(); + readonly #computerMutationTails = new Map>(); readonly #localComputerReadyListeners = new Set< @@ -430,6 +439,13 @@ export class RunnerConnections { onReady: () => this.owners.operations().completeOperationReconciliation(connection), }); + const priorGitBash = this.#lastWindowsGitBash.get(hello.runner_id); + const windowsGitBash = + priorGitBash !== undefined && + priorGitBash.platform === hello.platform && + priorGitBash.daemonVersion === hello.daemon_version + ? priorGitBash.enabled + : false; const connection: ConnectedRunner = { connectionId: this.context.createId(), runnerId: hello.runner_id, @@ -451,6 +467,7 @@ export class RunnerConnections { phase: "reconciling", operationReconciled: false, runtimeDiagnosticsRevision: 0, + windowsGitBash, localModelsRevision: 0, localSpeechRevision: 0, localTtsRevision: 0, @@ -571,6 +588,7 @@ export class RunnerConnections { "local_models_download_source", "local_models_forward_compat", "local_speech_forward_compat", + "windows_git_bash", ], } : {}), @@ -686,6 +704,14 @@ export class RunnerConnections { runtime_diagnostics: envelope.runtime_diagnostics, }); connection.runtimeDiagnosticsRevision = envelope.revision; + if (envelope.windows_git_bash !== undefined) { + connection.windowsGitBash = envelope.windows_git_bash; + this.#lastWindowsGitBash.set(connection.runnerId, { + platform: connection.hello.platform, + daemonVersion: connection.hello.daemon_version, + enabled: envelope.windows_git_bash, + }); + } connection.hello.runtime_diagnostics = envelope.runtime_diagnostics; const previousRuntimes = connection.hello.runtimes; connection.hello.runtimes = compatibleRuntimeTypes( @@ -1288,6 +1314,10 @@ export class RunnerConnections { return this.#connections.get(computerId)?.hello.platform; } + localComputerHasWindowsGitBash(computerId: string): boolean { + return this.#connections.get(computerId)?.windowsGitBash === true; + } + hasConnection(computerId: string): boolean { return this.#connections.has(computerId); } diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts index d37e76748d..698fe13d9f 100644 --- a/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts +++ b/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts @@ -277,6 +277,8 @@ export interface ConnectedRunner { phase: "reconciling" | "ready"; operationReconciled: boolean; runtimeDiagnosticsRevision: number; + /** Whether the Windows Computer reported a usable non-WSL Git Bash runtime post-welcome. */ + windowsGitBash: boolean; /** * Registration snapshots sent on this connection whose receipt has not * arrived. A diagnostics change can send a new snapshot before the Daemon diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts index 0ba312b4b2..4931bb91ef 100644 --- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts +++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts @@ -254,12 +254,17 @@ export class RunnerGateway ...options.contextContent, isCurrentConnection: (computerId, connectionEpoch) => this.#connections.isCurrentConnection(computerId, connectionEpoch), - staticPrefixes: (computerId) => + staticPrefixes: (computerId, prefixOptions) => renderStaticPrefixBundle({ ...context.deploymentFeatures, shellDialect: shellDialectFromPlatform( this.#connections.localComputerPlatform(computerId), "pi", + { + windowsGitBash: + prefixOptions?.windowsGitBash ?? + this.#connections.localComputerHasWindowsGitBash(computerId), + }, ), }), }); @@ -486,6 +491,10 @@ export class RunnerGateway return this.#connections.localComputerPlatform(computerId); } + localComputerHasWindowsGitBash(computerId: string): boolean { + return this.#connections.localComputerHasWindowsGitBash(computerId); + } + /** The models a connected Computer reports for a Runtime; undefined while * it is offline. */ runtimeModels( diff --git a/apps/node-services/tests/agent/agent-features/context-instructions.test.ts b/apps/node-services/tests/agent/agent-features/context-instructions.test.ts index 29af4a7d93..57dcfe4222 100644 --- a/apps/node-services/tests/agent/agent-features/context-instructions.test.ts +++ b/apps/node-services/tests/agent/agent-features/context-instructions.test.ts @@ -659,6 +659,15 @@ describe("Windows vs POSIX conditional prompt rendering", () => { expect(shellDialectFromPlatform("windows")).toBe("windows"); expect(shellDialectFromPlatform("win32", "pi")).toBe("windows-pi"); expect(shellDialectFromPlatform("windows", "pi")).toBe("windows-pi"); + expect( + shellDialectFromPlatform("win32", "pi", { windowsGitBash: false }), + ).toBe("windows-pi"); + expect( + shellDialectFromPlatform("win32", "pi", { windowsGitBash: true }), + ).toBe("posix"); + expect( + shellDialectFromPlatform("windows", "pi", { windowsGitBash: true }), + ).toBe("posix"); expect(shellDialectFromPlatform("win32", "codex")).toBe("windows"); expect(shellDialectFromPlatform("windows", "codex")).toBe("windows"); expect(shellDialectFromPlatform("win32", "antigravity")).toBe("windows"); diff --git a/apps/node-services/tests/agent/executor/activation.test.ts b/apps/node-services/tests/agent/executor/activation.test.ts index 22409df57a..d1be7fdcea 100644 --- a/apps/node-services/tests/agent/executor/activation.test.ts +++ b/apps/node-services/tests/agent/executor/activation.test.ts @@ -1136,6 +1136,96 @@ describe("Context Runtime Activator", () => { }, ); + it("recycles an activated Context on prepareNextRun when shellDialect flips and preserves it while offline", async () => { + let currentDialect: "posix" | "windows" | "windows-pi" | undefined = + "windows-pi"; + const provider = fakeProvider([]); + const harness = wired({ + shellDialect: "windows-pi", + provider, + activate: async () => ({ + ...fakeBackendActivation(provider), + resolveShellDialect: () => currentDialect, + }), + }); + const active = await harness.activate({ + renderDeveloperInstructions: (facts) => + `dialect:${facts.shellDialect ?? "posix"}`, + }); + try { + expect( + await active.prepareNextRun?.(new AbortController().signal), + ).toBe(true); + // An offline Computer returns undefined and must not tear down the active Context. + currentDialect = undefined; + expect( + await active.prepareNextRun?.(new AbortController().signal), + ).toBe(true); + currentDialect = "posix"; + expect( + await active.prepareNextRun?.(new AbortController().signal), + ).toBe(false); + } finally { + await active.deactivate(); + } + }); + + it("keeps a Windows Codex Context alive while offline and recycles POSIX Contexts when Windows Pi drops Git Bash", async () => { + let codexDialect: "posix" | "windows" | "windows-pi" | undefined = + "windows"; + const codexProvider = fakeProvider([]); + const codexHarness = wired({ + shellDialect: "windows", + provider: codexProvider, + activate: async () => ({ + ...fakeBackendActivation(codexProvider), + resolveShellDialect: () => codexDialect, + }), + }); + const codexActive = await codexHarness.activate({ + renderDeveloperInstructions: (facts) => + `dialect:${facts.shellDialect ?? "posix"}`, + }); + try { + codexDialect = undefined; + expect( + await codexActive.prepareNextRun?.(new AbortController().signal), + ).toBe(true); + } finally { + await codexActive.deactivate(); + } + + let posixDialect: "posix" | "windows" | "windows-pi" | undefined = + "posix"; + const posixProvider = fakeProvider([]); + const posixHarness = wired({ + provider: posixProvider, + activate: async () => ({ + ...fakeBackendActivation(posixProvider), + resolveShellDialect: () => posixDialect, + }), + }); + const posixActive = await posixHarness.activate({ + renderDeveloperInstructions: (facts) => + `dialect:${facts.shellDialect ?? "posix"}`, + }); + try { + expect( + await posixActive.prepareNextRun?.(new AbortController().signal), + ).toBe(true); + posixDialect = undefined; + expect( + await posixActive.prepareNextRun?.(new AbortController().signal), + ).toBe(true); + posixDialect = "windows-pi"; + expect( + await posixActive.prepareNextRun?.(new AbortController().signal), + ).toBe(false); + } finally { + await posixActive.deactivate(); + } + }); + it("keeps Agent Memory out of the instructions and maps its files", async () => { const prepare = vi.fn(async () => ({ summary: "memory summary", diff --git a/apps/node-services/tests/agent/executor/local-backend.test.ts b/apps/node-services/tests/agent/executor/local-backend.test.ts index cea3cfe2bb..f0f2cffdcd 100644 --- a/apps/node-services/tests/agent/executor/local-backend.test.ts +++ b/apps/node-services/tests/agent/executor/local-backend.test.ts @@ -123,6 +123,7 @@ function backendFixture( readRevision: () => number = () => 7, credential?: (input: { runnerRevision: number }) => Promise, platform?: string, + windowsGitBash?: boolean, ) { const targets: RunnerOperationTarget[] = []; const relay = { register: vi.fn(() => []), rebind: vi.fn(), revoke: vi.fn() }; @@ -135,6 +136,9 @@ function backendFixture( ...(platform === undefined ? {} : { localComputerPlatform: () => platform }), + ...(windowsGitBash === undefined + ? {} + : { localComputerHasWindowsGitBash: () => windowsGitBash }), ...(credential ? { ensureAgentCliCredential: credential } : {}), ...(inspectLocalContext ? { inspectLocalContext } : {}), async startOperation(target) { @@ -318,22 +322,45 @@ describe("Local Context Runtime backend", () => { ); it.each([ - ["win32", "pi", { instructionTier: "full", shellDialect: "windows-pi" }], - ["win32", "codex", { instructionTier: "full", shellDialect: "windows" }], + ["win32", "pi", true, { instructionTier: "full" }], + ["windows", "pi", true, { instructionTier: "full" }], + [ + "win32", + "pi", + false, + { instructionTier: "full", shellDialect: "windows-pi" }, + ], + [ + "windows", + "pi", + undefined, + { instructionTier: "full", shellDialect: "windows-pi" }, + ], + [ + "win32", + "codex", + true, + { instructionTier: "full", shellDialect: "windows" }, + ], [ "win32", "antigravity", + false, + { instructionTier: "full", shellDialect: "windows" }, + ], + [ + "windows", + "codex", + undefined, { instructionTier: "full", shellDialect: "windows" }, ], - ["windows", "pi", { instructionTier: "full", shellDialect: "windows-pi" }], - ["windows", "codex", { instructionTier: "full", shellDialect: "windows" }], - ["win32", "claude", { instructionTier: "full" }], - ["windows", "claude", { instructionTier: "full" }], - ["darwin", "pi", { instructionTier: "full" }], - ["linux", "codex", { instructionTier: "full" }], + ["win32", "claude", false, { instructionTier: "full" }], + ["windows", "claude", undefined, { instructionTier: "full" }], + ["darwin", "pi", false, { instructionTier: "full" }], + ["linux", "codex", false, { instructionTier: "full" }], ] as const)( - "returns %s (%s) platform shell dialect from preflight", - async (platform, runtimeType, expected) => { + "returns %s (%s, windowsGitBash=%s) platform shell dialect from preflight", + async (platform, runtimeType, windowsGitBash, expected) => { const base = requestFixture(); const { backend } = backendFixture( viewContent(FIRST).content, @@ -343,6 +370,7 @@ describe("Local Context Runtime backend", () => { undefined, undefined, platform, + windowsGitBash, ); expect( await backend.preflight?.({ @@ -360,6 +388,76 @@ describe("Local Context Runtime backend", () => { }, ); + it("resolveShellDialect returns undefined while offline and tracks live Windows Git Bash transitions", async () => { + let platform: string | undefined = "win32"; + let windowsGitBash = false; + const relay = { + register: vi.fn(() => []), + rebind: vi.fn(), + revoke: vi.fn(), + }; + const backend = createLocalContextRuntimeBackend({ + gateway: { + requireLocalPlacement: vi.fn(() => ({ + id: "local/qwen", + label: "Qwen", + })), + ensureReadyLocalAgentRunner: async () => 7, + readReadyLocalAgentRunnerRevision: () => 7, + localComputerPlatform: () => platform, + localComputerHasWindowsGitBash: () => windowsGitBash, + async startOperation() { + return completedOperation({ + type: "run", + final_response: "done", + session: { threadId: "thread-1" }, + }); + }, + }, + contextViewContent: viewContent(FIRST, SECOND).content, + mcpRelay: relay, + }); + + const base = requestFixture(); + const piActivation = await backend.activate({ + ...base, + runtime: { + ...base.runtime, + placement: { ...base.runtime.placement, runtimeType: "pi" }, + }, + }); + try { + expect(piActivation.resolveShellDialect?.()).toBe("windows-pi"); + windowsGitBash = true; + expect(piActivation.resolveShellDialect?.()).toBe("posix"); + platform = undefined; + expect(piActivation.resolveShellDialect?.()).toBeUndefined(); + platform = "win32"; + windowsGitBash = false; + expect(piActivation.resolveShellDialect?.()).toBe("windows-pi"); + platform = "darwin"; + expect(piActivation.resolveShellDialect?.()).toBe("posix"); + } finally { + await piActivation.deactivate(); + } + + platform = "win32"; + const codexActivation = await backend.activate({ + ...base, + runtime: { + ...base.runtime, + placement: { ...base.runtime.placement, runtimeType: "codex" }, + }, + }); + try { + expect(codexActivation.resolveShellDialect?.()).toBe("windows"); + platform = undefined; + expect(codexActivation.resolveShellDialect?.()).toBeUndefined(); + } finally { + await codexActivation.deactivate(); + } + }); + it("wraps compact and minimal instructions in the compact Codex rules", async () => { const baseInstructions = async (tier: "full" | "compact" | "minimal") => { const { backend, targets } = backendFixture(viewContent(FIRST).content); diff --git a/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.ts index a7cc726030..24415f96e1 100644 --- a/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.ts +++ b/apps/node-services/tests/agent/runner-gateway/runner-connections-public.test.ts @@ -1208,7 +1208,7 @@ describe("RunnerGateway local Computer reconnect wait", () => { }, }); - const fetchPrefixes = async (epoch: number) => { + const fetchPrefixes = async (epoch: number, query = "") => { const content = gateway.contextViewContent; expect(content).toBeDefined(); const baseUrl = content!.contentUrl("runner-local", epoch); @@ -1217,7 +1217,7 @@ describe("RunnerGateway local Computer reconnect wait", () => { token, "static-prefixes", "v1", - new Request(`${baseUrl}/static-prefixes/v1`), + new Request(`${baseUrl}/static-prefixes/v1${query}`), ); expect(response.status).toBe(200); return (await response.json()) as { @@ -1258,22 +1258,110 @@ describe("RunnerGateway local Computer reconnect wait", () => { ...hello(), platform: "win32", }); - const windows = await fetchPrefixes(3); - expect(windows.prefixes).toEqual( + const windowsFallback = await fetchPrefixes(3); + expect(windowsFallback.prefixes).toEqual( renderStaticPrefixBundle({ connectedApps: true, permissionReview: false, shellDialect: "windows-pi", }).prefixes, ); - expect(windows.prefixes.meta.full).toContain("$env:NODE_PATH"); - expect(windows.prefixes.meta.full).toContain("'Doing well, you?'"); - expect(windows.prefixes.meta.compact).toContain("'ARR is $6.4M'"); - expect(windows.prefixes.meta.minimal).toContain("'ARR is $6.4M'"); - expect(windows.prefixes.meta.full).not.toContain("<<'EOF'"); - expect(windows.prefixes.meta.compact).not.toContain("<<'EOF'"); - expect(windows.prefixes.meta.minimal).not.toContain("<<'EOF'"); - expect(windows.prefixes.alter_ego.minimal).not.toContain("find -L"); + expect(windowsFallback.prefixes.meta.full).toContain("powershell"); + expect(windowsFallback.prefixes.meta.full).not.toContain("<<'EOF'"); winConn.disconnect(); + + const winBashPeer = new RecordingPeer(); + const winBashConn = await acceptReadyConnection(gateway, winBashPeer, { + ...hello(), + platform: "win32", + }); + const welcome = winBashPeer.sent.find( + (frame) => frame.type === "runner.welcome", + ); + expect(welcome?.service_features).toContain("windows_git_bash"); + const beforeBashReport = await fetchPrefixes(4); + expect(beforeBashReport.prefixes).toEqual( + renderStaticPrefixBundle({ + connectedApps: true, + permissionReview: false, + shellDialect: "windows-pi", + }).prefixes, + ); + // Warm-up requests carrying ?windows_git_bash=1 never race WebSocket diagnostics. + const explicitQueryDualShell = await fetchPrefixes( + 4, + "?windows_git_bash=1", + ); + expect(explicitQueryDualShell.prefixes).toEqual( + renderStaticPrefixBundle({ + connectedApps: true, + permissionReview: false, + shellDialect: "posix", + }).prefixes, + ); + await winBashConn.receive({ + type: "runner.runtime_diagnostics", + protocol_version: "2", + runner_id: "runner-local", + sent_at: "2026-07-29T00:00:15.000Z", + revision: 1, + runtime_diagnostics: runtimeDiagnostics({ ready: ["pi"] }), + windows_git_bash: true, + }); + const windowsDualShell = await fetchPrefixes(4); + expect(windowsDualShell.prefixes).toEqual( + renderStaticPrefixBundle({ + connectedApps: true, + permissionReview: false, + shellDialect: "posix", + }).prefixes, + ); + expect(windowsDualShell.prefixes.meta.full).toContain("<<'EOF'"); + expect(windowsDualShell.prefixes.alter_ego.minimal).toContain("find -L"); + winBashConn.disconnect(); + + // Reconnecting the same Windows Computer preserves windowsGitBash immediately. + const reconnectedWinBash = await acceptReadyConnection( + gateway, + new RecordingPeer(), + { + ...hello(), + platform: "win32", + }, + ); + expect(gateway.localComputerHasWindowsGitBash("runner-local")).toBe(true); + const reconnectedPrefixes = await fetchPrefixes(5); + expect(reconnectedPrefixes.prefixes).toEqual(windowsDualShell.prefixes); + // Warm-up requests carrying ?windows_git_bash=0 override cached true immediately. + const explicitQueryFallback = await fetchPrefixes(5, "?windows_git_bash=0"); + expect(explicitQueryFallback.prefixes).toEqual(beforeBashReport.prefixes); + // Post-welcome windows_git_bash=false resets both the live connection and cached value. + await reconnectedWinBash.receive({ + type: "runner.runtime_diagnostics", + protocol_version: "2", + runner_id: "runner-local", + sent_at: "2026-07-29T00:00:25.000Z", + revision: 1, + runtime_diagnostics: runtimeDiagnostics({ ready: ["pi"] }), + windows_git_bash: false, + }); + expect(gateway.localComputerHasWindowsGitBash("runner-local")).toBe(false); + const resetPrefixes = await fetchPrefixes(5); + expect(resetPrefixes.prefixes).toEqual(beforeBashReport.prefixes); + reconnectedWinBash.disconnect(); + + // Subsequent same-version reconnect retains the reset false value. + const afterResetReconnect = await acceptReadyConnection( + gateway, + new RecordingPeer(), + { + ...hello(), + platform: "win32", + }, + ); + expect(gateway.localComputerHasWindowsGitBash("runner-local")).toBe(false); + const afterResetPrefixes = await fetchPrefixes(6); + expect(afterResetPrefixes.prefixes).toEqual(beforeBashReport.prefixes); + afterResetReconnect.disconnect(); }); }); diff --git a/contracts/README.md b/contracts/README.md index 51838e9b77..59284b3031 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -123,7 +123,8 @@ Progress and outcomes travel back only as snapshots: `model_gateway_unavailable`, `byok_authentication_failed`, `dynamic_reasoning_efforts`, `antigravity_usage_provider`, `pi_usage_provider`, - `model_invoke_usage_details`, and `session_compact_usage` to every Computer + `model_invoke_usage_details`, `session_compact_usage`, and + `windows_git_bash` to every Computer that receives the field: a Daemon ignores a feature it does not know, one that knows `local_model_unavailable` reports a Pi Run whose local model it could not load with that Run failure code instead of `model_unavailable`, @@ -141,8 +142,15 @@ Progress and outcomes travel back only as snapshots: Service that does not advertise it), one that knows `model_invoke_usage_details` preserves optional `input_includes_cached`, `cache_write_input_tokens`, and `reasoning_tokens` on `ModelInvoked.usage`, - and one that knows `session_compact_usage` sends optional `model`, `usage`, - and `usage_entries` on `SessionCompacted`. During rolling deploys, roll out + one that knows `session_compact_usage` sends optional `model`, `usage`, + and `usage_entries` on `SessionCompacted`, and one that knows + `windows_git_bash` reports `windows_git_bash` (`true` or `false` on Windows) + on post-welcome `runner.runtime_diagnostics` frames (never in + `runner.hello.capabilities`) and `?windows_git_bash=1`/`0` on + `/static-prefixes/v1`, enabling dual `bash` + `powershell` tools and guides + on Windows Pi when a usable non-WSL Git Bash runtime is present and falling + back to PowerShell-only otherwise or when connected to an older Agent + Service that does not advertise the feature. During rolling deploys, roll out TeamHub accepting a new provider before the Agent Service advertises its usage provider feature, so older TeamHub instances do not skip those entries. diff --git a/contracts/generated/go/runnergateway/wire.gen.go b/contracts/generated/go/runnergateway/wire.gen.go index 1ab3ffa5e2..d3e2275fbf 100644 --- a/contracts/generated/go/runnergateway/wire.gen.go +++ b/contracts/generated/go/runnergateway/wire.gen.go @@ -2741,6 +2741,7 @@ type RunnerRuntimeDiagnostics struct { SentAt string `json:"sent_at"` Revision uint64 `json:"revision"` RuntimeDiagnostics []RuntimeDiagnostic `json:"runtime_diagnostics"` + WindowsGitBash *bool `json:"windows_git_bash,omitempty"` } // FixedFields lists the keys whose value the schema fixes for a RunnerRuntimeDiagnostics. diff --git a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts index 5e00659146..a3456e2fb8 100644 --- a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts +++ b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts @@ -301,6 +301,7 @@ export const runnerGatewayEnvelopeSchema = { "local_models_download_source", "local_models_forward_compat", "local_speech_forward_compat", + "windows_git_bash", ], }, ReasoningEffort: { @@ -5653,6 +5654,11 @@ export const runnerGatewayEnvelopeSchema = { runtime_diagnostics: { $ref: "#/$defs/RuntimeDiagnostics", }, + windows_git_bash: { + description: + "Whether this Windows Computer has a usable non-WSL Git Bash runtime for dual-shell Pi runs. Sent only when runner.welcome service_features advertises windows_git_bash.", + type: "boolean", + }, }, }, RunnerReconciled: { diff --git a/contracts/generated/typescript/src/generated/runner-gateway/types.ts b/contracts/generated/typescript/src/generated/runner-gateway/types.ts index b9605eb543..046ba422b1 100644 --- a/contracts/generated/typescript/src/generated/runner-gateway/types.ts +++ b/contracts/generated/typescript/src/generated/runner-gateway/types.ts @@ -69,7 +69,8 @@ export type ServiceFeature = | "local_models_best_for_tier" | "local_models_download_source" | "local_models_forward_compat" - | "local_speech_forward_compat"; + | "local_speech_forward_compat" + | "windows_git_bash"; export type JsonValue = | null | boolean @@ -1788,6 +1789,10 @@ export interface RunnerRuntimeDiagnostics { sent_at: Timestamp; revision: PositiveInteger; runtime_diagnostics: RuntimeDiagnostics; + /** + * Whether this Windows Computer has a usable non-WSL Git Bash runtime for dual-shell Pi runs. Sent only when runner.welcome service_features advertises windows_git_bash. + */ + windows_git_bash?: boolean; } /** * The Computer's model library. Sent after a runner.welcome whose service_features names local_models, after every library change, and at most every 2 seconds while a download or load runs. revision grows within one connection. diff --git a/contracts/runner-gateway/envelope.schema.json b/contracts/runner-gateway/envelope.schema.json index c611f1cee5..e61c95c787 100644 --- a/contracts/runner-gateway/envelope.schema.json +++ b/contracts/runner-gateway/envelope.schema.json @@ -297,7 +297,8 @@ "local_models_best_for_tier", "local_models_download_source", "local_models_forward_compat", - "local_speech_forward_compat" + "local_speech_forward_compat", + "windows_git_bash" ] }, "ReasoningEffort": { @@ -5525,6 +5526,10 @@ }, "runtime_diagnostics": { "$ref": "#/$defs/RuntimeDiagnostics" + }, + "windows_git_bash": { + "description": "Whether this Windows Computer has a usable non-WSL Git Bash runtime for dual-shell Pi runs. Sent only when runner.welcome service_features advertises windows_git_bash.", + "type": "boolean" } } }, diff --git a/docs/desktop-release.md b/docs/desktop-release.md index 1c99b238d3..9ef211e900 100644 --- a/docs/desktop-release.md +++ b/docs/desktop-release.md @@ -526,8 +526,13 @@ daemon from `resources/computer/`, so every package carries them as `packaging/win/package.py` also downloads, SHA-256-verifies, and unpacks portable PowerShell 7.6.10 LTS (`PowerShell-7.6.10-win-x64.zip`, cached in `~/.cache/linger-desktop`, optional `PWSH_MIRROR` override) into -`resources/runtime/pwsh/pwsh.exe`, which the Daemon appends to the end of -Windows Runtime `PATH` as the default `pwsh` fallback. +`resources/runtime/pwsh/pwsh.exe`, and PortableGit 2.56.0.4 +(`PortableGit-2.56.0.4-64-bit.7z.exe`, cached in `~/.cache/linger-desktop`, +optional `GIT_BASH_MIRROR` override) into +`resources/runtime/git-bash/bin/bash.exe`. The Daemon appends both bundled +runtimes to Windows Runtime `PATH` as fallbacks and passes the resolved Git +Bash executable explicitly to Pi's Windows `bash` tool so WSL's +`System32\bash.exe` cannot intercept it. `build.mjs` stages them for each daemon target into `dist/computer-tools//` (`scripts/stage-computer-tools.mjs`) with diff --git a/scripts/ci/desktop-smoke-helpers.mjs b/scripts/ci/desktop-smoke-helpers.mjs index bd20664118..31eb42a3fd 100644 --- a/scripts/ci/desktop-smoke-helpers.mjs +++ b/scripts/ci/desktop-smoke-helpers.mjs @@ -148,7 +148,7 @@ export function piToolsForPlatform(platform = process.platform) { // Matches piBaseTools / piWindowsBaseTools in // apps/computer/local-daemon/internal/provider/native/pi_runtime.go. if (platform === "win32") { - return "read,powershell,edit,write,grep,find,ls,mcp__*"; + return "read,bash,powershell,edit,write,grep,find,ls,mcp__*"; } return "read,bash,edit,write,grep,find,ls,mcp__*"; } @@ -530,6 +530,7 @@ export async function runPackagedInstallerPiSmoke({ home, bundledPi, extension, + gitBashExecutable, platform = process.platform, prepTimeoutMs = 780_000, }) { @@ -700,6 +701,9 @@ export async function runPackagedInstallerPiSmoke({ ...process.env, PI_CODING_AGENT_DIR: join(home, "pi-profile"), LINGER_PI_MANAGED_MCP_CONFIG: config, + ...(gitBashExecutable + ? { LINGER_PI_GIT_BASH_PATH: gitBashExecutable } + : {}), }; delete env.ELECTRON_RUN_AS_NODE; delete env.NODE_PATH; diff --git a/scripts/ci/desktop-smoke.test.ts b/scripts/ci/desktop-smoke.test.ts index ec6fe1ce23..60bf91251c 100644 --- a/scripts/ci/desktop-smoke.test.ts +++ b/scripts/ci/desktop-smoke.test.ts @@ -680,7 +680,7 @@ describe("platform-aware Pi helpers", () => { it("returns platform-appropriate Pi tools list", () => { expect(piToolsForPlatform("win32")).toBe( - "read,powershell,edit,write,grep,find,ls,mcp__*", + "read,bash,powershell,edit,write,grep,find,ls,mcp__*", ); expect(piToolsForPlatform("darwin")).toBe( "read,bash,edit,write,grep,find,ls,mcp__*", diff --git a/scripts/ci/windows-pi-smoke.mjs b/scripts/ci/windows-pi-smoke.mjs index be4a576aa6..2cbcfa1433 100644 --- a/scripts/ci/windows-pi-smoke.mjs +++ b/scripts/ci/windows-pi-smoke.mjs @@ -6,9 +6,9 @@ import { runPackagedInstallerPiSmoke, } from "./desktop-smoke-helpers.mjs"; -function runPowerShellCommand(executable, args, timeoutMs) { +function runSmokeCommand(label, executable, args, timeoutMs, extraEnv = {}) { return new Promise((resolve, reject) => { - const env = { ...process.env }; + const env = { ...process.env, ...extraEnv }; delete env.ELECTRON_RUN_AS_NODE; delete env.NODE_PATH; delete env.NODE_OPTIONS; @@ -24,7 +24,7 @@ function runPowerShellCommand(executable, args, timeoutMs) { if (finished) return; finished = true; child.kill(); - reject(new Error(`PowerShell smoke: timed out after ${timeoutMs}ms`)); + reject(new Error(`${label}: timed out after ${timeoutMs}ms`)); }, timeoutMs); child.stdout?.setEncoding("utf8").on("data", (chunk) => { stdout += chunk; @@ -36,11 +36,7 @@ function runPowerShellCommand(executable, args, timeoutMs) { if (finished) return; finished = true; clearTimeout(timer); - reject( - new Error( - `PowerShell smoke: process error: ${error.code ?? error.name}`, - ), - ); + reject(new Error(`${label}: process error: ${error.code ?? error.name}`)); }); child.on("close", (code) => { if (finished) return; @@ -50,7 +46,7 @@ function runPowerShellCommand(executable, args, timeoutMs) { const diagnostic = stderr.trim().slice(-1500); reject( new Error( - `PowerShell smoke: exited with ${code}${diagnostic ? `\n${diagnostic}` : ""}`, + `${label}: exited with ${code}${diagnostic ? `\n${diagnostic}` : ""}`, ), ); return; @@ -64,7 +60,8 @@ export async function probeBundledPowerShell( executable, { nodeExecutable, expectedVersion = "7.6.10", timeoutMs = 15_000 } = {}, ) { - const versionOutput = await runPowerShellCommand( + const versionOutput = await runSmokeCommand( + "PowerShell smoke", executable, [ "-NoProfile", @@ -84,7 +81,8 @@ export async function probeBundledPowerShell( const quotedNode = nodeExecutable.replaceAll("'", "''"); const expectedArg = '[{"question":"a b"}]'; const command = `& '${quotedNode}' -e 'process.stdout.write(process.argv[1])' '${expectedArg}'`; - const echoed = await runPowerShellCommand( + const echoed = await runSmokeCommand( + "PowerShell smoke", executable, ["-NoProfile", "-NonInteractive", "-Command", command], timeoutMs, @@ -97,6 +95,37 @@ export async function probeBundledPowerShell( } } +export async function probeBundledGitBash( + executable, + { timeoutMs = 15_000 } = {}, +) { + const versionOutput = await runSmokeCommand( + "Git Bash smoke", + executable, + ["--version"], + timeoutMs, + { MSYS_NO_PATHCONV: "1", MSYS2_ARG_CONV_EXCL: "*" }, + ); + if (!/gnu bash/i.test(versionOutput)) { + throw new Error( + `Git Bash smoke: expected GNU bash banner, got ${versionOutput.trim() || "(empty)"}`, + ); + } + const expectedArg = '[{"question":"a b"}]'; + const echoed = await runSmokeCommand( + "Git Bash smoke", + executable, + ["-c", 'printf "%s" "$1"', "_", expectedArg], + timeoutMs, + { MSYS_NO_PATHCONV: "1", MSYS2_ARG_CONV_EXCL: "*" }, + ); + if (echoed !== expectedArg) { + throw new Error( + `Git Bash smoke: argument mismatch: expected ${expectedArg}, got ${echoed}`, + ); + } +} + async function main() { const home = process.env.LINGER_HOME; if ( @@ -111,6 +140,13 @@ async function main() { const resources = join(dirname(process.execPath), "resources"); const node = join(resources, "runtime", "bin", "node.exe"); const bundledPwsh = join(resources, "runtime", "pwsh", "pwsh.exe"); + const bundledGitBash = join( + resources, + "runtime", + "git-bash", + "bin", + "bash.exe", + ); const installer = join(resources, "app", "dist", "installer", "installer.js"); const bundledPi = join(resources, "cli", "computer-tools", "bin", "pi.exe"); const extension = join( @@ -122,6 +158,7 @@ async function main() { ); await access(node); await access(bundledPwsh); + await access(bundledGitBash); await access(installer); await access(bundledPi); await access(extension); @@ -135,12 +172,22 @@ async function main() { elapsed_ms: Math.round(performance.now() - pwshStart), }), ); + const gitBashStart = performance.now(); + await probeBundledGitBash(bundledGitBash); + console.log( + JSON.stringify({ + phase: "bundled_git_bash", + result: "passed", + elapsed_ms: Math.round(performance.now() - gitBashStart), + }), + ); await runPackagedInstallerPiSmoke({ nodeExecutable: node, installerEntry: installer, home, bundledPi, extension, + gitBashExecutable: bundledGitBash, platform: "win32", }); } diff --git a/scripts/ci/windows-pi-smoke.test.ts b/scripts/ci/windows-pi-smoke.test.ts index e7761b44f0..a5244b042f 100644 --- a/scripts/ci/windows-pi-smoke.test.ts +++ b/scripts/ci/windows-pi-smoke.test.ts @@ -3,7 +3,10 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; import { assertNoFreshHarnessPi, probePi } from "./desktop-smoke-helpers.mjs"; -import { probeBundledPowerShell } from "./windows-pi-smoke.mjs"; +import { + probeBundledGitBash, + probeBundledPowerShell, +} from "./windows-pi-smoke.mjs"; const tempDirs: string[] = []; @@ -153,3 +156,45 @@ it("rejects unexpected bundled PowerShell version or stripped JSON quotes", asyn }), ).rejects.toThrow("native JSON argument mismatch"); }); + +it("verifies bundled Git Bash banner and verbatim JSON argument preservation", async () => { + const dir = await privateCwd(); + const bash = await writeExecutableNodeShim( + dir, + ` + const args = process.argv.slice(2); + if (args[0] === "--version") { + process.stdout.write("GNU bash, version 5.2.37(1)-release (x86_64-pc-msys)\\n"); + } else { + process.stdout.write(args[args.length - 1] ?? ""); + } + `, + ); + await expect(probeBundledGitBash(bash)).resolves.toBeUndefined(); +}); + +it("rejects non-GNU Git Bash banners or mangled arguments", async () => { + const dir = await privateCwd(); + const wrongBanner = await writeExecutableNodeShim( + dir, + 'process.stdout.write("Windows Subsystem for Linux\\n");', + ); + await expect(probeBundledGitBash(wrongBanner)).rejects.toThrow( + "expected GNU bash banner", + ); + + const mangled = await writeExecutableNodeShim( + dir, + ` + const args = process.argv.slice(2); + if (args[0] === "--version") { + process.stdout.write("GNU bash, version 5.2.37(1)-release\\n"); + } else { + process.stdout.write("[{question:a"); + } + `, + ); + await expect(probeBundledGitBash(mangled)).rejects.toThrow( + "argument mismatch", + ); +}); diff --git a/scripts/env-inventory.json b/scripts/env-inventory.json index ec878800a0..fb3000365a 100644 --- a/scripts/env-inventory.json +++ b/scripts/env-inventory.json @@ -66,7 +66,7 @@ }, "platform": { "owner": "out-of-env", - "description": "Variables injected by the runtime environment: image build info, the teamhub-cli runtime, Computer on user machines (including Antigravity's GEMINI_API_KEY and GOOGLE_API_KEY), deployment platforms, and the Room Document E2E harness. On Linux the Computer reads the desktop session's DISPLAY and WAYLAND_DISPLAY before it opens a browser window. The Desktop tray probe uses DBUS_SESSION_BUS_ADDRESS or the user bus socket in XDG_RUNTIME_DIR. The Desktop WSL launcher and Windows Local Computer Daemon use WSLENV and WSL_DISTRO_NAME to forward TeamHub CLI configuration and resolve local attachment paths across the Windows/WSL boundary. Not part of .env.", + "description": "Variables injected by the runtime environment: image build info, the teamhub-cli runtime, Computer on user machines (including Antigravity's GEMINI_API_KEY and GOOGLE_API_KEY), deployment platforms, and the Room Document E2E harness. On Linux the Computer reads the desktop session's DISPLAY and WAYLAND_DISPLAY before it opens a browser window. The Desktop tray probe uses DBUS_SESSION_BUS_ADDRESS or the user bus socket in XDG_RUNTIME_DIR. The Desktop WSL launcher and Windows Local Computer Daemon use WSLENV and WSL_DISTRO_NAME to forward TeamHub CLI configuration and resolve local attachment paths across the Windows/WSL boundary, and set MSYS_NO_PATHCONV and MSYS2_ARG_CONV_EXCL to prevent Git Bash MSYS2 path mangling. Not part of .env.", "names": [ "APP_VERSION", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", @@ -96,6 +96,8 @@ "LINGER_PI_SESSION_ROOT", "LINGER_TOOLS_NODE_PATH", "LINGER_WEB_URL", + "MSYS2_ARG_CONV_EXCL", + "MSYS_NO_PATHCONV", "TEAMHUB_AGENT_ID", "TEAMHUB_CONFIG", "TEAMHUB_PROFILE",