diff --git a/README.md b/README.md index a05fe62..a102e51 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,14 @@ saved page.md · 293 KB · ~75,000 tokens · 200 · en.wikipedia.org The outline gives each of a Markdown page's headings after the line it starts on, so `sed -n 618,700p page.md` reads one section. `-o -` is stdout, and `-q` leaves status lines like these out of stderr. +`--max-tokens N` prints a page in parts of about N tokens, at four characters a token, each cut at a line's end. stderr says which part it is and gives the command for the next: + +``` +part 1 of 13 (tokens 0–6,000 of ~75,000). next: string fetch https://en.wikipedia.org/wiki/List_of_countries --max-tokens 6000 --offset 6000 +``` + +The parts after the first come from a local copy that the first part saves for 15 minutes, under `$XDG_CACHE_HOME/string/fetch` or `~/.cache/string/fetch`. They send no request and cost nothing, keyless allowance included. + A bare domain works too: `string example.com` fetches `https://example.com`. When `fetch`, `request` or `sitemap submit` gets a URL with no scheme, it uses `https://` and says so on stderr. **Every API field is a flag of the same name.** A field from the [API reference](https://docs.usestring.ai/api-reference/fetch) works on the command line as written: `executeJS` is `--executeJS`, and `countryCode` is `--countryCode DE`. A boolean flag alone is true, and `=false` turns it off (`--solveCaptcha=false`). An object or array field takes JSON, or `@` and a file path (`--jsonSchema @./schema.json`). `string fetch --help`, `string search --help` and `string sitemap --help` list each command's fields. Every flag of more than one word also takes its kebab-case and snake_case spellings, so `--main-content-only` and `--main_content_only` are `--mainContentOnly`, and `--envFile` is `--env-file`. A near miss of a flag, such as `--mainContentOnyl`, gets the right name back, and so does a near miss of a command, or a word other tools use for one: `string scrape URL` answers `Did you mean fetch?` with `string fetch URL` as the next step, and exits 2 without running it. diff --git a/cmd/string/help.go b/cmd/string/help.go index abff116..237cdf5 100644 --- a/cmd/string/help.go +++ b/cmd/string/help.go @@ -159,8 +159,11 @@ var commandDocs = map[string]commandDoc{ " only JSON carries: jsonSchema, screenshot, actions, captureXHR,", " captureIframes or captureCookies", }, exitsOfARequest...), - cost: "1 credit, 5 with --executeJS. Without a key: 50 requests and 100 credits a day\nper IP address, with --format and --executeJS only.", - flags: outputFlags, + cost: "1 credit, 5 with --executeJS. Without a key: 50 requests and 100 credits a day\nper IP address, with --format and --executeJS only. Parts after the first, with\n--offset, come from a local copy for 15 minutes and cost nothing.", + flags: ` --max-tokens N print about N tokens of the page, cut at a line's end; + stderr says which part it is and the next part's command + --offset N start the part N tokens into the page +` + outputFlags, fields: ` --format json|markdown|raw the response format --markdownMode readable|full how much of the page the Markdown keeps --mainContentOnly drop navigation, headers and footers @@ -513,6 +516,8 @@ Learn more: https://github.com/usestring/cli#errors-and-exit-codes nobody approves a sign-in and nothing updates itself XDG_CONFIG_HOME where the saved key lives: $XDG_CONFIG_HOME/string, or ~/.config/string without it + XDG_CACHE_HOME where fetch keeps a page read in parts for 15 minutes: + $XDG_CACHE_HOME/string/fetch, or ~/.cache/string/fetch CLAUDE_CONFIG_DIR where init finds Claude Code's settings CODEX_HOME where init finds Codex's settings @@ -550,6 +555,9 @@ its runner cuts the output. and host, and a Markdown page's outline. -o - is stdout -q, --quiet no status lines on stderr: no notes, receipts or wait lines. Errors and the keyless allowance stay + --max-tokens N fetch prints about N tokens, and stderr says which part + --offset N it is and the next part's command; parts after the + first come from a local copy, at no cost --input FILE more request fields, from a JSON object in FILE or - for stdin; flags win over it --errors json errors as JSON, as --json gives them, with stdout as it diff --git a/cmd/string/page_size_test.go b/cmd/string/page_size_test.go index 71314d1..f0603f2 100644 --- a/cmd/string/page_size_test.go +++ b/cmd/string/page_size_test.go @@ -36,7 +36,7 @@ func TestALargePageSaysItsSizeFirst(t *testing.T) { page := strings.Repeat("A line of the page that is long enough.\n", 512) base, _ := fetchAPI(t, page) note := func(cut, command string) string { - return "note: example.com returned 20,480 bytes (~5,120 tokens). " + cut + "\nSave it and read parts: " + command + "\n" + return "note: example.com returned 20,480 bytes (~5,120 tokens). " + cut + "\nSave it and read parts: " + command + " -o page.md\nOr page it: " + command + " --max-tokens 6000\n" } for _, c := range []struct { about string @@ -44,9 +44,9 @@ func TestALargePageSaysItsSizeFirst(t *testing.T) { list []string said string }{ - {"Claude Code", execCtx{agent: "claude-code"}, []string{"fetch", "https://example.com"}, note("Claude Code keeps only the first 2 KB of output this long.", "string fetch https://example.com -o page.md")}, - {"an agent string doesn't know", execCtx{agent: "acme-agent"}, []string{"https://example.com", "--mainContentOnly"}, note("Most agents cut output this long.", "string fetch https://example.com --mainContentOnly -o page.md")}, - {"a pipe", execCtx{stdinTTY: true, stderrTTY: true}, []string{"fetch", "https://example.com"}, note("Most agents cut output this long.", "string fetch https://example.com -o page.md")}, + {"Claude Code", execCtx{agent: "claude-code"}, []string{"fetch", "https://example.com"}, note("Claude Code keeps only the first 2 KB of output this long.", "string fetch https://example.com")}, + {"an agent string doesn't know", execCtx{agent: "acme-agent"}, []string{"https://example.com", "--mainContentOnly"}, note("Most agents cut output this long.", "string fetch https://example.com --mainContentOnly")}, + {"a pipe", execCtx{stdinTTY: true, stderrTTY: true}, []string{"fetch", "https://example.com"}, note("Most agents cut output this long.", "string fetch https://example.com")}, {"a person at a terminal", execCtx{stdinTTY: true, stdoutTTY: true, stderrTTY: true}, []string{"fetch", "https://example.com"}, ""}, {"-q", execCtx{agent: "claude-code"}, []string{"fetch", "https://example.com", "-q"}, ""}, } { diff --git a/cmd/string/pages.go b/cmd/string/pages.go new file mode 100644 index 0000000..f1b5dd0 --- /dev/null +++ b/cmd/string/pages.go @@ -0,0 +1,125 @@ +package main + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +// copyLife is how long a page's local copy serves the pages after the first, +// so reading a long page in parts spends one fetch. +const copyLife = 15 * time.Minute + +// page is the part of text that --max-tokens maxTokens and --offset offset +// ask for, both in tokens of four characters. Every part but the last ends on +// a whole token, so the next part starts exactly at its offset, and parts read +// one after another give the page back with nothing lost or repeated. A part +// ends at a line's end that falls on a whole token, when its second half has +// one; else at its last line's end, taking up to three characters of the next +// line; and inside a line longer than the part, at the part's size. next is +// the --offset of the part after it, or 0 for the last part. +func page(text string, maxTokens, offset int) (part string, start, end, next int) { + start = min(offset*4, len(text)) + end = min(start+maxTokens*4, len(text)) + if end < len(text) { + window := text[start:end] + if last := strings.LastIndexByte(window, '\n'); last >= 0 { + end = min((start+last+1+3)/4*4, len(text)) + for p := last; p >= len(window)/2; p = strings.LastIndexByte(window[:p], '\n') { + if (start+p+1)%4 == 0 { + end = start + p + 1 + break + } + } + } + next = end / 4 + } + return text[start:end], start, end, next +} + +// pageFooter is what stderr says after a part: which part it is, the tokens it +// holds of the whole, and the command for the next part. +func pageFooter(line []string, total, maxTokens, start, end, next int, fromCopy bool) string { + totalTokens := tokens(total) + parts := max(1, (totalTokens+maxTokens-1)/maxTokens) + said := fmt.Sprintf("part %d of %d (tokens %s–%s of ~%s)", min(start/4/maxTokens+1, parts), parts, thousands(int64(start/4)), thousands(int64(tokens(end))), thousands(int64(totalTokens))) + if fromCopy { + said += ", from the local copy, no credit used" + } + if next > 0 { + said += ". next: " + commandLine(withOffset(line, next)) + } + return said + "\n" +} + +// withOffset is line with its --offset, in any spelling, set to offset. +func withOffset(line []string, offset int) []string { + out := make([]string, 0, len(line)+2) + for i := 0; i < len(line); i++ { + name, _, inline := strings.Cut(line[i], "=") + if spelled, ok := flagNamed(name, []string{"--offset"}); ok && spelled == "--offset" { + if !inline { + i++ + } + continue + } + out = append(out, line[i]) + } + return append(out, "--offset", strconv.Itoa(offset)) +} + +// copyPath is where the local copy of a fetch with body lives: the cache +// directory, under a name made from the request. +func copyPath(env func(string) (string, bool), body map[string]any) (string, bool) { + dir, ok := env("XDG_CACHE_HOME") + if !ok || !filepath.IsAbs(dir) { + home, err := homeDir(env) + if err != nil { + return "", false + } + dir = filepath.Join(home, ".cache") + } + request, _ := json.Marshal(body) + sum := sha256.Sum256(request) + return filepath.Join(dir, "string", "fetch", hex.EncodeToString(sum[:16])+".page"), true +} + +// readCopy is the local copy of the fetch with body, when one was saved in +// the last copyLife. +func readCopy(rt runtime, body map[string]any) ([]byte, bool) { + path, ok := copyPath(rt.env, body) + if !ok { + return nil, false + } + info, err := os.Stat(path) + if err != nil || rt.clock().Sub(info.ModTime()) > copyLife { + return nil, false + } + data, err := os.ReadFile(path) + return data, err == nil +} + +// saveCopy keeps data as the local copy of the fetch with body, readable only +// by its owner, and clears copies past their life. It fails silently. +func saveCopy(rt runtime, body map[string]any, data []byte) { + path, ok := copyPath(rt.env, body) + if !ok || os.MkdirAll(filepath.Dir(path), 0o700) != nil { + return + } + if old, err := os.ReadDir(filepath.Dir(path)); err == nil { + for _, entry := range old { + if info, err := entry.Info(); err == nil && rt.clock().Sub(info.ModTime()) > copyLife { + os.Remove(filepath.Join(filepath.Dir(path), entry.Name())) + } + } + } + if os.WriteFile(path, data, 0o600) == nil { + os.Chtimes(path, rt.clock(), rt.clock()) + } +} diff --git a/cmd/string/pages_test.go b/cmd/string/pages_test.go new file mode 100644 index 0000000..9c8232d --- /dev/null +++ b/cmd/string/pages_test.go @@ -0,0 +1,130 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + goruntime "runtime" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" +) + +// Read part after part, a page comes back whole, with nothing lost or +// repeated, and each part holds about as many tokens as asked for. Most parts +// end at a line's end; a line longer than a part goes on in the next part. +func TestPagesCoverThePageWhole(t *testing.T) { + var lines []string + for i := range 300 { + lines = append(lines, fmt.Sprintf("line %d of the page, %s", i, strings.Repeat("words ", i%9))) + } + text := strings.Join(lines, "\n") + "\n" + short := "a\nbc\n" + strings.Repeat("abcdefghij", 101) + for _, c := range []struct { + text string + maxTokens int + }{{text, 1}, {text, 7}, {text, 50}, {text, 333}, {text, 100000}, {short, 1}, {short, 10}, {strings.Repeat("abcdefghij", 101), 10}} { + var whole strings.Builder + atLineEnd, parts := 0, 0 + for offset := 0; ; parts++ { + if parts > len(c.text) { + t.Fatalf("--max-tokens %d: the parts never end", c.maxTokens) + } + part, start, end, next := page(c.text, c.maxTokens, offset) + if start != whole.Len() || len(part) > c.maxTokens*4+3 { + t.Fatalf("--max-tokens %d: a part of %d characters starts at %d, after %d", c.maxTokens, len(part), start, whole.Len()) + } + whole.WriteString(part) + if strings.HasSuffix(part, "\n") { + atLineEnd++ + } + if next == 0 { + if end != len(c.text) { + t.Errorf("--max-tokens %d: the last part ends at %d of %d", c.maxTokens, end, len(c.text)) + } + break + } + offset = next + } + if whole.String() != c.text { + t.Errorf("--max-tokens %d: the parts together are %d characters, want the page's %d", c.maxTokens, whole.Len(), len(c.text)) + } + if c.text == text && c.maxTokens == 50 && atLineEnd*2 < parts { + t.Errorf("--max-tokens 50: only %d of %d parts end at a line's end", atLineEnd, parts) + } + } +} + +// --max-tokens prints one part and says which, with the command for the +// next; the next part comes from the local copy, which spends no request +// until it is 15 minutes old. +func TestAPageReadInPartsSpendsOneFetch(t *testing.T) { + text := strings.Repeat("A line of the page that is long enough.\n", 30) + var calls atomic.Int32 + base := api(t, func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + io.WriteString(w, text) + }) + cache, clock := t.TempDir(), time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) + fetch := func(list ...string) result { + var stdout, stderr bytes.Buffer + status := run(list, runtime{ + env: envOf(map[string]string{"STRING_API_KEY": "test-key", "STRING_API_BASE_URL": base, "XDG_CACHE_HOME": cache}), + client: http.DefaultClient, + stdin: strings.NewReader(""), + stdout: &stdout, + stderr: &stderr, + now: func() time.Time { return clock }, + }) + return result{status, stdout.String(), stderr.String()} + } + + first := fetch("fetch", "https://example.com", "--max-tokens", "100") + if want := "part 1 of 3 (tokens 0–100 of ~300). next: string fetch https://example.com --max-tokens 100 --offset 100\n"; first.status != 0 || first.output != text[:400] || first.errors != want || calls.Load() != 1 { + t.Errorf("the first part: %+v after %d requests, want stderr %q", first, calls.Load(), want) + } + second := fetch("fetch", "https://example.com", "--max-tokens", "100", "--offset", "100") + if want := "part 2 of 3 (tokens 100–200 of ~300), from the local copy, no credit used. next: string fetch https://example.com --max-tokens 100 --offset 200\n"; second.status != 0 || second.output != text[400:800] || second.errors != want || calls.Load() != 1 { + t.Errorf("the second part: %+v after %d requests, want stderr %q", second, calls.Load(), want) + } + last := fetch("fetch", "https://example.com", "--maxTokens=100", "--offset=200") + if want := "part 3 of 3 (tokens 200–300 of ~300), from the local copy, no credit used\n"; last.status != 0 || last.output != text[800:] || last.errors != want { + t.Errorf("the last part: %+v, want stderr %q", last, want) + } + if goruntime.GOOS != "windows" { + files, _ := filepath.Glob(filepath.Join(cache, "string", "fetch", "*.page")) + if info, err := os.Stat(files[0]); len(files) != 1 || err != nil || info.Mode().Perm() != 0o600 { + t.Errorf("the local copy: %v, %v", files, err) + } + } + // A copy past 15 minutes isn't used: the part is fetched again. + clock = clock.Add(16 * time.Minute) + if again := fetch("fetch", "https://example.com", "--max-tokens", "100", "--offset", "100"); again.status != 0 || strings.Contains(again.errors, "local copy") || calls.Load() != 2 { + t.Errorf("after 16 minutes: %+v after %d requests", again, calls.Load()) + } + // Other fields are another page, with a copy of their own. + if other := fetch("fetch", "https://example.com", "--mainContentOnly", "--max-tokens", "100", "--offset", "100"); strings.Contains(other.errors, "local copy") || calls.Load() != 3 { + t.Errorf("another field: %+v after %d requests", other, calls.Load()) + } + + for list, want := range map[string]string{ + "fetch https://example.com --offset 100": "error: --offset needs --max-tokens, which sets the size of each part\n", + "fetch https://example.com --max-tokens 0": "error: --max-tokens must be a positive integer\n", + "fetch https://example.com --max-tokens 100 -o page.md": "error: Use --max-tokens to read a page in parts, or -o to save all of it, not both\n", + "fetch https://example.com --max-tokens 100 --format raw": "error: --max-tokens pages text, not --format raw\n", + "fetch https://example.com --max-tokens 100 --offset minus": "error: --offset must be a nonnegative integer\n", + } { + if got := runOffline(t, strings.Fields(list)...); got.status != exitUsage || got.errors != want { + t.Errorf("string %s: %+v, want %q", list, got, want) + } + } + // The next command keeps the flags as given, with the new offset. + if got := withOffset([]string{"fetch", "https://example.com", "--max-tokens", "100", "--offset=100", "--json"}, 200); strings.Join(got, " ") != "fetch https://example.com --max-tokens 100 --json --offset "+strconv.Itoa(200) { + t.Errorf("withOffset: %v", got) + } +} diff --git a/cmd/string/run.go b/cmd/string/run.go index 8880546..3df55ad 100644 --- a/cmd/string/run.go +++ b/cmd/string/run.go @@ -284,6 +284,11 @@ type operation struct { line []string // siteStatus is the status the fetched site answered, from X-Status-Code. siteStatus string + // maxTokens and offset are --max-tokens and --offset: the part of the + // page to print, in tokens. maxTokens is 0 for all of it. + maxTokens, offset int + // fromCopy says the page came from its local copy, not a request. + fromCopy bool } // args is a parsed command line. Every command takes --help and --input; @@ -798,7 +803,7 @@ var sitemapFields = map[string]kind{ } func fetchCommand(list []string, stdin io.Reader) (*operation, error) { - parsed, err := parse(list, spec{options: []string{"output"}, fields: fetchFields}) + parsed, err := parse(list, spec{options: []string{"output", "max-tokens", "offset"}, fields: fetchFields}) if err != nil || parsed.help { return nil, err } @@ -824,7 +829,38 @@ func fetchCommand(list []string, stdin io.Reader) (*operation, error) { return nil, err } body["url"], body["method"], body["format"] = target, "GET", format - return &operation{method: "POST", path: "/fetch", body: body, binary: format == "raw", output: parsed.values["output"], flagged: flagged(parsed), note: note}, nil + op := &operation{method: "POST", path: "/fetch", body: body, binary: format == "raw", output: parsed.values["output"], flagged: flagged(parsed), note: note} + return op, pagesOf(op, parsed) +} + +// pagesOf reads --max-tokens and --offset into op: a part of the page, the +// size of an agent's reading, in place of all of it. +func pagesOf(op *operation, parsed args) error { + tokens, paged := parsed.values["max-tokens"] + offset, hasOffset := parsed.values["offset"] + switch { + case !paged && hasOffset: + return errors.New("--offset needs --max-tokens, which sets the size of each part") + case !paged: + return nil + case op.binary: + return errors.New("--max-tokens pages text, not --format raw") + case op.output != "": + return errors.New("Use --max-tokens to read a page in parts, or -o to save all of it, not both") + } + n, err := boundedInteger(tokens, "--max-tokens", 1, "positive") + if err != nil { + return err + } + op.maxTokens = int(n) + if hasOffset { + n, err := boundedInteger(offset, "--offset", 0, "nonnegative") + if err != nil { + return err + } + op.offset = int(n) + } + return nil } func requestCommand(list []string, stdin io.Reader) (*operation, error) { @@ -1207,9 +1243,19 @@ func execute(list []string, rt runtime) error { } caller := apiClient{rt: rt, base: base, key: key} started := rt.clock() - data, err := caller.call(op) - if err != nil { - return err + // The parts of a page after the first come from the local copy the first + // part saved, so reading a long page in parts spends one fetch. + var data []byte + if op.maxTokens > 0 && op.offset > 0 { + data, op.fromCopy = readCopy(rt, op.body) + } + if !op.fromCopy { + if data, err = caller.call(op); err != nil { + return err + } + if op.maxTokens > 0 { + saveCopy(rt, op.body, data) + } } var ended error if op.approve || op.wait { @@ -1293,6 +1339,18 @@ func (c apiClient) emit(op *operation, data []byte) error { data = []byte(text) } fetched := op.command == "fetch" + if op.maxTokens > 0 { + whole := decodeText(data) + part, start, end, next := page(whole, op.maxTokens, op.offset) + if !strings.HasSuffix(part, "\n") { + part += "\n" + } + if err := write(c.rt.stdout, []byte(part)); err != nil { + return err + } + fmt.Fprint(c.rt.stderr, pageFooter(op.line, len(whole), op.maxTokens, start, end, next, op.fromCopy)) + return nil + } if op.output == "" || op.output == "-" { // Where no person reads stdout at a terminal, a large page's size // comes first, before an agent's runner cuts the output. diff --git a/cmd/string/size.go b/cmd/string/size.go index dfd07a5..e24259a 100644 --- a/cmd/string/size.go +++ b/cmd/string/size.go @@ -3,6 +3,7 @@ package main import ( "fmt" "net/url" + "slices" "strconv" "strings" ) @@ -32,8 +33,9 @@ func sizeNotice(rt runtime, target string, size int, line []string) string { if !ok { cut = "Most agents cut output this long." } - return fmt.Sprintf("note: %s returned %s bytes (~%s tokens). %s\nSave it and read parts: %s\n", - hostOf(target), thousands(int64(size)), thousands(int64(tokens(size))), cut, commandLine(append(line, "-o", "page.md"))) + return fmt.Sprintf("note: %s returned %s bytes (~%s tokens). %s\nSave it and read parts: %s\nOr page it: %s\n", + hostOf(target), thousands(int64(size)), thousands(int64(tokens(size))), cut, + commandLine(append(slices.Clone(line), "-o", "page.md")), commandLine(append(slices.Clone(line), "--max-tokens", "6000"))) } // tokens estimates the tokens in size bytes of text, at four bytes each.