Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
5b5f153
Work out once whether a person, a coding agent or CI runs string
asavor Nov 20, 2026
f1aa517
Show update notices only to a person at a terminal
asavor Nov 20, 2026
2965b31
Say in the help and README how string finds a coding agent
asavor Nov 20, 2026
0a7ced0
Say in each request to String how string runs and which agent runs it
asavor Nov 20, 2026
5821244
Say in the help and README what each request tells String
asavor Nov 20, 2026
c43831d
Send the download host the same User-Agent as requests to String
asavor Nov 20, 2026
a6e36d4
Open a sign-in link in the browser only for a person at a terminal
asavor Nov 20, 2026
bd8003c
Wait for a person only when one is at the terminal
asavor Nov 20, 2026
744b748
Test that switches before update start no update check
asavor Nov 20, 2026
30068ae
Give each request to String a time limit
asavor Nov 20, 2026
6dd38e5
Bound sitemap --wait and say how to resume it
asavor Nov 20, 2026
4800d6b
Keep a sign-in's code when its server doesn't answer in time
asavor Nov 20, 2026
7c7b02c
Merge branch 'request-time-limits' into bounded-sitemap-wait
asavor Nov 20, 2026
e80c467
Bound login --poll and trial claim --poll and say how to resume them
asavor Nov 20, 2026
0c5815a
Say in the help and README how --poll waits and resumes
asavor Nov 20, 2026
60bea10
Say what Ctrl-C leaves behind, then end as an interrupted program
asavor Nov 20, 2026
b47aa9a
Say in the help and README what Ctrl-C does
asavor Nov 20, 2026
87502af
Give every command its own help, and take -h anywhere
asavor Nov 20, 2026
c13eb52
Say in the help and README how to get a command's help and the version
asavor Nov 20, 2026
5389a48
Suggest the command or flag meant, and take every spelling of a flag
asavor Nov 20, 2026
5ee2bc3
Say in the help and README which spellings work and what a typo gets
asavor Nov 20, 2026
534cf9b
Fetch a bare domain over https, and say when https:// was added
asavor Nov 20, 2026
aa7a92c
Say in the help and README that a bare domain works
asavor Nov 20, 2026
c147556
Add help topics, and start the help for all of string with lines for …
asavor Nov 20, 2026
f63fcff
Say in the help and README which help topics there are
asavor Nov 20, 2026
20d9042
Say in every JSON error its exit code, whether to retry, and the step…
asavor Nov 20, 2026
9798023
Say in the help and README what each JSON error field means
asavor Nov 20, 2026
7e0bb83
Write each error as error: and a sentence, without raw bodies
asavor Nov 20, 2026
5231315
Say in the help and README how an error reads
asavor Nov 20, 2026
952b5fb
Add --errors json, and say ahead what changes for fetch in 0.4
asavor Nov 20, 2026
7ceeaaa
Say in the help and README what --errors json does and what changes i…
asavor Nov 20, 2026
755cda4
Say a large page's size first, and what -o saved, with an outline
asavor Nov 20, 2026
e65ca51
Say in the help and README what -o says, what a large page says, and -q
asavor Nov 20, 2026
767931a
Read a long page in parts with --max-tokens, from one fetch
asavor Nov 20, 2026
69d23c2
Say in the help and README how to read a page in parts
asavor Nov 20, 2026
1d8cc0d
Merge main into page-tokens
asavor Nov 20, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 10 additions & 2 deletions cmd/string/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions cmd/string/page_size_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,17 @@ 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
exec execCtx
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"}, ""},
} {
Expand Down
125 changes: 125 additions & 0 deletions cmd/string/pages.go
Original file line number Diff line number Diff line change
@@ -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())
}
}
130 changes: 130 additions & 0 deletions cmd/string/pages_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading