diff --git a/AGENTS.md b/AGENTS.md index f824673..5459fac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -142,6 +142,7 @@ This is stderr only — it won't break piped output parsing. | `BW_CLIENT_SECRET` | OAuth2 client secret | | `OPENAI_API_KEY` | OpenAI API key for the `live-assistant` sample | | `TRANSFER_TO` | Transfer destination (E.164) for the `live-assistant` sample | +| `USER_NUMBER` | Destination number (E.164) for the `voice-bridge` sample | | `BW_ACCOUNT_ID` | Override active account | | `BW_ENVIRONMENT` | API environment: `prod` (default), `test` | | `BW_API_URL` | Override API base URL (overrides environment-based default) | @@ -376,7 +377,8 @@ For full flag/argument reference, use `band --help`. This section cove - **`band sample run` is helpful for demoing what a developer can accomplish with Bandwidth.** It clones a repo, starts a local process, launches ngrok, and blocks for the lifetime of the app. If you need to deploy a sample for a user, use the step-by-step [Agent Workflows](#agent-workflows) for the underlying provisioning. - **`band sample list` is safe for discovery.** Run it to enumerate available samples and supported languages before telling a user which command to run. -- **Credentials are auto-wired.** `band sample run` reads the active band profile and writes `BW_ACCOUNT_ID`, `BW_CLIENT_ID`, and `BW_CLIENT_SECRET` to a `.env` file in the clone directory — the user never needs to copy credentials manually. Sample-specific configuration (like `OPENAI_API_KEY` and `TRANSFER_TO` for the `live-assistant` sample) is read from the environment and must be exported before running. There are no flags for these — run the sample without them and the error names each one. +- **Credentials are auto-wired.** `band sample run` reads the active band profile and wires `BW_ACCOUNT_ID`, `BW_CLIENT_ID`, and `BW_CLIENT_SECRET` into the sample (via a `.env` file and process environment). Sample-specific configuration (like `OPENAI_API_KEY`, `TRANSFER_TO`, and `USER_NUMBER`) is read from the environment and must be exported before running. There are no flags for these — run the sample without them and the error names each one. +- **Python samples require Python 3.11+.** The pinned dependencies in the sample repos require it; the CLI fails fast with a clear message if you run a Python sample on an older interpreter. - **The `live-assistant` sample is the primary voice AI demo.** It pairs Bandwidth's PSTN infrastructure (dialing, audio streaming, webhook routing) with the OpenAI Realtime API. The command to give a user: ```bash @@ -390,7 +392,10 @@ For full flag/argument reference, use `band --help`. This section cove Prerequisites the user needs: ngrok (`brew install ngrok/ngrok/ngrok`), Python 3.11+, and an OpenAI API key with Realtime API access. A Bandwidth Build trial account is sufficient — no full account required. -- **Voice application and phone number are resolved automatically.** `band sample run` calls `band app list` internally and creates (or reuses) a voice application named `band-sample-`. It picks the first in-service phone number on the account. No manual provisioning needed before running the sample. +- **Voice application and phone number are resolved automatically.** `band sample run` creates (or reuses) a voice application named `band-sample-` and updates its callback URLs for the current ngrok tunnel. + + - For **inbound-only** samples (e.g. `voice-record`), Build credentials may not be permitted to change location-level routing via the Dashboard API. In that case the CLI temporarily updates the inbound app that the number already routes to (falling back to an app named `default-http-voice` when it can't be resolved), and restores the original callback URLs on exit. + - For other samples, the CLI best-effort assigns the sample app to the number's location so inbound calls reach the sample callbacks when the account permits it. --- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a6bb951..ef508dc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,13 +12,15 @@ make test # run tests make lint # run golangci-lint ``` -Requires Go 1.27.3+ and [golangci-lint](https://golangci-lint.run/welcome/install/). - -Go 1.27.3 includes the `crypto/x509` fix rejecting the compromised eMudhra -intermediate certificates. CI and release builds select the toolchain from -`go.mod`; keep the Docker builder's version aligned with that minimum. Existing -CLI binaries and container images must be rebuilt to pick up the fix; updating -the host's Go installation does not patch an already compiled binary. +Requires Go 1.27.4+ and [golangci-lint](https://golangci-lint.run/welcome/install/). + +Go 1.27.4 includes the `crypto/x509` fix rejecting the compromised eMudhra +intermediate certificates (introduced in 1.27.3), and also includes fixes for +newer standard-library vulnerabilities flagged by `govulncheck`. CI and release +builds select the toolchain from `go.mod`; keep the Docker builder's version +aligned with that minimum. Existing CLI binaries and container images must be +rebuilt to pick up fixes; updating the host's Go installation does not patch an +already compiled binary. ## What happens when you open a PR diff --git a/Dockerfile b/Dockerfile index 4f9cf99..2d355b6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.27.3-alpine AS builder +FROM golang:1.27.4-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download diff --git a/README.md b/README.md index 3fcee1f..d392722 100644 --- a/README.md +++ b/README.md @@ -623,6 +623,7 @@ All five share the same filters: `--to`/`--from` (comma-separated E.164), `--dir | `BW_MESSAGING_URL` | Override the Messaging API base URL. Messaging is production-only (no test host), so `--environment`/`BW_ENVIRONMENT` does not change it; use this for local proxies or the internal lab. | | `OPENAI_API_KEY` | OpenAI API key for the `live-assistant` sample (`band sample run`) | | `TRANSFER_TO` | Transfer destination in E.164 for the `live-assistant` sample (`band sample run`) | +| `USER_NUMBER` | Destination number for the `voice-bridge` sample (`band sample run`) | --- @@ -708,9 +709,19 @@ Want to see Bandwidth in action without writing any boilerplate? The CLI ships w ```sh band sample list # see what's available OPENAI_API_KEY=sk-... TRANSFER_TO=+19195550100 band sample run live-assistant --language python +band sample run voice-gather --language python --call-to +19195550101 +band sample run voice-record --language python +USER_NUMBER=+19195550100 band sample run voice-bridge --language python +band sample run voice-redirect-loop --language python ``` -`band sample run` handles everything: clones the GitHub repo, creates a virtual environment, installs dependencies, starts an ngrok tunnel, wires your Bandwidth credentials into a `.env` file, creates or reuses a voice application, and launches the app. Pass `--call-to` and it dials a number automatically once the app is healthy. +`band sample run` handles everything: clones the GitHub repo, creates a Python virtual environment (for Python samples), installs dependencies, starts an ngrok tunnel, wires your Bandwidth credentials into a `.env` file, creates or reuses a voice application, and launches the app. + +**Python samples require Python 3.11+.** The pinned dependencies in the sample repos require it; the CLI fails fast with a clear message if you run a Python sample on an older interpreter. + +Pass `--call-to` to automatically dial a number once the app is healthy. This is only supported by samples that implement outbound call flows (for example, `voice-gather` and `live-assistant`). Inbound-only samples (for example, `voice-record`) should be tested by calling your Bandwidth number after the app starts. + +**Bandwidth Build accounts:** inbound-only samples temporarily update your account's default inbound voice application (`default-http-voice`) to point at the ngrok URL for this run, then restore it when the sample exits. This makes inbound testing work out of the box even when the account doesn't permit location-level routing changes via API. Samples that need their own configuration read it from the environment, the same way `BW_CLIENT_ID` and `BW_CLIENT_SECRET` do. Run a sample without them and the CLI tells you which variables it expects. diff --git a/cmd/sample/catalog.go b/cmd/sample/catalog.go index 173a2f0..3729780 100644 --- a/cmd/sample/catalog.go +++ b/cmd/sample/catalog.go @@ -17,6 +17,22 @@ type langSetup struct { RunCmd []string // HealthPath is the HTTP path polled to detect a ready server. HealthPath string + // MinPython is the minimum required Python version for python variants, + // in major.minor form (e.g. "3.11"). Empty means "no minimum enforced". + MinPython string +} + +// voiceConfig describes how to wire a sample app up for Programmable Voice callbacks. +type voiceConfig struct { + // InitiateCallbackPath is appended to the ngrok base URL and used as the voice + // application's CallInitiatedCallbackUrl. + InitiateCallbackPath string + // StatusCallbackPath is appended to the ngrok base URL and used as the voice + // application's CallStatusCallbackUrl. When empty, InitiateCallbackPath is used. + StatusCallbackPath string + // DialAnswerPath is appended to the ngrok base URL and used as the answer URL + // when `band sample run --call-to` auto-initiates an outbound call. + DialAnswerPath string } // SampleEntry describes one sample app and its variants. @@ -28,6 +44,8 @@ type SampleEntry struct { ExtraEnv []envPrompt // Setup maps language name → build/run instructions. Setup map[string]langSetup + // Voice is non-nil when the sample expects Programmable Voice callbacks. + Voice *voiceConfig // Port is the default local port the app listens on. Port int } @@ -47,24 +65,152 @@ var catalog = map[string]*SampleEntry{ "python": { AppDir: "app", InstallCmd: []string{".venv/bin/pip", "install", "-q", "-r", "app/requirements.txt"}, - RunCmd: []string{".venv/bin/python3", "main.py"}, + RunCmd: []string{".venv/bin/python", "main.py"}, HealthPath: "/health", + MinPython: "3.11", }, }, + Voice: &voiceConfig{ + InitiateCallbackPath: "/webhooks/bandwidth/voice/initiate", + StatusCallbackPath: "/webhooks/bandwidth/voice/status", + DialAnswerPath: "/webhooks/bandwidth/voice/initiate", + }, Port: 3000, }, "voice-gather": { Description: "In-call DTMF gather example", Repos: map[string]string{ - "python": "https://github.com/Bandwidth-Samples/in-call-gather-python", + "python": "https://github.com/Bandwidth-Samples/voice-gather-python", + "node": "https://github.com/Bandwidth-Samples/voice-gather-js", + "java": "https://github.com/Bandwidth-Samples/voice-gather-java", + }, + Setup: map[string]langSetup{ + "python": { + AppDir: ".", + InstallCmd: []string{".venv/bin/pip", "install", "-q", "-r", "requirements.txt"}, + RunCmd: []string{".venv/bin/python", "main.py"}, + HealthPath: "/", + MinPython: "3.11", + }, + "node": { + AppDir: ".", + InstallCmd: []string{"npm", "i"}, + RunCmd: []string{"npm", "start"}, + HealthPath: "/", + }, + "java": { + AppDir: ".", + InstallCmd: []string{"mvn", "package", "-q"}, + RunCmd: []string{"mvn", "spring-boot:run"}, + HealthPath: "/", + }, + }, + Voice: &voiceConfig{ + InitiateCallbackPath: "/callbacks/outbound/voice", + DialAnswerPath: "/callbacks/outbound/voice", + }, + Port: 3000, + }, + "voice-record": { + Description: "Record a message from a call (voicemail-style)", + Repos: map[string]string{ + "python": "https://github.com/Bandwidth-Samples/voice-record-python", + "node": "https://github.com/Bandwidth-Samples/voice-record-js", + "java": "https://github.com/Bandwidth-Samples/voice-record-java", + }, + Setup: map[string]langSetup{ + "python": { + AppDir: ".", + InstallCmd: []string{".venv/bin/pip", "install", "-q", "-r", "requirements.txt"}, + RunCmd: []string{".venv/bin/python", "main.py"}, + HealthPath: "/", + MinPython: "3.11", + }, + "node": { + AppDir: ".", + InstallCmd: []string{"npm", "i"}, + RunCmd: []string{"npm", "start"}, + HealthPath: "/", + }, + "java": { + AppDir: ".", + InstallCmd: []string{"mvn", "package", "-q"}, + RunCmd: []string{"mvn", "spring-boot:run"}, + HealthPath: "/", + }, + }, + Voice: &voiceConfig{ + InitiateCallbackPath: "/callbacks/inbound/voice", + }, + Port: 3000, + }, + "voice-bridge": { + Description: "Mask a call by bridging the caller to a configured destination number", + Repos: map[string]string{ + "python": "https://github.com/Bandwidth-Samples/voice-bridge-python", + "node": "https://github.com/Bandwidth-Samples/voice-bridge-js", + "java": "https://github.com/Bandwidth-Samples/voice-bridge-java", + }, + ExtraEnv: []envPrompt{ + {Key: "USER_NUMBER", Description: "Phone number to bridge calls to (E.164, e.g. +19195550100)"}, }, Setup: map[string]langSetup{ "python": { AppDir: ".", InstallCmd: []string{".venv/bin/pip", "install", "-q", "-r", "requirements.txt"}, - RunCmd: []string{".venv/bin/python3", "app.py"}, + RunCmd: []string{".venv/bin/python", "main.py"}, HealthPath: "/", + MinPython: "3.11", }, + "node": { + AppDir: ".", + InstallCmd: []string{"npm", "i"}, + RunCmd: []string{"npm", "start"}, + HealthPath: "/", + }, + "java": { + AppDir: ".", + InstallCmd: []string{"mvn", "package", "-q"}, + RunCmd: []string{"mvn", "spring-boot:run"}, + HealthPath: "/", + }, + }, + Voice: &voiceConfig{ + InitiateCallbackPath: "/callbacks/inbound/voice", + }, + Port: 3000, + }, + "voice-redirect-loop": { + Description: "Indefinitely redirect a call until interrupted (demo of Redirect and UpdateCall)", + Repos: map[string]string{ + "python": "https://github.com/Bandwidth-Samples/voice-redirect-loop-python", + "node": "https://github.com/Bandwidth-Samples/voice-redirect-loop-js", + "java": "https://github.com/Bandwidth-Samples/voice-redirect-loop-java", + }, + Setup: map[string]langSetup{ + "python": { + AppDir: ".", + InstallCmd: []string{".venv/bin/pip", "install", "-q", "-r", "requirements.txt"}, + RunCmd: []string{".venv/bin/python", "main.py"}, + HealthPath: "/", + MinPython: "3.11", + }, + "node": { + AppDir: ".", + InstallCmd: []string{"npm", "i"}, + RunCmd: []string{"npm", "start"}, + HealthPath: "/", + }, + "java": { + AppDir: ".", + InstallCmd: []string{"mvn", "package", "-q"}, + RunCmd: []string{"mvn", "spring-boot:run"}, + HealthPath: "/", + }, + }, + Voice: &voiceConfig{ + InitiateCallbackPath: "/callbacks/inbound/voice", + StatusCallbackPath: "/callbacks/inbound/voice/disconnect", }, Port: 3000, }, diff --git a/cmd/sample/run.go b/cmd/sample/run.go index fa86b48..2d0045f 100644 --- a/cmd/sample/run.go +++ b/cmd/sample/run.go @@ -3,11 +3,15 @@ package sample import ( "context" "encoding/json" + "errors" "fmt" "net/http" + "net/url" "os" "os/exec" "path/filepath" + "regexp" + "sort" "strconv" "strings" "time" @@ -24,6 +28,7 @@ var ( runLanguage string runCallTo string runPort int + runVoiceApp string ) var runCmd = &cobra.Command{ @@ -36,10 +41,20 @@ Samples that need their own configuration read it from the environment, the same way BW_CLIENT_ID and BW_CLIENT_SECRET work. Run the command without them to see which variables a given sample expects. -Pass --call-to to automatically dial a number once the app is ready.`, +Python samples require Python 3.11+. + +Pass --call-to to automatically dial a number once the app is ready. This is +only supported by samples that implement outbound call flows (e.g. voice-gather, +live-assistant). Inbound-only samples (e.g. voice-record) should be tested by +calling your Bandwidth number after the app starts.`, Example: ` band sample run live-assistant --language python OPENAI_API_KEY=sk-... TRANSFER_TO=+19195550100 band sample run live-assistant --language python - OPENAI_API_KEY=sk-... TRANSFER_TO=+19195550100 band sample run live-assistant --language python --call-to +19195550101`, + OPENAI_API_KEY=sk-... TRANSFER_TO=+19195550100 band sample run live-assistant --language python --call-to +19195550101 + + band sample run voice-gather --language python --call-to +19195550101 + band sample run voice-redirect-loop --language python + band sample run voice-record --language python + USER_NUMBER=+19195550100 band sample run voice-bridge --language python`, Args: cobra.ExactArgs(1), RunE: runSample, } @@ -48,6 +63,7 @@ func init() { runCmd.Flags().StringVarP(&runLanguage, "language", "l", "", "Language variant to run (required)") runCmd.Flags().StringVar(&runCallTo, "call-to", "", "Phone number to call after the app is ready (E.164)") runCmd.Flags().IntVar(&runPort, "port", 0, "Local port (default: from catalog)") + runCmd.Flags().StringVar(&runVoiceApp, "voice-app", "", "Voice-V2 application ID to use for inbound routing overrides (advanced)") _ = runCmd.MarkFlagRequired("language") } @@ -60,12 +76,17 @@ func runSample(cmd *cobra.Command, args []string) error { if !ok { return fmt.Errorf("unknown sample %q — run `band sample list` to see available samples", name) } + if entry.Voice == nil { + return fmt.Errorf("sample %q is not runnable yet — open a PR to add its provisioning and runtime wiring", name) + } + inboundOnly := entry.Voice.DialAnswerPath == "" repoURL, ok := entry.Repos[runLanguage] if !ok { supported := make([]string, 0, len(entry.Repos)) for l := range entry.Repos { supported = append(supported, l) } + sort.Strings(supported) return fmt.Errorf("language %q not supported for %q (available: %s)", runLanguage, name, strings.Join(supported, ", ")) } setup, ok := entry.Setup[runLanguage] @@ -90,7 +111,8 @@ func runSample(cmd *cobra.Command, args []string) error { } // ── Prerequisites ──────────────────────────────────────────────────────── - if err := checkPrerequisites(runLanguage); err != nil { + pythonExe, err := checkPrerequisites(runLanguage, setup.MinPython) + if err != nil { return err } @@ -130,31 +152,114 @@ func runSample(cmd *cobra.Command, args []string) error { return err } - appID, err := ensureVoiceApp(ctx, dashClient, acctID, "band-sample-"+name, - publicURL+"/webhooks/bandwidth/voice/initiate", - publicURL+"/webhooks/bandwidth/voice/status", - ) + numInfo, err := firstPhoneNumber(ctx, dashClient, acctID) if err != nil { return err } + phoneNumber := numInfo.PhoneNumber + ui.Successf("Using number: %s", ui.ID(phoneNumber)) - phoneNumber, err := firstPhoneNumber(ctx, dashClient, acctID) - if err != nil { - return err + appName := "band-sample-" + name + appID := "" + var restoreCallbacks func() + + if inboundOnly { + // For inbound-only samples, prefer updating the routed voice application's + // callback URLs (Build accounts ship with a default HTTP voice app that the + // pre-provisioned number routes to). This avoids permission-gated location + // assignment endpoints on restricted credentials. + overrideID := runVoiceApp + if overrideID == "" { + // Allow an explicit env override for selecting the inbound app. + // (Note: the runner also writes BW_VOICE_APPLICATION_ID into the sample's .env; + // this env var is read from the user's environment before we write that file.) + overrideID = os.Getenv("BW_SAMPLE_VOICE_APP_ID") + if overrideID == "" { + overrideID = os.Getenv("BW_VOICE_APPLICATION_ID") + } + } + + routedID, routedName, err := resolveInboundVoiceApp(ctx, dashClient, acctID, numInfo, appName, overrideID) + if err != nil { + return err + } + appID = routedID + + statePath, err := voiceAppOverrideStatePath(acctID, appID) + if err != nil { + return err + } + // If a previous run crashed, restore first. + _ = restoreVoiceAppOverrideIfPresent(ctx, dashClient, acctID, appID, statePath) + + newInitiate := publicURL + entry.Voice.InitiateCallbackPath + newStatus := "" + if entry.Voice.StatusCallbackPath != "" { + newStatus = publicURL + entry.Voice.StatusCallbackPath + } + + restore, err := overrideVoiceAppCallbacks(ctx, dashClient, acctID, appID, routedName, newInitiate, newStatus, statePath) + if err != nil { + return err + } + restoreCallbacks = func() { + restoreCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := restore(restoreCtx); err != nil { + ui.Warnf("Failed to restore %s callbacks: %v", routedName, err) + } + } + defer restoreCallbacks() + + ui.Successf("Inbound app overridden: %s (%s)", ui.ID(appID), routedName) + ui.Infof("Callback URL updated for this run and will be restored on exit.") + } else { + statusPath := entry.Voice.StatusCallbackPath + if statusPath == "" { + statusPath = entry.Voice.InitiateCallbackPath + } + appID, err = ensureVoiceApp(ctx, dashClient, acctID, appName, + publicURL+entry.Voice.InitiateCallbackPath, + publicURL+statusPath, + ) + if err != nil { + return err + } + + // Optional: assign the app to the number's location for accounts that allow it. + ensureVoiceAppOnNumberLocationBestEffort(ctx, dashClient, acctID, phoneNumber, numInfo.SiteID, numInfo.SipPeerID, appID, appName) + } + + // Inbound-only samples don't implement answer webhooks, so we can't auto-dial + // them; the correct flow is to call the Bandwidth number after the app starts. + if runCallTo != "" && inboundOnly { + return fmt.Errorf("%q does not support --call-to (it handles inbound calls only). Start the app, then call %s", name, phoneNumber) } - ui.Successf("Using number: %s", ui.ID(phoneNumber)) // ── Python venv setup (language-specific) ─────────────────────────────── if runLanguage == "python" { + if pythonExe == "" { + return fmt.Errorf("python interpreter not resolved") + } venvSpin := ui.NewSpinner("Creating Python virtual environment...") venvSpin.Start() - venvCmd := exec.CommandContext(ctx, "python3", "-m", "venv", ".venv") + venvCmd := exec.CommandContext(ctx, pythonExe, "-m", "venv", ".venv") venvCmd.Dir = cloneDir if out, err := venvCmd.CombinedOutput(); err != nil { venvSpin.Stop() return fmt.Errorf("creating venv: %w\n%s", err, out) } venvSpin.Stop() + + pipSpin := ui.NewSpinner("Upgrading pip...") + pipSpin.Start() + upgradeCmd := exec.CommandContext(ctx, filepath.Join(cloneDir, ".venv", "bin", "pip"), "install", "-q", "--upgrade", "pip", "setuptools", "wheel") + upgradeCmd.Dir = cloneDir + if out, err := upgradeCmd.CombinedOutput(); err != nil { + pipSpin.Stop() + return fmt.Errorf("upgrading pip: %w\n%s", err, out) + } + pipSpin.Stop() } // ── Install dependencies ───────────────────────────────────────────────── @@ -174,9 +279,10 @@ func runSample(cmd *cobra.Command, args []string) error { "BW_ACCOUNT_ID": acctID, "BW_CLIENT_ID": clientID, "BW_CLIENT_SECRET": clientSecret, + "BASE_URL": publicURL, + "BASE_CALLBACK_URL": publicURL, "BW_VOICE_APPLICATION_ID": appID, "BW_NUMBER": phoneNumber, - "BASE_URL": publicURL, "LOCAL_PORT": strconv.Itoa(port), "LOG_LEVEL": "INFO", } @@ -203,6 +309,10 @@ func runSample(cmd *cobra.Command, args []string) error { } appCmd := exec.CommandContext(ctx, runExe, setup.RunCmd[1:]...) appCmd.Dir = filepath.Join(cloneDir, setup.AppDir) + appCmd.Env = os.Environ() + for k, v := range envVars { + appCmd.Env = append(appCmd.Env, k+"="+v) + } appCmd.Stdout = os.Stdout appCmd.Stderr = os.Stderr if err := appCmd.Start(); err != nil { @@ -220,11 +330,12 @@ func runSample(cmd *cobra.Command, args []string) error { time.Sleep(500 * time.Millisecond) // brief pause after health before dialing fmt.Fprintf(os.Stderr, "\n[sample] Dialing %s...\n", runCallTo) var resp interface{} + answerURL := publicURL + entry.Voice.DialAnswerPath body := callcmd.BuildCreateBody(callcmd.CreateOpts{ From: phoneNumber, To: runCallTo, AppID: appID, - AnswerURL: publicURL + "/webhooks/bandwidth/voice/initiate", + AnswerURL: answerURL, }) if err := voiceClient.Post(ctx, fmt.Sprintf("/accounts/%s/calls", acctID), body, &resp); err != nil { fmt.Fprintf(os.Stderr, "[sample] call failed: %v\n", err) @@ -271,11 +382,19 @@ func collectExtraEnv(name, lang string, entry *SampleEntry) (map[string]string, } // checkPrerequisites verifies that git, ngrok, and the language runtime exist. -func checkPrerequisites(lang string) error { +// Returns the resolved Python interpreter path when lang=="python". +func checkPrerequisites(lang string, minPython string) (string, error) { required := []string{"git", "ngrok"} + var pythonExe string switch lang { case "python": - required = append(required, "python3") + var version string + var err error + pythonExe, version, err = resolvePython(minPython) + if err != nil { + return "", err + } + ui.Successf("Using Python: %s (%s)", ui.ID(pythonExe), version) case "node": required = append(required, "node", "npm") case "java": @@ -288,9 +407,133 @@ func checkPrerequisites(lang string) error { } } if len(missing) > 0 { - return fmt.Errorf("missing required tools: %s", strings.Join(missing, ", ")) + return "", fmt.Errorf("missing required tools: %s", strings.Join(missing, ", ")) } - return nil + return pythonExe, nil +} + +type pythonVersion struct { + Major int + Minor int + Patch int +} + +func (v pythonVersion) String() string { + return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch) +} + +func parsePythonVersion(s string) (pythonVersion, bool) { + parts := strings.Split(strings.TrimSpace(s), ".") + if len(parts) < 2 { + return pythonVersion{}, false + } + atoi := func(x string) (int, bool) { + n, err := strconv.Atoi(x) + return n, err == nil + } + maj, ok := atoi(parts[0]) + if !ok { + return pythonVersion{}, false + } + min, ok := atoi(parts[1]) + if !ok { + return pythonVersion{}, false + } + patch := 0 + if len(parts) >= 3 { + if p, ok := atoi(parts[2]); ok { + patch = p + } + } + return pythonVersion{Major: maj, Minor: min, Patch: patch}, true +} + +func (v pythonVersion) less(o pythonVersion) bool { + if v.Major != o.Major { + return v.Major < o.Major + } + if v.Minor != o.Minor { + return v.Minor < o.Minor + } + return v.Patch < o.Patch +} + +func parseMinPython(min string) (pythonVersion, bool) { + if min == "" { + return pythonVersion{}, false + } + v, ok := parsePythonVersion(min + ".0") + return v, ok +} + +type pythonCandidate struct { + Path string + Version pythonVersion +} + +// resolvePython picks the newest python3.x on PATH that satisfies minPython (major.minor). +// If minPython is empty, it picks the newest python3.x available. +func resolvePython(minPython string) (string, string, error) { + min, hasMin := parseMinPython(minPython) + if minPython != "" && !hasMin { + return "", "", fmt.Errorf("invalid minimum python version %q (expected major.minor, e.g. 3.11)", minPython) + } + + // Collect candidate executable names from PATH: python3 plus any python3.N we can see. + candidates := map[string]struct{}{"python3": {}} + re := regexp.MustCompile(`^python3\.(\d+)$`) + for _, dir := range filepath.SplitList(os.Getenv("PATH")) { + entries, err := os.ReadDir(dir) + if err != nil { + continue + } + for _, e := range entries { + name := e.Name() + if name == "python3" || re.MatchString(name) { + candidates[name] = struct{}{} + } + } + } + + var found []pythonCandidate + for name := range candidates { + path, err := exec.LookPath(name) + if err != nil { + continue + } + out, err := exec.Command(path, "-c", `import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")`).CombinedOutput() + if err != nil { + continue + } + v, ok := parsePythonVersion(string(out)) + if !ok { + continue + } + // Only consider python3.x + if v.Major != 3 { + continue + } + found = append(found, pythonCandidate{Path: path, Version: v}) + } + + if len(found) == 0 { + return "", "", fmt.Errorf("python3 not found — install Python 3.11+") + } + + sort.Slice(found, func(i, j int) bool { return found[j].Version.less(found[i].Version) }) // desc + + for _, c := range found { + // Choose the newest version that satisfies the minimum. + if !hasMin || !c.Version.less(min) { + return c.Path, c.Version.String(), nil + } + } + + best := found[0] + if hasMin { + return "", "", fmt.Errorf("python %d.%d+ required, found %s at %s", min.Major, min.Minor, best.Version.String(), best.Path) + } + return best.Path, best.Version.String(), nil } // ensureCloned clones repoURL to ~/.band/samples/-/ or pulls if @@ -303,18 +546,35 @@ func ensureCloned(ctx context.Context, repoURL, name, lang string) (string, erro cloneDir := filepath.Join(home, ".band", "samples", name+"-"+lang) if _, err := os.Stat(filepath.Join(cloneDir, ".git")); err == nil { - spin := ui.NewSpinner("Updating sample repo...") - spin.Start() - pullCmd := exec.CommandContext(ctx, "git", "pull", "--ff-only") - pullCmd.Dir = cloneDir - out, err := pullCmd.CombinedOutput() - spin.Stop() - if err != nil { - fmt.Fprintf(os.Stderr, "git pull failed (%v), proceeding with existing clone\n%s\n", err, out) + remoteCmd := exec.CommandContext(ctx, "git", "remote", "get-url", "origin") + remoteCmd.Dir = cloneDir + remoteOut, remoteErr := remoteCmd.CombinedOutput() + if remoteErr == nil { + remote := strings.TrimSpace(string(remoteOut)) + if remote != "" && remote != repoURL { + backupDir := cloneDir + ".bak-" + strconv.FormatInt(time.Now().Unix(), 10) + if err := os.Rename(cloneDir, backupDir); err != nil { + return "", fmt.Errorf("existing sample clone has origin %q (expected %q), and moving it aside failed: %w", remote, repoURL, err) + } + ui.Successf("Existing clone origin mismatch; moved aside: %s", backupDir) + } + } + if _, err := os.Stat(filepath.Join(cloneDir, ".git")); err != nil { + // cloneDir was moved aside above; fall through to clone below } else { - ui.Successf("Repo up to date: %s", cloneDir) + spin := ui.NewSpinner("Updating sample repo...") + spin.Start() + pullCmd := exec.CommandContext(ctx, "git", "pull", "--ff-only") + pullCmd.Dir = cloneDir + out, err := pullCmd.CombinedOutput() + spin.Stop() + if err != nil { + fmt.Fprintf(os.Stderr, "git pull failed (%v), proceeding with existing clone\n%s\n", err, out) + } else { + ui.Successf("Repo up to date: %s", cloneDir) + } + return cloneDir, nil } - return cloneDir, nil } if err := os.MkdirAll(filepath.Dir(cloneDir), 0o755); err != nil { @@ -373,7 +633,9 @@ func waitForHealth(ctx context.Context, url string, timeout time.Duration) error resp, err := http.Get(url) if err == nil { resp.Body.Close() - if resp.StatusCode < 300 { + // Many samples don't have a dedicated health endpoint; treat any + // non-5xx response as "the server is up". + if resp.StatusCode < 500 { return nil } } @@ -390,7 +652,25 @@ func ensureVoiceApp(ctx context.Context, client *api.Client, acctID, appName, in return "", fmt.Errorf("listing applications: %w", err) } if id := findAppByName(listResp, appName); id != "" { - ui.Successf("Voice application (existing): %s", ui.ID(id)) + // Keep the app but update its callback URLs for the current ngrok tunnel. + spin := ui.NewSpinner("Updating voice application...") + spin.Start() + var result interface{} + body := api.XMLBody{ + RootElement: "Application", + Data: map[string]interface{}{ + "ServiceType": "Voice-V2", + "AppName": appName, + "CallInitiatedCallbackUrl": initiateURL, + "CallStatusCallbackUrl": statusURL, + }, + } + err := client.Put(ctx, fmt.Sprintf("/accounts/%s/applications/%s", acctID, url.PathEscape(id)), body, &result) + spin.Stop() + if err != nil { + return "", fmt.Errorf("updating voice application: %w", err) + } + ui.Successf("Voice application (updated): %s", ui.ID(id)) return id, nil } @@ -420,25 +700,451 @@ func ensureVoiceApp(ctx context.Context, client *api.Client, acctID, appName, in return id, nil } +type voiceAppCallbacks struct { + AppID string + AppName string + Initiate string + Status string + ServiceType string +} + +func getVoiceAppCallbacks(ctx context.Context, client api.Requester, acctID, appID string) (voiceAppCallbacks, error) { + var existing interface{} + if err := client.Get(ctx, fmt.Sprintf("/accounts/%s/applications/%s", acctID, url.PathEscape(appID)), &existing); err != nil { + return voiceAppCallbacks{}, fmt.Errorf("getting application: %w", err) + } + return voiceAppCallbacks{ + AppID: appID, + AppName: extractStringField(existing, "AppName", "appName"), + Initiate: extractStringField(existing, "CallInitiatedCallbackUrl", "callInitiatedCallbackUrl"), + Status: extractStringField(existing, "CallStatusCallbackUrl", "callStatusCallbackUrl"), + ServiceType: extractStringField(existing, "ServiceType", "serviceType"), + }, nil +} + +func setVoiceAppCallbacks(ctx context.Context, client api.Requester, acctID string, cb voiceAppCallbacks) error { + body := api.XMLBody{ + RootElement: "Application", + Data: map[string]interface{}{ + "ServiceType": "Voice-V2", + "AppName": cb.AppName, + "CallInitiatedCallbackUrl": cb.Initiate, + }, + } + if cb.Status != "" { + body.Data["CallStatusCallbackUrl"] = cb.Status + } + var result interface{} + if err := client.Put(ctx, fmt.Sprintf("/accounts/%s/applications/%s", acctID, url.PathEscape(cb.AppID)), body, &result); err != nil { + return fmt.Errorf("updating application: %w", err) + } + return nil +} + +type voiceAppOverrideState struct { + AccountID string `json:"accountId"` + ApplicationID string `json:"applicationId"` + AppName string `json:"appName"` + OriginalInitiate string `json:"originalCallInitiatedCallbackUrl"` + OriginalStatus string `json:"originalCallStatusCallbackUrl"` + CreatedAt string `json:"createdAt"` +} + +func voiceAppOverrideStatePath(acctID, appID string) (string, error) { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + dir := filepath.Join(home, ".band", "sample-state", "voice-app-overrides") + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", fmt.Errorf("creating sample state dir: %w", err) + } + safe := strings.ReplaceAll(appID, string(os.PathSeparator), "_") + return filepath.Join(dir, acctID+"-"+safe+".json"), nil +} + +func restoreVoiceAppOverrideIfPresent(ctx context.Context, client api.Requester, acctID, appID, statePath string) error { + data, err := os.ReadFile(statePath) + if err != nil { + return nil // nothing to restore + } + var st voiceAppOverrideState + if err := json.Unmarshal(data, &st); err != nil { + return nil + } + if st.ApplicationID != appID || st.AccountID != acctID { + return nil + } + restore := voiceAppCallbacks{AppID: appID, AppName: st.AppName, Initiate: st.OriginalInitiate, Status: st.OriginalStatus} + if err := setVoiceAppCallbacks(ctx, client, acctID, restore); err != nil { + return err + } + _ = os.Remove(statePath) + return nil +} + +// overrideVoiceAppCallbacks updates a voice application's callback URLs for the +// duration of a run and returns a restore function. When newStatus is empty, the +// application's existing CallStatusCallbackUrl is preserved. +func overrideVoiceAppCallbacks(ctx context.Context, client api.Requester, acctID, appID, appName, newInitiate, newStatus, statePath string) (func(context.Context) error, error) { + current, err := getVoiceAppCallbacks(ctx, client, acctID, appID) + if err != nil { + return nil, err + } + if current.ServiceType != "" && current.ServiceType != "Voice-V2" { + return nil, fmt.Errorf("application %s is %s, expected Voice-V2", appID, current.ServiceType) + } + if appName == "" { + appName = current.AppName + } + original := voiceAppCallbacks{AppID: appID, AppName: appName, Initiate: current.Initiate, Status: current.Status} + target := voiceAppCallbacks{AppID: appID, AppName: appName, Initiate: newInitiate, Status: current.Status} + if newStatus != "" { + target.Status = newStatus + } + + st := voiceAppOverrideState{ + AccountID: acctID, + ApplicationID: appID, + AppName: appName, + OriginalInitiate: original.Initiate, + OriginalStatus: original.Status, + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + b, _ := json.MarshalIndent(st, "", " ") + if err := os.WriteFile(statePath, b, 0o600); err != nil { + return nil, fmt.Errorf("writing override state: %w", err) + } + + if err := setVoiceAppCallbacks(ctx, client, acctID, target); err != nil { + return nil, err + } + + return func(restoreCtx context.Context) error { + err := setVoiceAppCallbacks(restoreCtx, client, acctID, original) + _ = os.Remove(statePath) + return err + }, nil +} + +type inboundResolution struct { + notes []string + voice []voiceAppSummary +} + +func (r inboundResolution) errorf(format string, a ...interface{}) error { + var b strings.Builder + fmt.Fprintf(&b, format, a...) + if len(r.notes) > 0 { + b.WriteString("\n\nLookups attempted:\n") + for _, n := range r.notes { + b.WriteString(" - " + n + "\n") + } + } + if len(r.voice) > 0 { + b.WriteString("\nVoice-V2 applications found:\n") + for _, v := range r.voice { + if v.name != "" { + fmt.Fprintf(&b, " - %s (%s)\n", v.name, v.id) + } else { + fmt.Fprintf(&b, " - %s\n", v.id) + } + } + } + b.WriteString("\n\nTo override selection, pass --voice-app or set BW_SAMPLE_VOICE_APP_ID.") + return errors.New(b.String()) +} + +func statusNote(step string, err error) string { + var apiErr *api.APIError + if errors.As(err, &apiErr) { + return fmt.Sprintf("%s → %d", step, apiErr.StatusCode) + } + return fmt.Sprintf("%s → %v", step, err) +} + +// resolveInboundVoiceApp tries to determine which Voice-V2 app inbound calls to +// the selected number are routed to, using only endpoints that restricted +// credentials (notably Build OAuth creds) can often access. +func resolveInboundVoiceApp(ctx context.Context, client api.Requester, acctID string, numInfo sampleNumberInfo, sampleAppName string, overrideID string) (string, string, error) { + res := inboundResolution{} + + if overrideID != "" { + cb, err := getVoiceAppCallbacks(ctx, client, acctID, overrideID) + if err != nil { + res.notes = append(res.notes, statusNote("GET /applications/", err)) + return "", "", res.errorf("failed to use --voice-app/BW_SAMPLE_VOICE_APP_ID %q: %v", overrideID, err) + } + return overrideID, cb.AppName, nil + } + + var listResp interface{} + if err := client.Get(ctx, fmt.Sprintf("/accounts/%s/applications", acctID), &listResp); err != nil { + res.notes = append(res.notes, statusNote("GET /applications", err)) + return "", "", res.errorf("could not list applications: %v", err) + } + res.voice = findAllVoiceApps(listResp) + + // If /tns already gave us an app id, trust it. + if numInfo.VoiceAppID != "" { + cb, err := getVoiceAppCallbacks(ctx, client, acctID, numInfo.VoiceAppID) + if err == nil { + return numInfo.VoiceAppID, cb.AppName, nil + } + res.notes = append(res.notes, statusNote("GET /applications/", err)) + } + + // If exactly one Voice-V2 app exists excluding band-sample-* apps, use it. + var nonSample []voiceAppSummary + for _, v := range res.voice { + if strings.HasPrefix(v.name, "band-sample-") { + continue + } + if v.name == sampleAppName { + continue + } + nonSample = append(nonSample, v) + } + if len(nonSample) == 1 { + return nonSample[0].id, nonSample[0].name, nil + } + + // Try reading the number's sippeer origination settings if we have site/peer IDs. + if numInfo.SiteID != "" && numInfo.SipPeerID != "" { + if appID, err := sippeerRoutedVoiceApp(ctx, client, acctID, numInfo.SiteID, numInfo.SipPeerID); err == nil && appID != "" { + name := "" + for _, v := range res.voice { + if v.id == appID { + name = v.name + break + } + } + return appID, name, nil + } else if err != nil { + res.notes = append(res.notes, statusNote("GET /sippeers/.../origination/settings", err)) + } + } else { + res.notes = append(res.notes, "GET /sippeers/.../origination/settings skipped (no siteId/sippeerId from /tns)") + } + + // Try enumerating sippeers and extracting a single routed Voice-V2 app ID. + if appID, err := discoverSingleRoutedVoiceApp(ctx, client, acctID); err == nil && appID != "" { + name := "" + for _, v := range res.voice { + if v.id == appID { + name = v.name + break + } + } + return appID, name, nil + } else if err != nil { + res.notes = append(res.notes, statusNote("discover routed app via /sites + /sippeers", err)) + } + + return "", "", res.errorf("could not resolve inbound Voice-V2 application for %s", numInfo.PhoneNumber) +} + +type voiceAppSummary struct { + id string + name string +} + +func sippeerRoutedVoiceApp(ctx context.Context, client api.Requester, acctID, siteID, peerID string) (string, error) { + var result interface{} + path := fmt.Sprintf("/accounts/%s/sites/%s/sippeers/%s/products/origination/settings", acctID, url.PathEscape(siteID), url.PathEscape(peerID)) + if err := client.Get(ctx, path, &result); err != nil { + return "", err + } + // The XML decoder produces nested maps; search broadly for the ID. + appID := extractStringField(result, "HttpVoiceV2AppId", "httpVoiceV2AppId", "HttpVoiceV2AppID") + return appID, nil +} + +func discoverSingleRoutedVoiceApp(ctx context.Context, client api.Requester, acctID string) (string, error) { + var sites interface{} + if err := client.Get(ctx, fmt.Sprintf("/accounts/%s/sites", acctID), &sites); err != nil { + return "", err + } + siteIDs := extractAllStringFields(sites, "Id", "SiteId", "siteId") + seen := map[string]struct{}{} + for _, sid := range siteIDs { + var peers interface{} + if err := client.Get(ctx, fmt.Sprintf("/accounts/%s/sites/%s/sippeers", acctID, url.PathEscape(sid)), &peers); err != nil { + continue + } + peerIDs := extractAllStringFields(peers, "Id", "SipPeerId", "sipPeerId", "SippeerId") + for _, pid := range peerIDs { + appID, err := sippeerRoutedVoiceApp(ctx, client, acctID, sid, pid) + if err != nil || appID == "" { + continue + } + seen[appID] = struct{}{} + if len(seen) > 1 { + return "", fmt.Errorf("multiple routed Voice-V2 apps detected across locations") + } + } + } + for id := range seen { + return id, nil + } + return "", fmt.Errorf("no routed Voice-V2 app detected from location settings") +} + +func extractAllStringFields(resp interface{}, keys ...string) []string { + data, _ := json.Marshal(resp) + var m map[string]interface{} + if json.Unmarshal(data, &m) != nil { + return nil + } + var out []string + var walk func(v interface{}) + walk = func(v interface{}) { + switch x := v.(type) { + case map[string]interface{}: + for k, vv := range x { + for _, want := range keys { + if k == want { + if s, ok := vv.(string); ok && s != "" { + out = append(out, s) + } + } + } + walk(vv) + } + case []interface{}: + for _, item := range x { + walk(item) + } + } + } + walk(m) + uniq := map[string]struct{}{} + var dedup []string + for _, s := range out { + if _, ok := uniq[s]; ok { + continue + } + uniq[s] = struct{}{} + dedup = append(dedup, s) + } + return dedup +} + +func findAllVoiceApps(resp interface{}) []voiceAppSummary { + data, _ := json.Marshal(resp) + var list []map[string]interface{} + if json.Unmarshal(data, &list) == nil { + var out []voiceAppSummary + for _, item := range list { + svc, _ := item["ServiceType"].(string) + if svc != "" && svc != "Voice-V2" { + continue + } + id, _ := item["ApplicationId"].(string) + if id == "" { + id, _ = item["applicationId"].(string) + } + if id == "" { + continue + } + name, _ := item["AppName"].(string) + if name == "" { + name, _ = item["appName"].(string) + } + out = append(out, voiceAppSummary{id: id, name: name}) + } + return out + } + return nil +} + +// ensureVoiceAppOnNumberLocationBestEffort assigns the voice application to the +// phone number's location (SIP peer) and enables HTTP origination on that +// location. Some credentials (notably Bandwidth Build OAuth creds) can't read +// the fields needed for this wiring; when the assignment can't be performed, +// we warn and continue so the sample can still be started. +func ensureVoiceAppOnNumberLocationBestEffort(ctx context.Context, client api.Requester, acctID, phoneNumber, siteID, peerID, appID, appName string) { + if siteID == "" || peerID == "" { + var err error + siteID, peerID, err = numberLocation(ctx, client, phoneNumber) + if err != nil { + ui.Warnf("Could not auto-assign voice routing for %s (app %s): %v", phoneNumber, appName, err) + ui.Warnf("To enable inbound calls, assign application %s to the number's location in the Bandwidth Dashboard (Applications → %s → Associated Locations).", appName, appName) + return + } + } + + body := api.XMLBody{ + RootElement: "SipPeerOriginationSettings", + Data: map[string]interface{}{ + "VoiceProtocol": "HTTP", + "HttpSettings": map[string]interface{}{ + "HttpVoiceV2AppId": appID, + }, + }, + } + path := fmt.Sprintf("/accounts/%s/sites/%s/sippeers/%s/products/origination/settings", + acctID, url.PathEscape(siteID), url.PathEscape(peerID)) + + spin := ui.NewSpinner("Assigning voice application to location...") + spin.Start() + var result interface{} + if err := client.Post(ctx, path, body, &result); err != nil { + spin.Stop() + ui.Warnf("Could not auto-assign voice routing for %s (app %s): %v", phoneNumber, appName, err) + ui.Warnf("To enable inbound calls, assign application %s to the number's location in the Bandwidth Dashboard (Applications → %s → Associated Locations).", appName, appName) + return + } + spin.Stop() + ui.Successf("Voice routing set on location: %s (site %s)", ui.ID(peerID), ui.ID(siteID)) +} + +func numberLocation(ctx context.Context, client api.Requester, phoneNumber string) (siteID string, peerID string, err error) { + var result interface{} + if err := client.Get(ctx, fmt.Sprintf("/tns/%s/tndetails", url.PathEscape(phoneNumber)), &result); err != nil { + return "", "", fmt.Errorf("getting number details for %s: %w", phoneNumber, err) + } + + siteID = extractStringField(result, "SiteId", "SubAccountId", "SubaccountId", "siteId", "subAccountId", "subaccountId") + peerID = extractStringField(result, "SipPeerId", "SippeerId", "SipPeerID", "sipPeerId", "sippeersId", "LocationId", "locationId") + if siteID == "" || peerID == "" { + return "", "", fmt.Errorf("could not determine site/location for %s (siteId=%q, sippeerId=%q)", phoneNumber, siteID, peerID) + } + return siteID, peerID, nil +} + // firstPhoneNumber returns the first in-service TN on the account. // The Dashboard client already scopes requests to the account, so the path is // just /tns (same as `band number list` uses internally). -func firstPhoneNumber(ctx context.Context, client *api.Client, acctID string) (string, error) { +type sampleNumberInfo struct { + PhoneNumber string + SiteID string + SipPeerID string + VoiceAppID string +} + +func firstPhoneNumber(ctx context.Context, client *api.Client, acctID string) (sampleNumberInfo, error) { var resp interface{} if err := client.Get(ctx, "/tns?size=1&page=1", &resp); err != nil { - return "", fmt.Errorf("listing phone numbers: %w", err) + return sampleNumberInfo{}, fmt.Errorf("listing phone numbers: %w", err) } tn := extractStringField(resp, "FullNumber", "TelephoneNumber", "telephoneNumber") if tn == "" { - return "", fmt.Errorf("no phone numbers found on account %s", acctID) + return sampleNumberInfo{}, fmt.Errorf("no phone numbers found on account %s", acctID) } if !strings.HasPrefix(tn, "+") { tn = "+" + tn } - return tn, nil + // Best-effort: some credential sets can list numbers but cannot access + // /tndetails to learn the site/location. When present, re-use the list + // response to avoid that extra permission gate. + siteID := extractStringField(resp, "SiteId", "SubAccountId", "SubaccountId", "siteId", "subAccountId", "subaccountId") + peerID := extractStringField(resp, "SipPeerId", "SippeerId", "SipPeerID", "sipPeerId", "sippeersId", "LocationId", "locationId") + voiceAppID := extractStringField(resp, "ApplicationId", "VoiceApplicationId", "voiceApplicationId", "applicationId") + return sampleNumberInfo{PhoneNumber: tn, SiteID: siteID, SipPeerID: peerID, VoiceAppID: voiceAppID}, nil } -// writeEnvFile writes env vars in `export KEY="VALUE"` format. +// writeEnvFile writes env vars in .env format. func writeEnvFile(path string, vars map[string]string) error { f, err := os.Create(path) if err != nil { @@ -446,7 +1152,7 @@ func writeEnvFile(path string, vars map[string]string) error { } defer f.Close() for k, v := range vars { - fmt.Fprintf(f, "export %s=%q\n", k, v) + fmt.Fprintf(f, "%s=%s\n", k, strconv.Quote(v)) } return nil } diff --git a/cmd/sample/run_test.go b/cmd/sample/run_test.go index e76df94..102e408 100644 --- a/cmd/sample/run_test.go +++ b/cmd/sample/run_test.go @@ -1,8 +1,14 @@ package sample import ( + "context" + "encoding/json" + "os" "strings" "testing" + + "github.com/Bandwidth/cli/internal/api" + "github.com/Bandwidth/cli/internal/testutil" ) func TestCollectExtraEnvReadsEnvironment(t *testing.T) { @@ -61,3 +67,252 @@ func TestCollectExtraEnvNoRequirements(t *testing.T) { t.Errorf("got %v, want empty map", got) } } + +func TestCollectExtraEnvReportsMissingForVoiceBridge(t *testing.T) { + t.Setenv("USER_NUMBER", "") + + _, err := collectExtraEnv("voice-bridge", "python", catalog["voice-bridge"]) + if err == nil { + t.Fatal("expected an error when USER_NUMBER is unset, got nil") + } + msg := err.Error() + if !strings.Contains(msg, "USER_NUMBER") { + t.Errorf("error should name the missing variable, got: %s", msg) + } + if !strings.Contains(msg, "USER_NUMBER=...") { + t.Errorf("hint should show the missing variable, got: %s", msg) + } +} + +type failingRequester struct { + getErr error + postErr error +} + +func (f failingRequester) Get(context.Context, string, interface{}) error { return f.getErr } +func (f failingRequester) Post(context.Context, string, interface{}, interface{}) error { + return f.postErr +} +func (f failingRequester) Put(context.Context, string, interface{}, interface{}) error { return nil } +func (f failingRequester) Patch(context.Context, string, interface{}, interface{}) error { + return nil +} +func (f failingRequester) Delete(context.Context, string, interface{}) error { return nil } +func (f failingRequester) GetRaw(context.Context, string) ([]byte, error) { return nil, nil } +func (f failingRequester) PutRaw(context.Context, string, []byte, string) error { + return nil +} + +func TestEnsureVoiceAppOnNumberLocation_403WarnsAndContinues(t *testing.T) { + req := failingRequester{getErr: &api.APIError{StatusCode: 403, Body: "Forbidden"}} + + stderr := testutil.CaptureStderr(t, func() { + ensureVoiceAppOnNumberLocationBestEffort(context.Background(), req, "acct", "+19404060874", "", "", "app-id", "band-sample-voice-record") + }) + + if !strings.Contains(stderr, "Could not auto-assign voice routing") { + t.Fatalf("expected warning, got: %s", stderr) + } + if !strings.Contains(stderr, "band-sample-voice-record") { + t.Fatalf("expected app name in warning, got: %s", stderr) + } + if !strings.Contains(stderr, "Bandwidth Dashboard") { + t.Fatalf("expected manual remediation hint, got: %s", stderr) + } +} + +type recordingRequester struct { + getByPath map[string]interface{} + putCalls []struct { + path string + body interface{} + } +} + +func (r *recordingRequester) Get(_ context.Context, path string, result interface{}) error { + raw, ok := r.getByPath[path] + if !ok { + return &api.APIError{StatusCode: 404, Body: "not found"} + } + b, _ := json.Marshal(raw) + return json.Unmarshal(b, result) +} +func (r *recordingRequester) Post(context.Context, string, interface{}, interface{}) error { + return nil +} +func (r *recordingRequester) Put(_ context.Context, path string, body, _ interface{}) error { + r.putCalls = append(r.putCalls, struct { + path string + body interface{} + }{path: path, body: body}) + return nil +} +func (r *recordingRequester) Patch(context.Context, string, interface{}, interface{}) error { + return nil +} +func (r *recordingRequester) Delete(context.Context, string, interface{}) error { return nil } +func (r *recordingRequester) GetRaw(context.Context, string) ([]byte, error) { return nil, nil } +func (r *recordingRequester) PutRaw(context.Context, string, []byte, string) error { return nil } + +func TestResolveInboundVoiceApp_FallsBackToDefaultHTTPVoice(t *testing.T) { + client := &recordingRequester{ + getByPath: map[string]interface{}{ + "/accounts/acct/applications": []interface{}{ + map[string]interface{}{ + "ApplicationId": "app-default", + "ServiceType": "Voice-V2", + "AppName": "default-http-voice", + }, + }, + "/accounts/acct/applications/app-default": map[string]interface{}{ + "ApplicationResponse": map[string]interface{}{ + "Application": map[string]interface{}{ + "ApplicationId": "app-default", + "ServiceType": "Voice-V2", + "AppName": "default-http-voice", + "CallInitiatedCallbackUrl": "https://orig.example/cb", + "CallStatusCallbackUrl": "https://orig.example/status", + }, + }, + }, + }, + } + + id, name, err := resolveInboundVoiceApp(context.Background(), client, "acct", sampleNumberInfo{PhoneNumber: "+10000000000"}, "band-sample-voice-record", "") + if err != nil { + t.Fatalf("resolveInboundVoiceApp: %v", err) + } + if id != "app-default" { + t.Fatalf("id=%q want %q", id, "app-default") + } + if name != "default-http-voice" { + t.Fatalf("name=%q want %q", name, "default-http-voice") + } +} + +func TestResolveInboundVoiceApp_SingleNonSampleVoiceAppWins(t *testing.T) { + client := &recordingRequester{ + getByPath: map[string]interface{}{ + "/accounts/acct/applications": []interface{}{ + map[string]interface{}{ + "ApplicationId": "app-sample", + "ServiceType": "Voice-V2", + "AppName": "band-sample-voice-record", + }, + map[string]interface{}{ + "ApplicationId": "app-only", + "ServiceType": "Voice-V2", + "AppName": "some-voice-app", + }, + }, + "/accounts/acct/applications/app-only": map[string]interface{}{ + "ApplicationResponse": map[string]interface{}{ + "Application": map[string]interface{}{ + "ApplicationId": "app-only", + "ServiceType": "Voice-V2", + "AppName": "some-voice-app", + "CallInitiatedCallbackUrl": "https://orig.example/cb", + }, + }, + }, + }, + } + + id, name, err := resolveInboundVoiceApp(context.Background(), client, "acct", sampleNumberInfo{PhoneNumber: "+10000000000"}, "band-sample-voice-record", "") + if err != nil { + t.Fatalf("resolveInboundVoiceApp: %v", err) + } + if id != "app-only" { + t.Fatalf("id=%q want %q", id, "app-only") + } + if name != "some-voice-app" { + t.Fatalf("name=%q want %q", name, "some-voice-app") + } +} + +func TestResolveInboundVoiceApp_FailureHasDiagnostics(t *testing.T) { + client := &recordingRequester{ + getByPath: map[string]interface{}{ + "/accounts/acct/applications": []interface{}{ + map[string]interface{}{ + "ApplicationId": "app-one", + "ServiceType": "Voice-V2", + "AppName": "voice-one", + }, + map[string]interface{}{ + "ApplicationId": "app-two", + "ServiceType": "Voice-V2", + "AppName": "voice-two", + }, + }, + }, + } + + _, err := func() (string, error) { + _, _, err := resolveInboundVoiceApp(context.Background(), client, "acct", sampleNumberInfo{PhoneNumber: "+10000000000"}, "band-sample-voice-record", "") + return "", err + }() + if err == nil { + t.Fatal("expected error") + } + msg := err.Error() + if !strings.Contains(msg, "Voice-V2 applications found") { + t.Fatalf("expected diagnostics listing apps, got: %s", msg) + } + if !strings.Contains(msg, "voice-one") || !strings.Contains(msg, "app-one") { + t.Fatalf("expected app list in diagnostics, got: %s", msg) + } + if !strings.Contains(msg, "Lookups attempted") { + t.Fatalf("expected lookup notes in diagnostics, got: %s", msg) + } + if !strings.Contains(msg, "--voice-app") || !strings.Contains(msg, "BW_SAMPLE_VOICE_APP_ID") { + t.Fatalf("expected override hint in diagnostics, got: %s", msg) + } +} + +func TestOverrideVoiceAppCallbacks_RestoresAndCleansState(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + + client := &recordingRequester{ + getByPath: map[string]interface{}{ + "/accounts/acct/applications/app-default": map[string]interface{}{ + "ApplicationResponse": map[string]interface{}{ + "Application": map[string]interface{}{ + "ApplicationId": "app-default", + "ServiceType": "Voice-V2", + "AppName": "default-http-voice", + "CallInitiatedCallbackUrl": "https://orig.example/cb", + "CallStatusCallbackUrl": "https://orig.example/status", + }, + }, + }, + }, + } + + statePath, err := voiceAppOverrideStatePath("acct", "app-default") + if err != nil { + t.Fatalf("voiceAppOverrideStatePath: %v", err) + } + + restore, err := overrideVoiceAppCallbacks(context.Background(), client, "acct", "app-default", "default-http-voice", "https://ngrok.example/callbacks/inbound/voice", "", statePath) + if err != nil { + t.Fatalf("overrideVoiceAppCallbacks: %v", err) + } + if _, err := os.Stat(statePath); err != nil { + t.Fatalf("expected state file to exist: %v", err) + } + if len(client.putCalls) != 1 { + t.Fatalf("expected 1 Put call, got %d", len(client.putCalls)) + } + + if err := restore(context.Background()); err != nil { + t.Fatalf("restore: %v", err) + } + if len(client.putCalls) != 2 { + t.Fatalf("expected 2 Put calls after restore, got %d", len(client.putCalls)) + } + if _, err := os.Stat(statePath); err == nil { + t.Fatalf("expected state file to be removed") + } +} diff --git a/cmd/sample/sample.go b/cmd/sample/sample.go index 0e483cb..3d36618 100644 --- a/cmd/sample/sample.go +++ b/cmd/sample/sample.go @@ -14,7 +14,9 @@ wired from your active band profile. Examples: band sample list band sample run live-assistant --language python - band sample run live-assistant --language python --call-to +19195550101`, + band sample run live-assistant --language python --call-to +19195550101 + band sample run voice-record --language python --call-to +19195550101 + USER_NUMBER=+19195550100 band sample run voice-bridge --language python --call-to +19195550101`, } func init() { diff --git a/go.mod b/go.mod index 755af6b..d12dcea 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/Bandwidth/cli -go 1.27.3 +go 1.27.4 require ( github.com/briandowns/spinner v1.23.2