Files
openchamber-android-native/cmd/ocprobe/main.go
T
blumia 2fb4a8ea79 feat: context usage ring and tool image previews
- the composer shows a context ring and percentage from the last
  token-bearing assistant message, toned at 75% and 90%; tapping opens a
  sheet with the model, used tokens, limits, output reserve and turn cost
- images a tool call names (read attachments as data URLs, input paths,
  and image paths in output text) get a link under the tool row; tapping
  previews it from the data URL or /api/fs/raw, allowing paths outside
  the workspace
- directory-scoped requests now send x-opencode-directory-encoding: uri,
  which scoped routes such as /api/fs/raw need to decode the header
- ocprobe gains a raw file command for checking previews

Bump version to 0.2.2 (build 16).
2026-11-18 02:15:11 +08:00

223 lines
5.9 KiB
Go

// Command ocprobe exercises the OpenChamber API from a terminal. It is the
// M0 probe: no UI, just the same client the app uses.
//
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 health
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 -password secret sessions
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 messages ses_123
// go run ./cmd/ocprobe -url http://127.0.0.1:3000 events -seconds 20
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/openchamber/openchamber-native/internal/ocapi"
)
func main() {
var (
base = flag.String("url", "http://127.0.0.1:3000", "OpenChamber server URL")
password = flag.String("password", "", "UI password (empty for a passwordless server)")
proxy = flag.String("proxy", "", "optional HTTP(S) or SOCKS5 proxy URL")
insecure = flag.Bool("insecure", false, "skip TLS verification")
fp = flag.String("fingerprint", "", "pin the server certificate (SHA-256 hex)")
timeout = flag.Duration("timeout", 20*time.Second, "request timeout")
limit = flag.Int("limit", 20, "page size for sessions/messages")
seconds = flag.Int("seconds", 10, "how long to watch events")
types = flag.String("types", "", "comma-separated event types for events")
)
flag.Parse()
if flag.NArg() == 0 {
usage()
}
cmd := flag.Arg(0)
client, err := ocapi.New(*base, ocapi.Options{
Proxy: *proxy,
InsecureSkipVerify: *insecure,
CertFingerprint: *fp,
Timeout: *timeout,
})
if err != nil {
fail(err)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Every command except health authenticates first.
if cmd != "health" {
if err := authenticate(ctx, client, *password); err != nil {
fail(err)
}
}
switch cmd {
case "health":
h, err := client.Health(ctx)
if err != nil {
fail(err)
}
printJSON(h)
fmt.Fprintf(os.Stderr, "server %s, openchamber %s, opencode ready=%v\n", client.BaseURL(), h.OpenChamberVersion, h.IsOpenCodeReady)
case "status":
st, err := client.SessionStatus(ctx)
if err != nil {
fail(err)
}
printJSON(st)
case "sessions":
page, err := client.ListSessions(ctx, ocapi.ListSessionsOptions{Limit: *limit, Order: "desc"})
if err != nil {
fail(err)
}
printJSON(page)
fmt.Fprintf(os.Stderr, "%d sessions, next=%q\n", len(page.Data), page.Cursor.Next)
case "messages":
if flag.NArg() < 2 {
fail(fmt.Errorf("messages needs a session id"))
}
page, err := client.ListMessages(ctx, flag.Arg(1), ocapi.ListMessagesOptions{Limit: *limit, Order: "desc"})
if err != nil {
fail(err)
}
printJSON(page)
fmt.Fprintf(os.Stderr, "%d messages, next=%q\n", len(page.Data), page.Cursor.Next)
case "raw":
if flag.NArg() < 2 {
fail(fmt.Errorf("raw needs an absolute file path, and optionally a directory"))
}
dir := ""
if flag.NArg() > 2 {
dir = flag.Arg(2)
}
data, mime, err := client.RawFile(ctx, flag.Arg(1), dir)
if err != nil {
fail(err)
}
fmt.Fprintf(os.Stderr, "%d bytes, %s\n", len(data), mime)
case "prompt":
if flag.NArg() < 3 {
fail(fmt.Errorf("prompt needs a session id and text"))
}
if err := client.Prompt(ctx, flag.Arg(1), ocapi.PromptOptions{Text: strings.Join(flag.Args()[2:], " ")}); err != nil {
fail(err)
}
fmt.Fprintln(os.Stderr, "prompt accepted; watch `events` for the reply")
case "interrupt":
if flag.NArg() < 2 {
fail(fmt.Errorf("interrupt needs a session id"))
}
ok, err := client.Interrupt(ctx, flag.Arg(1), "")
if err != nil {
fail(err)
}
fmt.Fprintf(os.Stderr, "interrupted=%v\n", ok)
case "events":
var list []string
if strings.TrimSpace(*types) != "" {
for _, t := range strings.Split(*types, ",") {
if t = strings.TrimSpace(t); t != "" {
list = append(list, t)
}
}
}
ectx, cancel := context.WithTimeout(ctx, time.Duration(*seconds)*time.Second)
defer cancel()
fmt.Fprintf(os.Stderr, "watching events for %ds…\n", *seconds)
err := client.StreamEvents(ectx, list, func(ev ocapi.Event) error {
fmt.Printf("%s %s %s\n", time.UnixMilli(ev.Created).Format("15:04:05"), ev.Type, string(ev.Data))
return nil
})
if err != nil && ectx.Err() == nil {
fail(err)
}
default:
usage()
}
}
func authenticate(ctx context.Context, c *ocapi.Client, password string) error {
st, err := c.SessionStatus(ctx)
if err == nil {
if !st.Authenticated {
return fmt.Errorf("server did not accept the request")
}
return nil
}
if !ocapi.IsUnauthorized(err) {
return err
}
if strings.TrimSpace(password) == "" {
return fmt.Errorf("this server requires a password; pass -password")
}
res, err := c.Login(ctx, ocapi.LoginRequest{
Password: password,
DedupeKey: probeDedupeKey(),
ClientLabel: "OpenChamber Probe",
ClientKind: "desktop",
DevicePlatform: "cli",
})
if err != nil {
if wait, ok := ocapi.IsRateLimited(err); ok {
return fmt.Errorf("%w (retry after %s)", err, wait)
}
return err
}
if res.ClientToken == "" {
return fmt.Errorf("login returned no client token")
}
return nil
}
func probeDedupeKey() string {
host, err := os.Hostname()
if err != nil || host == "" {
return "ocprobe"
}
return "ocprobe-" + host
}
func printJSON(v any) {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(v)
}
func usage() {
fmt.Fprint(os.Stderr, `usage: ocprobe [flags] <command>
commands:
health server health (no auth)
status probe /auth/session
sessions list sessions (newest first)
messages <session-id> latest messages of a session
raw <path> [directory] fetch a file the server can read
prompt <session-id> <text> send a message
interrupt <session-id> stop the running turn
events watch the event stream
`)
flag.PrintDefaults()
os.Exit(2)
}
func fail(err error) {
fmt.Fprintln(os.Stderr, "ocprobe:", err)
os.Exit(1)
}