oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package fakeclaude is a stand-in for the pinned Claude Code 2.1.312 CLI,
2// reproducing what Equipo relies on from the recordings under
3// internal/runner/provider/claude/testdata: `auth status --json`, and the
4// stream-json print mode with --verbose, stdin held open, one system/init
5// per turn after the first input, partial-message stream_event deltas, an
6// assistant frame and a result frame; --session-id and --resume with a
7// transcript under $CLAUDE_CONFIG_DIR/projects/-workspace; and the stdio MCP
8// server from --mcp-config.
9//
10// Test binaries call Main when they are started as "claude". Prompt words
11// steer it: "sleep:<ms>" pauses mid-reply, "crash" exits mid-turn, "fail"
12// ends the turn with an error result, "badinit" reports a native tool in
13// system/init, "othersession" answers under another session id, "accents"
14// replies with non-ASCII text, "replymd" (or "replymd:long", or
15// "replymd:paste" with two paste boxes) with a formatted one, "chunks:<n>" streams in n deltas, "slowstream" pauses after every chunk,
16// "think" opens with a thinking block, "pause:<ms>" waits before any text, and "tool:<name>[:<arg>]" calls an
17// Equipo MCP tool before replying (add_project:<repo>,
18// create_project:<namespace>/<name>, ask_person:<question>|<option>...,
19// find:<query>, search_code:<repo>|<query>, read_file:<repo>|<path>,
20// write_note:<source>|<text>, read_notes; the Assistant's look[:<query>],
21// describe:<operation>, use:<operation>|<json input> and
22// read_attachment:<path>).
23//
24// Jobs: a prompt carrying a job's news ("[News about one of the person's
25// jobs", a team_update turn) steers by the news alone. With "The work on
26// it has a question:" it calls use team_reply for the request in "Job
27// ... (request <id>)", answering with the first option of "The answer
28// must be one of:" (or, with none, the question's text after
29// "answer:"), and ends with no text. With "It stopped before any work
30// started" or "A step of it failed" and "Nudges left:" above 0 it calls
31// use team_nudge for that request, words the quoted text of "The person
32// asked for it in these words:" and context, when those words hold
33// "nudge:", the rot13 words after it decoded, and ends with no text.
34// With "no nudges are left" or "only the person can move it on" it
35// replies "It stopped.". Other news gets the usual reply. A Coordinator
36// prompt answering its question ("(My answer to your question ...")
37// also follows the newest "onanswer:<rot13 words>" of the session's
38// earlier prompts, decoded. In decoded words each " tool:" starts a
39// line, so one line can carry several tool words.
40//
41// Moving in: a prompt with "[Equipo: moving in" calls status, reads the
42// README of up to three listed repositories, writes notebook.md naming
43// them and introduces itself; "[Equipo: access changed]" reads only the
44// newly reachable repositories and says so. "movein-pause:<ms>" anywhere
45// pauses before each of those tool calls. A prompt carrying the notebook
46// ("=== Your notebook") adds "(notebook in context)". write_note text
47// starting "rot13:" is decoded first, so a test can write words the
48// person's message does not contain; a source starting "+" (as in
49// "+person|...") keeps the notebook's other entries.
50//
51// Tasks: record_task:<repo>|<title>|<brief>, add_finding:<task>|<text>|
52// <repo>|<path>|<line>[|<headline>], start_task:<task>|<brief>, read_task:<task> and
53// cancel_task:<task>; propose_specialist:<brief> proposes the research-v1
54// profile and research:<task>|<question>|<url>[,<url>...] requests a run;
55// "$task" in a later tool's argument is the id the
56// last record_task returned. record_task:<repo>|<title>|<brief>|separate
57// records even when similar tasks are open; "$similar" is the first
58// similar task record_task returned, for add_report:<task>|<text>.
59//
60// Engineering: a prompt starting "[Equipo: engineering]" is a step. Each
61// "edit:<path>|<old>|<new>" in it asks the permission callback for Edit on
62// /workspace/<path> and, if allowed, replaces old with new in the file;
63// "create:<path>|<text>" asks for Write on /workspace/<path> and, if
64// allowed, writes the text there as a new file (the text ends at ";" or
65// the line's end); "escape:<path>" asks for Write on an absolute path and reports the
66// answer; "copy:<absolute path>|<path>" asks to Read the absolute path
67// and, if allowed, copies its bytes to /workspace/<path> (asking for
68// Write); "rowrite:<absolute path>" writes there directly, asking
69// nobody, and says whether the filesystem refused (with its errno);
70// "linger:<absolute path>" starts, once, a child in its own session that
71// ignores SIGTERM and SIGHUP, keeps the environment and writes its pid
72// there; "probe:<path>" says whether the file is in the workspace and
73// "saycwd" names the workspace in the reply;
74// "stepsleep:<ms>" pauses before editing, "stepwait:<absolute path>"
75// waits before editing while that file exists, and "afterwait:<absolute
76// path>" waits the same way after editing, before the reply (at most ten
77// minutes each); "bytes:<path>|<base64>"
78// asks for Write and writes the decoded bytes (a binary file);
79// "symlink:<path>|<target>" asks for Write and makes a symbolic link;
80// "say:<text>" (to ";" or the line's end) adds the text to the reply,
81// "headsay:<text>" is its headline's words;
82// "move:<from>|<to>" asks for Write on <to> and renames the file;
83// with "steplimit:<email>", "limitleave:<path>" writes the file before
84// the refusal (a refused attempt that changed its tree). On a darwin
85// launch (it pins the project directory) the workspace is the CLI's own
86// working directory, the real worktree, not /workspace. In a rebase round each
87// "conflict:<path>" line has its conflicts resolved to the task's side.
88// The reply is a summary, after a "Headline: ..." line when the prompt
89// asks for one, ending " (resumed session)" when the step resumed a kept
90// session (a fix round), whose result then reports the earlier
91// transcript as cache_read_input_tokens. Every result's num_turns is one
92// plus the tools the turn called. Before anything else (and before
93// "stepsleep") it reads each file it will edit, so the step shows its
94// activity while it runs.
95//
96// Design: a prompt starting "[Equipo: design]" is a Design step, played
97// first as an Engineering one (edit:, create:, copy: and the rest); then
98// each "render:<json>" (the JSON ends at ";" or the line's end) calls
99// render_page with that input and collects the captures its reply names
100// (/render/<id>); then each "submit:<json>" calls submit_candidate, with
101// "$cap<n>" in it the n-th capture collected. The reply adds what each
102// call answered: "[render_page rendered <ids>]" or "[render_page
103// refused: <text>]", and "[submit_candidate: <text>]".
104//
105// Review: a prompt starting "[Equipo: review]" reads the change and calls
106// submit_review: "review:approve" (the default), "review:changes:<path>|
107// <line>|<text>", "review:need:<path>|<text in the file>|<finding>"
108// (approve when /workspace/<path> holds the text, else ask for changes),
109// "review:silent" (no verdict), "reviewsleep:<ms>" (a pause first) and "review:write:<path>" (asks to write
110// and reports the answer). A finding ends at ";" or the line's end. In a
111// finding "~" becomes "|" and "=" becomes
112// ":", so a finding can carry an edit word for the next Engineering
113// round without steering the first one.
114// Questions: a prompt starting "[Equipo: question]" is a resumed step
115// session asked about its work. The reply starts "From my session:" and
116// the last reply the transcript holds, so a test sees the session was
117// the step's own. In the question (the quoted data after "The person's
118// question: "): "ask:git" calls
119// git_diff and quotes the change's first added line, "ask:read:<path>"
120// asks to Read /workspace/<path> (on a darwin launch, the worktree) and
121// quotes its first line, "ask:write:<path>" asks to Write it and reports
122// the answer, "asksleep:<ms>" pauses before the reply.
123// Research: a prompt starting "[Equipo: research]" is a Research step.
124// Each "keep:<source>|<role>|<description>" (the description ends at ";"
125// or the line's end) calls keep_image; then one submit_findings carries
126// "summary:<text>", every "fact:<label>|<value>|<source>[,<source>...]",
127// every "gap:<text>" and every "image:<id>", where "$kept" is the last
128// keep_image reply and "$kept<n>" the n-th. "findings:silent" submits
129// nothing, "findings:twice" submits twice, and "findings:raw:<json>"
130// submits that JSON object verbatim instead. The reply names what was
131// kept and each tool's answer. Words in page text count too, as an
132// injected instruction would for a gullible model.
133// Native tools in system/init are those of --tools.
134//
135// Several messages in one turn: when the newest part of the prompt holds
136// "Message <i> of <n>:" headers (the instance's batch), the reply ends
137// "You sent <n> messages: <i>/<n> <first line> [<files>]; ...", in the
138// order the prompt gives them, so a test sees each one arrived apart.
139//
140// Setup tokens: with CLAUDE_CODE_OAUTH_TOKEN in its environment the fake
141// is signed in by that token, as the pinned CLI is: `auth status` says
142// logged in for any token at all, never asking the server (with the
143// email Token encoded, when it has one), and writes no login file; only
144// a turn finds a bad token out: a turn on a token that is not one of
145// Token's is refused as an authentication failure, and so is a turn in
146// a home with neither a token nor a login file. A token anywhere in
147// argv exits 3 at once. A reply on a token ends "(signed in by token)".
148// `setup-token` (setuptoken.go) makes such a token from a sign-in code.
149package fakeclaude
150
151import (
152 "bufio"
153 "bytes"
154 "crypto/sha256"
155 "encoding/base64"
156 "encoding/hex"
157 "encoding/json"
158 "errors"
159 "fmt"
160 "image"
161 _ "image/gif" // DecodeConfig for attached GIFs
162 _ "image/jpeg" // DecodeConfig for attached JPEGs
163 _ "image/png" // DecodeConfig for attached PNGs
164 "io"
165 "os"
166 "os/exec"
167 "os/signal"
168 "path/filepath"
169 "regexp"
170 "slices"
171 "strconv"
172 "strings"
173 "syscall"
174 "time"
175)
176
177// Version is the pinned CLI version the fake reports.
178const Version = "2.1.312"
179
180// Main runs the fake with argv after the program name.
181func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
182 if len(args) == 2 && args[0] == lingerArg {
183 return lingerMain(args[1])
184 }
185 // The token by descriptor, as the pinned CLI reads it (task 1, S4):
186 // /dev/fd/<n>, trimmed, when CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR
187 // names one; the fake then holds it as if it were in its environment.
188 if n := os.Getenv(tokenFDEnv); n != "" && os.Getenv(tokenEnv) == "" {
189 raw, err := os.ReadFile("/dev/fd/" + n)
190 if err != nil || len(raw) == 0 {
191 fmt.Fprintln(stderr, "no token on descriptor "+n)
192 return 3
193 }
194 os.Setenv(tokenEnv, strings.TrimSpace(string(raw)))
195 }
196 if tok := os.Getenv(tokenEnv); tok != "" {
197 for _, a := range args {
198 if strings.Contains(a, tok) {
199 fmt.Fprintln(stderr, "the token is in argv")
200 return 3
201 }
202 }
203 }
204 if len(args) == 1 && args[0] == "--version" {
205 fmt.Fprintln(stdout, Version+" (Claude Code)")
206 return 0
207 }
208 if len(args) == 1 && args[0] == "setup-token-child" && os.Getenv("FAKE_SETUP_CHILD") == "1" {
209 return setupChild()
210 }
211 if len(args) >= 1 && args[0] == "setup-token" {
212 return setupToken(args, stdin, stdout)
213 }
214 if len(args) >= 3 && args[0] == "auth" && args[2] == "--help" {
215 return 0
216 }
217 if len(args) >= 2 && args[0] == "auth" && args[1] == "status" {
218 return authStatus(stdout)
219 }
220 if len(args) >= 2 && args[0] == "auth" && args[1] == "login" {
221 return authLogin()
222 }
223 f, err := parse(args)
224 if err != nil {
225 fmt.Fprintln(stderr, err)
226 return 2
227 }
228 return f.serve(stdin, stdout, stderr)
229}
230
231func home() string {
232 if h := os.Getenv("CLAUDE_CONFIG_DIR"); h != "" {
233 return h
234 }
235 return os.Getenv("HOME")
236}
237
238// authStatus reports the identity in the home and refreshes the login the
239// way the CLI does: a new credential file, atomically replaced.
240func authStatus(stdout io.Writer) int {
241 if tok, set := os.LookupEnv(tokenEnv); set && tok != "" {
242 // Any token is logged in: status never checks it.
243 email, ok := tokenEmail(tok)
244 if !ok {
245 email = ""
246 }
247 status := map[string]any{"loggedIn": true, "authMethod": "oauth_token", "apiProvider": "firstParty"}
248 if email != "" {
249 status["email"] = email
250 }
251 out, _ := json.Marshal(status)
252 fmt.Fprintln(stdout, string(out))
253 return 0
254 }
255 h := home()
256 var id struct {
257 AccountID string `json:"account_id"`
258 }
259 raw, err := os.ReadFile(filepath.Join(h, "equipo-identity.json"))
260 if os.IsNotExist(err) {
261 raw, err = os.ReadFile(filepath.Join(h, ".fake-login.json"))
262 }
263 if err == nil {
264 err = json.Unmarshal(raw, &id)
265 }
266 if _, gone := os.Stat(filepath.Join(h, ".fake-signed-out")); gone == nil || err != nil {
267 fmt.Fprintln(stdout, `{"loggedIn":false,"authMethod":"none","apiProvider":"firstParty"}`)
268 return 1
269 }
270 if err = WriteCredentials(h, time.Now().Add(8*time.Hour)); err != nil {
271 return 1
272 }
273 out, _ := json.Marshal(map[string]any{"loggedIn": true, "authMethod": "claude.ai", "apiProvider": "firstParty", "email": id.AccountID, "orgId": "fake-org", "subscriptionType": "max"})
274 fmt.Fprintln(stdout, string(out))
275 return 0
276}
277
278func authLogin() int {
279 // Signs in as FAKE_LOGIN_EMAIL (the terminal login, whose
280 // paste goes into the CLI); the loopback sign-in is gone.
281 email := os.Getenv("FAKE_LOGIN_EMAIL")
282 if email == "" {
283 return 1
284 }
285 h := home()
286 if err := WriteCredentials(h, time.Now().Add(8*time.Hour)); err != nil {
287 return 1
288 }
289 raw, _ := json.Marshal(map[string]any{"oauthAccount": map[string]string{"emailAddress": email, "accountUuid": "fake-account"}})
290 if err := os.WriteFile(filepath.Join(h, ".claude.json"), raw, 0600); err != nil {
291 return 1
292 }
293 // The fake reads its identity from this marker, like the real CLI
294 // reads its account metadata.
295 id, _ := json.Marshal(map[string]string{"account_id": email})
296 return map[bool]int{true: 0, false: 1}[os.WriteFile(filepath.Join(h, ".fake-login.json"), id, 0600) == nil]
297}
298
299// WriteCredentials replaces the fake OAuth file atomically, mode 0600.
300func WriteCredentials(home string, expires time.Time) error {
301 raw, _ := json.Marshal(map[string]any{"claudeAiOauth": map[string]any{"accessToken": "fake-access", "refreshToken": "fake-refresh", "expiresAt": expires.UnixMilli(), "scopes": []string{"user:inference"}}})
302 tmp := filepath.Join(home, ".credentials.json.fake")
303 if err := os.WriteFile(tmp, raw, 0600); err != nil {
304 return err
305 }
306 return os.Rename(tmp, filepath.Join(home, ".credentials.json"))
307}
308
309type fake struct {
310 model, session, mcpConfig string
311 resume, partial bool
312 native []string
313 lastTask string
314 lastSimilar string
315
316 mcpIn io.Writer
317 mcpOut *bufio.Reader
318 tools []string
319 callID int
320}
321
322func parse(args []string) (*fake, error) {
323 f := &fake{}
324 print, verbose, inFormat, outFormat := false, false, "", ""
325 for i := 0; i < len(args); i++ {
326 next := func() string {
327 if i+1 < len(args) {
328 i++
329 return args[i]
330 }
331 return ""
332 }
333 switch args[i] {
334 case "-p":
335 print = true
336 case "--verbose":
337 verbose = true
338 case "--input-format":
339 inFormat = next()
340 case "--output-format":
341 outFormat = next()
342 case "--model":
343 f.model = next()
344 case "--session-id":
345 f.session = next()
346 case "--resume":
347 f.session, f.resume = next(), true
348 case "--mcp-config":
349 f.mcpConfig = next()
350 case "--include-partial-messages":
351 f.partial = true
352 case "--tools":
353 if v := next(); v != "" {
354 f.native = strings.Split(v, ",")
355 }
356 case "--setting-sources", "--settings", "--permission-mode", "--permission-prompt-tool":
357 next()
358 }
359 }
360 // 2.1.312 requires --verbose for stream-json output in print mode.
361 if !print || !verbose || inFormat != "stream-json" || outFormat != "stream-json" || f.model == "" || f.session == "" {
362 return nil, fmt.Errorf("unsupported arguments")
363 }
364 return f, nil
365}
366
367func (f *fake) transcript() string {
368 return filepath.Join(home(), "projects", "-workspace", f.session+".jsonl")
369}
370
371var sleepWord = regexp.MustCompile(`\bsleep:([0-9]+)`)
372
373// pauseWord waits after any tools and before the first text.
374var pauseWord = regexp.MustCompile(`pause:([0-9]+)`)
375
376// toolWord is tool:<name> or tool:<name>:<arg>, the argument running to
377// the end of the line.
378var toolWord = regexp.MustCompile(`tool:([a-z_]+)(?::([^\n]*))?`)
379
380// ToolInput is the input the fakes send for tool:<name>:<arg>.
381func ToolInput(name, arg string) map[string]any { return toolInput(name, arg) }
382
383func toolInput(name, arg string) map[string]any {
384 arg = strings.TrimSpace(arg)
385 switch name {
386 case "add_project":
387 return map[string]any{"repo": arg}
388 case "create_project":
389 ns, repo, _ := strings.Cut(arg, "/")
390 return map[string]any{"namespace": ns, "name": repo}
391 case "ask_person":
392 parts := strings.Split(arg, "|")
393 return map[string]any{"question": parts[0], "options": parts[1:]}
394 case "find":
395 return map[string]any{"query": arg}
396 case "look":
397 if arg == "" {
398 return map[string]any{}
399 }
400 return map[string]any{"query": arg}
401 case "describe":
402 return map[string]any{"operation": arg}
403 case "use":
404 op, raw, _ := strings.Cut(arg, "|")
405 var input map[string]any
406 if json.Unmarshal([]byte(raw), &input) != nil || input == nil {
407 input = map[string]any{}
408 }
409 return map[string]any{"operation": op, "input": input}
410 case "set_project_home":
411 return map[string]any{"namespace": arg}
412 case "search_code":
413 repo, q, _ := strings.Cut(arg, "|")
414 return map[string]any{"repo": repo, "query": q}
415 case "read_file":
416 repo, p, _ := strings.Cut(arg, "|")
417 return map[string]any{"repo": repo, "path": p}
418 case "write_note":
419 source, text, _ := strings.Cut(strings.TrimPrefix(arg, "+"), "|")
420 if rest, ok := strings.CutPrefix(text, "rot13:"); ok {
421 text = rot13(rest)
422 }
423 return map[string]any{"entries": []map[string]string{{"source": source, "text": text}}}
424 case "read_notes":
425 return map[string]any{}
426 case "read_attachment":
427 return map[string]any{"path": arg}
428 case "record_task":
429 parts := append(strings.SplitN(arg, "|", 4), "", "", "", "")
430 in := map[string]any{"repo": parts[0], "title": parts[1], "brief": parts[2]}
431 if parts[3] == "separate" {
432 in["separate"] = true
433 }
434 return in
435 case "add_report":
436 task, text, _ := strings.Cut(arg, "|")
437 return map[string]any{"task": task, "text": text}
438 case "add_finding":
439 parts := append(strings.SplitN(arg, "|", 6), "", "", "", "", "", "")
440 line, _ := strconv.Atoi(parts[4])
441 in := map[string]any{"task": parts[0], "text": parts[1], "repo": parts[2], "path": parts[3], "line": line}
442 if parts[5] != "" {
443 in["headline"] = parts[5]
444 }
445 return in
446 case "start_task":
447 task, brief, _ := strings.Cut(arg, "|")
448 return map[string]any{"task": task, "brief": brief}
449 case "read_task", "cancel_task":
450 return map[string]any{"task": arg}
451 case "propose_specialist":
452 // The one profile on the menu; the argument is its brief.
453 return map[string]any{"profile": "research-v1", "name": "Research", "brief": arg, "capabilities": []string{"web.research"}, "tools": []string{"submit_findings", "keep_image"}}
454 case "research":
455 parts := append(strings.SplitN(arg, "|", 3), "", "", "")
456 urls := []string{}
457 for _, u := range strings.Split(parts[2], ",") {
458 if u = strings.TrimSpace(u); u != "" {
459 urls = append(urls, u)
460 }
461 }
462 return map[string]any{"task": parts[0], "question": parts[1], "urls": urls}
463 }
464 return map[string]any{}
465}
466
467// rot13 turns each ASCII letter 13 places, so a test can write words a
468// fake must not follow where they first appear.
469func rot13(s string) string {
470 return strings.Map(func(r rune) rune {
471 switch {
472 case r >= 'a' && r <= 'z':
473 return 'a' + (r-'a'+13)%26
474 case r >= 'A' && r <= 'Z':
475 return 'A' + (r-'A'+13)%26
476 }
477 return r
478 }, s)
479}
480
481// unrot is rot13 words decoded, each " tool:" in them starting a line of
482// its own, so one line of them can carry several tool words.
483func unrot(s string) string {
484 return strings.ReplaceAll(rot13(strings.TrimSpace(s)), " tool:", "\ntool:")
485}
486
487// goQuoted is a string as the instance quotes it in a note (%q).
488const goQuoted = `("(?:[^"\\\n]|\\.)*")`
489
490// The lines of a job's news that the fake Assistant acts on (the
491// instance's jobNote).
492var (
493 newsRequest = regexp.MustCompile(`Job "(?:[^"\\\n]|\\.)*" \(request (h_[a-z0-9]+)\)`)
494 newsWords = regexp.MustCompile(`The person asked for it in these words: ` + goQuoted)
495 newsQuestion = regexp.MustCompile(`The work on it has a question: ` + goQuoted)
496 newsOption = regexp.MustCompile(`The answer must be one of: ` + goQuoted)
497 newsNudges = regexp.MustCompile(`Nudges left: ([0-9]+)`)
498)
499
500// newsMarker opens a team_update turn's prompt (the runner's
501// teamUpdateNote).
502const newsMarker = "[News about one of the person's jobs"
503
504// news is what the fake Assistant does with a job's news: the tool word
505// to follow ("" for none) and its reply, with ok false for news it
506// leaves to the usual words. A question is answered with team_reply
507// (its first option, else the question's text after "answer:"); a stop
508// with nudges left is pushed through with team_nudge, quoting the
509// person's words (context: the rot13 words after "nudge:" in them,
510// decoded); a stop it cannot get past is "It stopped.".
511func news(prompt string) (steer, reply string, ok bool) {
512 if !strings.Contains(prompt, newsMarker) {
513 return "", "", false
514 }
515 request := ""
516 if m := newsRequest.FindStringSubmatch(prompt); m != nil {
517 request = m[1]
518 }
519 unquote := func(re *regexp.Regexp) string {
520 m := re.FindStringSubmatch(prompt)
521 if m == nil {
522 return ""
523 }
524 v, _ := strconv.Unquote(m[1])
525 return v
526 }
527 use := func(op string, input map[string]string) string {
528 raw, _ := json.Marshal(input)
529 // "$task" in a nudge's context is the Coordinator's to fill in.
530 return "tool:use:" + op + "|" + strings.ReplaceAll(string(raw), "$", `\u0024`)
531 }
532 if strings.Contains(prompt, "The work on it has a question:") {
533 answer := unquote(newsOption)
534 if answer == "" {
535 _, answer, _ = strings.Cut(unquote(newsQuestion), "answer:")
536 answer = strings.TrimSpace(answer)
537 }
538 return use("team_reply", map[string]string{"request": request, "answer": answer}), "", true
539 }
540 if strings.Contains(prompt, "no nudges are left") || strings.Contains(prompt, "only the person can move it on") {
541 return "", "It stopped.", true
542 }
543 left := 0
544 if m := newsNudges.FindStringSubmatch(prompt); m != nil {
545 left, _ = strconv.Atoi(m[1])
546 }
547 if (strings.Contains(prompt, "It stopped before any work started") || strings.Contains(prompt, "A step of it failed")) && left > 0 {
548 words := unquote(newsWords)
549 input := map[string]string{"request": request, "words": words}
550 if _, rest, found := strings.Cut(words, "nudge:"); found {
551 input["context"] = unrot(rest)
552 }
553 return use("team_nudge", input), "", true
554 }
555 return "", "", false
556}
557
558// answerPrefix opens the Coordinator's frame for an answer to its
559// question (the instance's answerPrefix).
560const answerPrefix = "(My answer to your question "
561
562// onAnswerWord is onanswer:<rot13 words>, to the line's end.
563var onAnswerWord = regexp.MustCompile(`onanswer:([^\n]*)`)
564
565// onAnswer is what the session follows when its question is answered:
566// the decoded words of the newest onanswer: word in an earlier prompt of
567// this session ("" with none).
568func (f *fake) onAnswer() string {
569 raw, err := os.ReadFile(f.transcript())
570 if err != nil {
571 return ""
572 }
573 words := ""
574 for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
575 var v struct {
576 Type string `json:"type"`
577 Text string `json:"text"`
578 }
579 if json.Unmarshal([]byte(line), &v) != nil || v.Type != "user" {
580 continue
581 }
582 if all := onAnswerWord.FindAllStringSubmatch(v.Text, -1); len(all) > 0 {
583 words = unrot(all[len(all)-1][1])
584 }
585 }
586 return words
587}
588
589var editWord = regexp.MustCompile(`edit:([^|\n]+)\|([^|\n]*)\|([^\n]*)`)
590var conflictWord = regexp.MustCompile(`(?m)^conflict:([^\n]+)$`)
591var conflictBlock = regexp.MustCompile(`(?s)<<<<<<< [^\n]*\n.*?=======\n(.*?)>>>>>>> [^\n]*\n`)
592var escapeWord = regexp.MustCompile(`escape:(/[^\s]+)`)
593var copyWord = regexp.MustCompile(`copy:(/[^|\s]+)\|([^\s;]+)`)
594var rowriteWord = regexp.MustCompile(`rowrite:(/[^\s;]+)`)
595var createWord = regexp.MustCompile(`create:([^|\s]+)\|([^;\n]*)`)
596var stepSleep = regexp.MustCompile(`stepsleep:([0-9]+)`)
597var bytesWord = regexp.MustCompile(`bytes:([^|\s]+)\|([A-Za-z0-9+/=]+)`)
598var symlinkWord = regexp.MustCompile(`symlink:([^|\s]+)\|([^;\s]+)`)
599var sayWord = regexp.MustCompile(`\bsay:([^;\n]*)`)
600
601// headWord ("headsay:<text>") replaces the headline's words.
602var headWord = regexp.MustCompile(`headsay:([^;\n]*)`)
603var moveWord = regexp.MustCompile(`move:([^|\s]+)\|([^;\s]+)`)
604var limitLeave = regexp.MustCompile(`limitleave:([^;\s]+)`)
605var stepWait = regexp.MustCompile(`stepwait:(/[^;\s]+)`)
606var lingerWord = regexp.MustCompile(`linger:(/[^;\s]+)`)
607var probeWord = regexp.MustCompile(`probe:([^;\s]+)`)
608var sayCwd = regexp.MustCompile(`\bsaycwd\b`)
609
610// lingerArg starts the fake as linger's child.
611const lingerArg = "__linger"
612
613// linger starts, once (while pidfile is not there), a child in a session
614// of its own that keeps this process's environment (its attempt marker
615// among it), ignores SIGTERM, SIGHUP and SIGINT, writes its pid to
616// pidfile and sleeps ten minutes: what a launch leaves behind that only
617// a SIGKILL ends.
618func linger(pidfile string) {
619 if _, err := os.Lstat(pidfile); err == nil {
620 return
621 }
622 self, err := os.Executable()
623 if err != nil {
624 return
625 }
626 cmd := exec.Command(self, lingerArg, pidfile)
627 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
628 if cmd.Start() == nil {
629 _ = cmd.Process.Release()
630 }
631}
632
633func lingerMain(pidfile string) int {
634 signal.Ignore(syscall.SIGTERM, syscall.SIGHUP, syscall.SIGINT)
635 tmp := pidfile + ".tmp"
636 if os.WriteFile(tmp, []byte(strconv.Itoa(os.Getpid())), 0600) != nil || os.Rename(tmp, pidfile) != nil {
637 return 1
638 }
639 time.Sleep(10 * time.Minute)
640 return 0
641}
642
643var afterWait = regexp.MustCompile(`afterwait:(/[^;\s]+)`)
644
645// holdWhile waits, at most ten minutes, while the file the prompt's word
646// names exists: a test decides when the step goes on.
647func holdWhile(word *regexp.Regexp, prompt string) {
648 m := word.FindStringSubmatch(prompt)
649 if m == nil {
650 return
651 }
652 for deadline := time.Now().Add(10 * time.Minute); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
653 if _, err := os.Lstat(m[1]); err != nil {
654 return
655 }
656 }
657}
658
659// workspaceRoot is the workspace the model's paths name: /workspace in
660// Linux's namespace; on a darwin launch (CLAUDE_CODE_PROJECT_DIR_NAME
661// pinned) the CLI's working directory, its real worktree.
662func workspaceRoot() string {
663 if os.Getenv("CLAUDE_CODE_PROJECT_DIR_NAME") != "" {
664 if wd, err := os.Getwd(); err == nil {
665 return wd
666 }
667 }
668 return "/workspace"
669}
670
671// engineer plays an Engineering step: permission first, then the edit in
672// the working directory (the namespace's /workspace).
673func (f *fake) engineer(prompt string, turn int, emit func(any)) string {
674 prompt = StepMarkerText(prompt)
675 root := workspaceRoot()
676 read := map[string]bool{}
677 for i, m := range DistinctStepMarkers(editWord, prompt) {
678 if path := filepath.Join(root, filepath.Clean("/"+m[1])); !read[path] {
679 read[path] = true
680 f.readTool(fmt.Sprintf("toolu_fake_%d_er%d", turn, i), path, emit)
681 }
682 }
683 if m := stepSleep.FindStringSubmatch(prompt); m != nil {
684 ms, _ := strconv.Atoi(m[1])
685 time.Sleep(time.Duration(ms) * time.Millisecond)
686 }
687 if m := lingerWord.FindStringSubmatch(prompt); m != nil {
688 linger(m[1])
689 }
690 holdWhile(stepWait, prompt)
691 var done []string
692 for _, m := range probeWord.FindAllStringSubmatch(prompt, -1) {
693 rel := filepath.Clean("/" + m[1])[1:]
694 if _, err := os.Lstat(filepath.Join(root, rel)); err == nil {
695 done = append(done, "Found "+rel+".")
696 } else {
697 done = append(done, "No "+rel+".")
698 }
699 }
700 if sayCwd.MatchString(prompt) {
701 done = append(done, "Working in "+root+".")
702 }
703 ask := func(i int, tool string, input map[string]any) bool {
704 id := fmt.Sprintf("toolu_fake_%d_e%d", turn, i)
705 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": tool, "input": input}}}, "uuid": "assistant-" + id})
706 text, isError := f.callTool(id, "permission", map[string]any{"tool_name": tool, "tool_use_id": id, "input": input})
707 var answer struct {
708 Behavior string `json:"behavior"`
709 }
710 return !isError && json.Unmarshal([]byte(text), &answer) == nil && answer.Behavior == "allow"
711 }
712 for i, m := range DistinctStepMarkers(editWord, prompt) {
713 path := filepath.Join(root, filepath.Clean("/"+m[1]))
714 if !ask(i, "Edit", map[string]any{"file_path": path, "old_string": m[2], "new_string": m[3]}) {
715 done = append(done, "Edit of "+m[1]+" was denied.")
716 continue
717 }
718 raw, err := os.ReadFile(m[1])
719 if err != nil {
720 done = append(done, "Could not read "+m[1]+".")
721 continue
722 }
723 if err := os.WriteFile(m[1], []byte(strings.Replace(string(raw), m[2], m[3], 1)), 0644); err != nil {
724 done = append(done, "Could not write "+m[1]+".")
725 continue
726 }
727 done = append(done, fmt.Sprintf("Replaced %q with %q in %s.", m[2], m[3], m[1]))
728 }
729 // A rebase round: each conflicted file keeps the task's side of every
730 // conflict (the part after =======).
731 for i, m := range conflictWord.FindAllStringSubmatch(prompt, -1) {
732 path := filepath.Join(root, filepath.Clean("/"+m[1]))
733 raw, err := os.ReadFile(m[1])
734 if err != nil {
735 done = append(done, "Could not read "+m[1]+".")
736 continue
737 }
738 resolved := conflictBlock.ReplaceAllString(string(raw), "$1")
739 if !ask(200+i, "Edit", map[string]any{"file_path": path, "old_string": string(raw), "new_string": resolved}) {
740 done = append(done, "Edit of "+m[1]+" was denied.")
741 continue
742 }
743 if err := os.WriteFile(m[1], []byte(resolved), 0644); err != nil {
744 done = append(done, "Could not write "+m[1]+".")
745 continue
746 }
747 done = append(done, "Resolved the conflict in "+m[1]+", keeping this task's change.")
748 }
749 for i, m := range createWord.FindAllStringSubmatch(prompt, -1) {
750 rel := filepath.Clean("/" + m[1])[1:]
751 path := filepath.Join(root, rel)
752 if !ask(300+i, "Write", map[string]any{"file_path": path, "content": m[2]}) {
753 done = append(done, "Write of "+rel+" was denied.")
754 continue
755 }
756 if err := os.MkdirAll(filepath.Dir(rel), 0755); err != nil {
757 done = append(done, "Could not write "+rel+".")
758 continue
759 }
760 if err := os.WriteFile(rel, []byte(m[2]+"\n"), 0644); err != nil {
761 done = append(done, "Could not write "+rel+".")
762 continue
763 }
764 done = append(done, "Created "+rel+".")
765 }
766 // copy:<absolute source>|<path>: Read the source (asking, as a read
767 // outside /workspace asks), then Write its bytes to /workspace/<path>.
768 for i, m := range copyWord.FindAllStringSubmatch(prompt, -1) {
769 rel := filepath.Clean("/" + m[2])[1:]
770 if !ask(400+i, "Read", map[string]any{"file_path": m[1]}) {
771 done = append(done, "Read of "+m[1]+" was denied.")
772 continue
773 }
774 raw, err := os.ReadFile(m[1])
775 if err != nil {
776 done = append(done, "Could not read "+m[1]+".")
777 continue
778 }
779 if !ask(500+i, "Write", map[string]any{"file_path": filepath.Join(root, rel), "content": "(binary)"}) {
780 done = append(done, "Write of "+rel+" was denied.")
781 continue
782 }
783 if err := os.MkdirAll(filepath.Dir(rel), 0755); err != nil || os.WriteFile(rel, raw, 0644) != nil {
784 done = append(done, "Could not write "+rel+".")
785 continue
786 }
787 done = append(done, fmt.Sprintf("Copied %s to %s.", m[1], rel))
788 }
789 // rowrite:<absolute path>: write there directly, as a process would
790 // without asking, and say whether the filesystem let it.
791 for _, m := range rowriteWord.FindAllStringSubmatch(prompt, -1) {
792 if err := os.WriteFile(m[1], []byte("x"), 0644); err != nil {
793 var errno syscall.Errno
794 if errors.As(err, &errno) {
795 done = append(done, fmt.Sprintf("Writing %s failed (errno %d).", m[1], int(errno)))
796 } else {
797 done = append(done, "Writing "+m[1]+" failed.")
798 }
799 continue
800 }
801 done = append(done, "Writing "+m[1]+" worked.")
802 }
803 for i, m := range escapeWord.FindAllStringSubmatch(prompt, -1) {
804 if ask(100+i, "Write", map[string]any{"file_path": m[1], "content": "x"}) {
805 done = append(done, "Write to "+m[1]+" was allowed.")
806 } else {
807 done = append(done, "Write to "+m[1]+" was denied.")
808 }
809 }
810 for i, m := range bytesWord.FindAllStringSubmatch(prompt, -1) {
811 rel := filepath.Clean("/" + m[1])[1:]
812 raw, err := base64.StdEncoding.DecodeString(m[2])
813 if err != nil || !ask(600+i, "Write", map[string]any{"file_path": filepath.Join(root, rel), "content": "(binary)"}) {
814 done = append(done, "Write of "+rel+" was denied.")
815 continue
816 }
817 if os.MkdirAll(filepath.Dir(rel), 0755) != nil || os.WriteFile(rel, raw, 0644) != nil {
818 done = append(done, "Could not write "+rel+".")
819 continue
820 }
821 done = append(done, "Wrote "+rel+".")
822 }
823 for i, m := range symlinkWord.FindAllStringSubmatch(prompt, -1) {
824 rel := filepath.Clean("/" + m[1])[1:]
825 if !ask(700+i, "Write", map[string]any{"file_path": filepath.Join(root, rel), "content": m[2]}) {
826 done = append(done, "Write of "+rel+" was denied.")
827 continue
828 }
829 if os.MkdirAll(filepath.Dir(rel), 0755) != nil || os.Symlink(m[2], rel) != nil {
830 done = append(done, "Could not link "+rel+".")
831 continue
832 }
833 done = append(done, "Linked "+rel+".")
834 }
835 for i, m := range moveWord.FindAllStringSubmatch(prompt, -1) {
836 from, to := filepath.Clean("/" + m[1])[1:], filepath.Clean("/" + m[2])[1:]
837 if !ask(800+i, "Write", map[string]any{"file_path": filepath.Join(root, to), "content": "(moved)"}) {
838 done = append(done, "Write of "+to+" was denied.")
839 continue
840 }
841 if os.MkdirAll(filepath.Dir(to), 0755) != nil || os.Rename(from, to) != nil {
842 done = append(done, "Could not move "+from+".")
843 continue
844 }
845 done = append(done, "Moved "+from+" to "+to+".")
846 }
847 for _, m := range sayWord.FindAllStringSubmatch(prompt, -1) {
848 done = append(done, strings.TrimSpace(m[1]))
849 }
850 // The work is in the tree; hold before replying (a step that runs out
851 // of time with its work done so far).
852 holdWhile(afterWait, prompt)
853 headline := ""
854 if strings.Contains(prompt, "Headline: ") {
855 // The step prompt asks for a headline line first.
856 headline = "Headline: Made the change the task asks for.\n\n"
857 if len(done) == 0 {
858 headline = "Headline: Nothing needed changing.\n\n"
859 }
860 if m := headWord.FindStringSubmatch(prompt); m != nil {
861 headline = "Headline: " + strings.TrimSpace(m[1]) + "\n\n"
862 }
863 }
864 if len(done) == 0 {
865 return headline + "I looked and changed nothing."
866 }
867 return headline + strings.Join(done, " ")
868}
869
870var (
871 renderWord = regexp.MustCompile(`render:(\{[^;\n]*\})`)
872 submitWord = regexp.MustCompile(`submit:(\{[^;\n]*\})`)
873 captureName = regexp.MustCompile(`/render/([0-9]+-(?:base|work|diff)-[0-9]+\.png)`)
874 captureRef = regexp.MustCompile(`\$cap([0-9]+)`)
875)
876
877// designer plays a Design step: Engineering's edits, then its renders
878// and its submission.
879func (f *fake) designer(prompt string, turn int, emit func(any)) string {
880 reply := f.engineer(prompt, turn, emit)
881 prompt = StepMarkerText(prompt)
882 use := func(id, tool string, raw string) (string, bool) {
883 var input map[string]any
884 if json.Unmarshal([]byte(raw), &input) != nil {
885 return "the fixture's input is not a JSON object", true
886 }
887 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__" + tool, "input": input}}}, "uuid": "assistant-" + id})
888 text, isError := f.callTool(id, tool, input)
889 emit(map[string]any{"type": "user", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"role": "user", "content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "content": text, "is_error": isError}}}, "uuid": "user-" + id})
890 return text, isError
891 }
892 var caps, notes []string
893 for i, m := range DistinctStepMarkers(renderWord, prompt) {
894 text, isError := use(fmt.Sprintf("toolu_fake_%d_dr%d", turn, i), "render_page", m[1])
895 if isError {
896 notes = append(notes, "[render_page refused: "+text+"]")
897 continue
898 }
899 var got []string
900 for _, c := range captureName.FindAllStringSubmatch(text, -1) {
901 if !slices.Contains(caps, c[1]) {
902 caps, got = append(caps, c[1]), append(got, c[1])
903 }
904 }
905 notes = append(notes, "[render_page rendered "+strings.Join(got, ",")+"]")
906 }
907 for i, m := range DistinctStepMarkers(submitWord, prompt) {
908 input := captureRef.ReplaceAllStringFunc(m[1], func(ref string) string {
909 n, _ := strconv.Atoi(strings.TrimPrefix(ref, "$cap"))
910 if n >= 1 && n <= len(caps) {
911 return caps[n-1]
912 }
913 return ref
914 })
915 text, _ := use(fmt.Sprintf("toolu_fake_%d_ds%d", turn, i), "submit_candidate", input)
916 notes = append(notes, "[submit_candidate: "+text+"]")
917 }
918 if len(notes) == 0 {
919 return reply
920 }
921 return reply + " " + strings.Join(notes, " ")
922}
923
924// readTool shows a Read of path as the CLI streams it (the read itself
925// needs no permission inside the workspace).
926func (f *fake) readTool(id, path string, emit func(any)) {
927 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": "Read", "input": map[string]any{"file_path": path}}}}, "uuid": "assistant-" + id})
928}
929
930var (
931 reviewChanges = regexp.MustCompile(`review:changes:([^|\n]+)\|([0-9]+)\|([^\n;]*)`)
932 reviewNeed = regexp.MustCompile(`review:need:([^|\n]+)\|([^|\n]+)\|([^\n;]*)`)
933 reviewWrite = regexp.MustCompile(`review:write:([^\s]+)`)
934 reviewSleep = regexp.MustCompile(`reviewsleep:([0-9]+)`)
935)
936
937// reviewer plays a Review step: reads what the words name in the
938// working directory and gives its verdict through submit_review.
939func (f *fake) reviewer(prompt string, turn int, emit func(any)) string {
940 prompt = StepMarkerText(prompt)
941 for i, m := range append(DistinctStepMarkers(reviewNeed, prompt), DistinctStepMarkers(reviewChanges, prompt)...) {
942 f.readTool(fmt.Sprintf("toolu_fake_%d_rr%d", turn, i), filepath.Join("/workspace", filepath.Clean("/"+m[1])), emit)
943 }
944 if m := reviewSleep.FindStringSubmatch(prompt); m != nil {
945 ms, _ := strconv.Atoi(m[1])
946 time.Sleep(time.Duration(ms) * time.Millisecond)
947 }
948 unfold := strings.NewReplacer("~", "|", "=", ":")
949 verdict, summary := "approve", "The change does what the task asks."
950 findings := []map[string]any{}
951 var notes []string
952 for i, m := range DistinctStepMarkers(reviewWrite, prompt) {
953 id := fmt.Sprintf("toolu_fake_%d_rw%d", turn, i)
954 path := filepath.Join("/workspace", filepath.Clean("/"+m[1]))
955 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": "Write", "input": map[string]any{"file_path": path, "content": "x"}}}}, "uuid": "assistant-" + id})
956 text, isError := f.callTool(id, "permission", map[string]any{"tool_name": "Write", "tool_use_id": id, "input": map[string]any{"file_path": path, "content": "x"}})
957 allowed := !isError && strings.Contains(text, `"allow"`)
958 if allowed {
959 _ = os.WriteFile(m[1], []byte("x"), 0644)
960 }
961 notes = append(notes, fmt.Sprintf("Write to %s was %s.", m[1], map[bool]string{true: "allowed", false: "denied"}[allowed]))
962 }
963 for _, m := range DistinctStepMarkers(reviewChanges, prompt) {
964 line, _ := strconv.Atoi(m[2])
965 verdict, summary = "changes_requested", "One thing needs changing."
966 findings = append(findings, map[string]any{"path": m[1], "line": line, "text": unfold.Replace(m[3])})
967 }
968 for _, m := range DistinctStepMarkers(reviewNeed, prompt) {
969 raw, err := os.ReadFile(m[1])
970 if err != nil || !strings.Contains(string(raw), m[2]) {
971 verdict, summary = "changes_requested", "Not done yet."
972 findings = append(findings, map[string]any{"path": m[1], "line": 1, "text": unfold.Replace(m[3])})
973 }
974 }
975 summary = strings.TrimSpace(summary + " " + strings.Join(notes, " "))
976 notes = nil
977 if !strings.Contains(prompt, "review:silent") {
978 id := fmt.Sprintf("toolu_fake_%d_rv", turn)
979 headline := "Approved."
980 if verdict == "changes_requested" {
981 headline = "Asked for one more change."
982 }
983 input := map[string]any{"verdict": verdict, "headline": headline, "summary": summary, "findings": findings}
984 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__submit_review", "input": input}}}, "uuid": "assistant-" + id})
985 text, isError := f.callTool(id, "submit_review", input)
986 if isError {
987 notes = append(notes, "[submit_review failed: "+text+"]")
988 }
989 }
990 return strings.TrimSpace(summary + " " + strings.Join(notes, " "))
991}
992
993var (
994 keepWord = regexp.MustCompile(`keep:([^|\n]+)\|([^|\n]+)\|([^;\n]*)`)
995 summaryWord = regexp.MustCompile(`summary:([^\n]*)`)
996 factWord = regexp.MustCompile(`fact:([^|\n]+)\|([^|\n]+)\|([^\s;]*)`)
997 gapWord = regexp.MustCompile(`gap:([^;\n]*)`)
998 imageWord = regexp.MustCompile(`image:(\S+)`)
999 rawFindings = regexp.MustCompile(`findings:raw:([^\n]*)`)
1000 keptRef = regexp.MustCompile(`\$kept([0-9]*)`)
1001)
1002
1003// researcher plays a Research step: keep_image for each keep word, then
1004// submit_findings built from the prompt's words.
1005func (f *fake) researcher(prompt string, turn int, emit func(any)) string {
1006 use := func(id, tool string, input any) (string, bool) {
1007 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__" + tool, "input": input}}}, "uuid": "assistant-" + id})
1008 var args map[string]any
1009 raw, _ := json.Marshal(input)
1010 _ = json.Unmarshal(raw, &args)
1011 text, isError := f.callTool(id, tool, args)
1012 emit(map[string]any{"type": "user", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"role": "user", "content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "content": text, "is_error": isError}}}, "uuid": "user-" + id})
1013 return text, isError
1014 }
1015 var kept, notes []string
1016 for i, m := range keepWord.FindAllStringSubmatch(prompt, -1) {
1017 text, isError := use(fmt.Sprintf("toolu_fake_%d_rk%d", turn, i), "keep_image", map[string]any{"source_id": strings.TrimSpace(m[1]), "role": strings.TrimSpace(m[2]), "description": strings.TrimSpace(m[3])})
1018 if isError {
1019 notes = append(notes, "[keep_image failed: "+text+"]")
1020 continue
1021 }
1022 kept = append(kept, strings.TrimSpace(text))
1023 }
1024 resolve := func(s string) string {
1025 return keptRef.ReplaceAllStringFunc(s, func(ref string) string {
1026 n, _ := strconv.Atoi(strings.TrimPrefix(ref, "$kept"))
1027 switch {
1028 case n == 0 && len(kept) > 0:
1029 return kept[len(kept)-1]
1030 case n > 0 && n <= len(kept):
1031 return kept[n-1]
1032 }
1033 return ref
1034 })
1035 }
1036 reply := "Research done."
1037 if len(kept) > 0 {
1038 reply += " kept " + strings.Join(kept, ", ") + "."
1039 }
1040 submissions := 1
1041 if strings.Contains(prompt, "findings:silent") {
1042 submissions = 0
1043 } else if strings.Contains(prompt, "findings:twice") {
1044 submissions = 2
1045 }
1046 var input any
1047 if m := rawFindings.FindStringSubmatch(prompt); m != nil {
1048 input = json.RawMessage(strings.TrimSpace(m[1]))
1049 } else {
1050 findings := map[string]any{"summary": "", "facts": []any{}, "images": []any{}, "gaps": []any{}}
1051 if m := summaryWord.FindStringSubmatch(prompt); m != nil {
1052 findings["summary"] = strings.TrimSpace(m[1])
1053 }
1054 for _, m := range factWord.FindAllStringSubmatch(prompt, -1) {
1055 sources := []any{}
1056 for _, src := range strings.Split(m[3], ",") {
1057 if src = strings.TrimSpace(src); src != "" {
1058 sources = append(sources, src)
1059 }
1060 }
1061 findings["facts"] = append(findings["facts"].([]any), map[string]any{"label": strings.TrimSpace(m[1]), "value": strings.TrimSpace(m[2]), "sources": sources})
1062 }
1063 for _, m := range gapWord.FindAllStringSubmatch(prompt, -1) {
1064 findings["gaps"] = append(findings["gaps"].([]any), strings.TrimSpace(m[1]))
1065 }
1066 for _, m := range imageWord.FindAllStringSubmatch(prompt, -1) {
1067 findings["images"] = append(findings["images"].([]any), resolve(m[1]))
1068 }
1069 input = findings
1070 }
1071 for i := 0; i < submissions; i++ {
1072 text, isError := use(fmt.Sprintf("toolu_fake_%d_rf%d", turn, i), "submit_findings", input)
1073 if isError {
1074 notes = append(notes, "[submit_findings failed: "+text+"]")
1075 } else {
1076 notes = append(notes, text)
1077 }
1078 }
1079 return strings.TrimSpace(reply + " " + strings.Join(notes, " "))
1080}
1081
1082var (
1083 askRead = regexp.MustCompile(`ask:read:([^\s]+)`)
1084 askWrite = regexp.MustCompile(`ask:write:([^\s]+)`)
1085 askSleep = regexp.MustCompile(`asksleep:([0-9]+)`)
1086)
1087
1088// answer plays a resumed step session answering a question.
1089func (f *fake) answer(question string, turn int, emit func(any)) string {
1090 parts := []string{"From my session: " + f.lastReply()}
1091 use := func(id, tool string, input map[string]any) {
1092 if f.partial {
1093 emit(map[string]any{"type": "stream_event", "session_id": f.session, "parent_tool_use_id": nil, "event": map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "tool_use", "id": id, "name": tool, "input": map[string]any{}}}, "uuid": "start-" + id})
1094 }
1095 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": "msg_" + id, "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": tool, "input": input}}}, "uuid": "assistant-" + id})
1096 }
1097 allowed := func(id, tool string, input map[string]any) bool {
1098 text, isError := f.callTool(id, "permission", map[string]any{"tool_name": tool, "tool_use_id": id, "input": input})
1099 return !isError && strings.Contains(text, `"allow"`)
1100 }
1101 if strings.Contains(question, "ask:git") {
1102 id := fmt.Sprintf("toolu_fake_%d_ag", turn)
1103 use(id, "mcp__equipo__git_diff", map[string]any{})
1104 text, isError := f.callTool(id, "git_diff", map[string]any{})
1105 line := "(no change)"
1106 for _, l := range strings.Split(text, "\n") {
1107 if strings.HasPrefix(l, "+") && !strings.HasPrefix(l, "+++") {
1108 line = l
1109 break
1110 }
1111 }
1112 if isError {
1113 line = "[git_diff failed: " + text + "]"
1114 }
1115 parts = append(parts, "The change: "+line)
1116 }
1117 for i, m := range askRead.FindAllStringSubmatch(question, -1) {
1118 id := fmt.Sprintf("toolu_fake_%d_ar%d", turn, i)
1119 input := map[string]any{"file_path": filepath.Join(workspaceRoot(), filepath.Clean("/"+m[1]))}
1120 use(id, "Read", input)
1121 if !allowed(id, "Read", input) {
1122 parts = append(parts, "Read of "+m[1]+" was denied.")
1123 continue
1124 }
1125 raw, err := os.ReadFile(m[1])
1126 first, _, _ := strings.Cut(string(raw), "\n")
1127 if err != nil {
1128 first = "unreadable"
1129 }
1130 parts = append(parts, m[1]+" starts: "+first)
1131 }
1132 for i, m := range askWrite.FindAllStringSubmatch(question, -1) {
1133 id := fmt.Sprintf("toolu_fake_%d_aw%d", turn, i)
1134 input := map[string]any{"file_path": filepath.Join(workspaceRoot(), filepath.Clean("/"+m[1])), "content": "x"}
1135 use(id, "Write", input)
1136 if allowed(id, "Write", input) {
1137 if os.WriteFile(m[1], []byte("x"), 0644) == nil {
1138 parts = append(parts, "Write to "+m[1]+" was allowed and written.")
1139 } else {
1140 parts = append(parts, "Write to "+m[1]+" was allowed but failed.")
1141 }
1142 continue
1143 }
1144 parts = append(parts, "Write to "+m[1]+" was denied. I can't change anything from here.")
1145 }
1146 if m := askSleep.FindStringSubmatch(question); m != nil {
1147 ms, _ := strconv.Atoi(m[1])
1148 time.Sleep(time.Duration(ms) * time.Millisecond)
1149 }
1150 return strings.Join(parts, " ")
1151}
1152
1153// questionText is the person's question in a question's prompt: the
1154// quoted data after "The person's question: " (a quoted line, or a
1155// delimited block), then whatever follows it.
1156func questionText(prompt string) string {
1157 _, rest, ok := strings.Cut(prompt, "The person's question: ")
1158 if !ok {
1159 _, rest, _ = strings.Cut(prompt, "Question: ")
1160 return rest
1161 }
1162 if q, err := strconv.QuotedPrefix(rest); err == nil {
1163 v, _ := strconv.Unquote(q)
1164 return v + rest[len(q):]
1165 }
1166 if strings.HasPrefix(rest, "\n<EQUIPO_DATA_") {
1167 open := strings.Index(rest[1:], ">\n") + 1
1168 nonce := rest[2:strings.Index(rest, " bytes=")]
1169 if end := strings.Index(rest, "\n</"+nonce+">"); open > 0 && end > open {
1170 return rest[open+2:end] + rest[end+len("\n</"+nonce+">"):]
1171 }
1172 }
1173 return rest
1174}
1175
1176// lastReply is the newest reply the session's transcript holds.
1177func (f *fake) lastReply() string {
1178 raw, err := os.ReadFile(f.transcript())
1179 if err != nil {
1180 return "(nothing)"
1181 }
1182 last := "(nothing)"
1183 for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
1184 var v struct {
1185 Type string `json:"type"`
1186 Text string `json:"text"`
1187 }
1188 if json.Unmarshal([]byte(line), &v) == nil && v.Type == "assistant" {
1189 last = v.Text
1190 }
1191 }
1192 return last
1193}
1194
1195// callTool calls the Equipo MCP server the way the CLI does, with the
1196// tool-use id in _meta.
1197func (f *fake) callTool(id, name string, input map[string]any) (string, bool) {
1198 if f.mcpIn == nil {
1199 return "no MCP server", true
1200 }
1201 f.callID++
1202 raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 100 + f.callID, "method": "tools/call", "params": map[string]any{"name": name, "arguments": input, "_meta": map[string]any{"claudecode/toolUseId": id}}})
1203 if _, err := f.mcpIn.Write(append(raw, '\n')); err != nil {
1204 return "MCP write failed", true
1205 }
1206 line, err := f.mcpOut.ReadBytes('\n')
1207 var reply struct {
1208 Result struct {
1209 Content []struct {
1210 Text string `json:"text"`
1211 } `json:"content"`
1212 IsError bool `json:"isError"`
1213 } `json:"result"`
1214 Error *struct{} `json:"error"`
1215 }
1216 if err != nil || json.Unmarshal(line, &reply) != nil || reply.Error != nil || len(reply.Result.Content) == 0 {
1217 return "MCP call failed", true
1218 }
1219 return reply.Result.Content[0].Text, reply.Result.IsError
1220}
1221
1222func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
1223 if f.resume {
1224 if _, err := os.Stat(f.transcript()); err != nil {
1225 fmt.Fprintf(stderr, "No conversation found with session ID: %s\n", f.session)
1226 return 1
1227 }
1228 }
1229 status := f.connectMCP()
1230 out := json.NewEncoder(stdout)
1231 // requests counts the turn's model requests, as num_turns does: one
1232 // for the reply and one more for each tool the model called.
1233 requests := 1
1234 emit := func(v any) {
1235 raw, _ := json.Marshal(v)
1236 if bytes.Contains(raw, []byte(`"type":"assistant"`)) {
1237 requests += bytes.Count(raw, []byte(`"type":"tool_use"`))
1238 }
1239 _ = out.Encode(v)
1240 }
1241 scan := bufio.NewScanner(stdin)
1242 scan.Buffer(make([]byte, 0, 64<<10), 16<<20)
1243 served := 0
1244 for scan.Scan() {
1245 var in struct {
1246 Type string `json:"type"`
1247 Session string `json:"session_id"`
1248 Message struct {
1249 Role string `json:"role"`
1250 Content json.RawMessage `json:"content"`
1251 } `json:"message"`
1252 }
1253 if json.Unmarshal(scan.Bytes(), &in) != nil || in.Type != "user" || in.Message.Role != "user" {
1254 fmt.Fprintln(stderr, "Error: invalid stream-json input")
1255 return 1
1256 }
1257 prompt, images, err := userContent(in.Message.Content)
1258 if err != nil {
1259 fmt.Fprintln(stderr, "Error: invalid stream-json input")
1260 return 1
1261 }
1262 // The instance project block is reference data, not fixture commands.
1263 steering, _, _ := strings.Cut(prompt, "\n\nProjects available to this person,")
1264 // Steering words count only in the newest message, not the context.
1265 newest := steering
1266 if _, after, ok := strings.Cut(steering, "Newest message:\n"); ok {
1267 newest = after
1268 }
1269 // Words a failed turn left unanswered ride before it, as context.
1270 if _, after, ok := strings.Cut(newest, "The person's newest message:\n"); ok {
1271 newest = after
1272 }
1273 // A move-in or explore turn has no person message to steer by.
1274 steps, intro, settle := settling(prompt)
1275 if settle {
1276 newest = ""
1277 }
1278 turn := f.turns() + 1
1279 requests = 1
1280 // An Engineering step resumed from a kept session (a fix round)
1281 // says so, and reads its earlier transcript from the cache.
1282 cacheRead := 0
1283 if f.resume && strings.HasPrefix(prompt, "[Equipo: engineering]") {
1284 if info, err := os.Stat(f.transcript()); err == nil {
1285 cacheRead = int(info.Size() / 4)
1286 }
1287 }
1288 tools, session := append([]string{}, f.tools...), f.session
1289 if strings.Contains(newest, "badinit") {
1290 tools = append(tools, "Bash")
1291 }
1292 if strings.Contains(newest, "othersession") {
1293 session = "00000000-0000-4000-8000-0000000000ff"
1294 }
1295 emit(map[string]any{"type": "system", "subtype": "init", "cwd": "/workspace", "session_id": f.session, "tools": append(append([]string{}, f.native...), tools...), "mcp_servers": []any{map[string]string{"name": "equipo", "status": status}}, "model": f.model, "permissionMode": "default", "slash_commands": []string{}, "apiKeySource": "none", "claude_code_version": Version, "output_style": "default", "skills": []string{}, "plugins": []any{map[string]string{"name": "cc-plugin-agents-md", "path": "builtin", "source": "cc-plugin-agents-md@builtin"}, map[string]string{"name": "cc-plugin-plugin-authoring", "path": "builtin", "source": "cc-plugin-plugin-authoring@builtin"}}, "uuid": fmt.Sprintf("init-%d", turn)})
1296 byToken, ok := signedIn()
1297 if !ok {
1298 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_auth_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": "Invalid API key"}}}, "error": "authentication_failed", "uuid": fmt.Sprintf("assistant-%d", turn)})
1299 emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "Invalid API key", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
1300 continue
1301 }
1302 // A glance: one short line from the small model, no tools.
1303 if line, pause, fail, ok := Glance(prompt, f.resume || turn > 1); ok {
1304 time.Sleep(pause)
1305 f.record(prompt, line)
1306 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_glance_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": line}}}, "uuid": fmt.Sprintf("assistant-%d", turn)})
1307 subtype := "success"
1308 if fail {
1309 subtype = "error_during_execution"
1310 }
1311 emit(map[string]any{"type": "result", "subtype": subtype, "is_error": fail, "result": line, "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": len(prompt) / 4, "output_tokens": len(line) / 4}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
1312 continue
1313 }
1314 context := "fresh"
1315 if f.resume || turn > 1 {
1316 context = "resumed"
1317 }
1318 served++
1319 reply := fmt.Sprintf("Hello from the fake coordinator. Turn %d, %s session, process turn %d.", turn, context, served)
1320 if strings.Contains(newest, "accents") {
1321 reply = "Café con ñandú, señor. ☕ Ünïcödé 🎉 works."
1322 }
1323 if md, ok := markdownReply(newest); ok {
1324 reply = md
1325 }
1326 if strings.Contains(prompt, "Conversation so far") {
1327 reply += " I see the earlier conversation."
1328 }
1329 if seen := batchMessages(newest); len(seen) > 0 {
1330 reply += fmt.Sprintf(" You sent %d messages: %s.", len(seen), strings.Join(seen, "; "))
1331 } else if strings.Contains(steering, "\n\n") && !strings.Contains(steering, "Newest message") {
1332 reply += fmt.Sprintf(" You sent %d messages.", strings.Count(steering, "\n\n")+1)
1333 }
1334 if strings.Contains(prompt, "=== Your notebook") {
1335 reply += " (notebook in context)"
1336 }
1337 // limit:<email> refuses the turn on quota when this home's account
1338 // is that email (steplimit:<email> does so for an Engineering or Design step):
1339 // a rejected rate_limit_event with its reset, then an error result,
1340 // as the CLI reports a spent weekly limit.
1341 refuse := func() {
1342 reset := time.Now().Add(46 * time.Hour).Truncate(time.Hour).Unix()
1343 emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": map[string]any{"status": "rejected", "resetsAt": reset, "rateLimitType": "seven_day", "utilization": 1.0, "unifiedWindows": map[string]any{"seven_day": map[string]any{"utilization": 1.0, "resetsAt": reset, "status": "rejected"}}}, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
1344 emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "You've hit your weekly limit", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
1345 }
1346 if m := limitWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() {
1347 refuse()
1348 continue
1349 }
1350 // The runner's token check is refused on quota for an account
1351 // whose email starts "spent-", as for a spent weekly limit.
1352 check := prompt == CheckPrompt
1353 if check && strings.HasPrefix(accountEmail(), "spent-") {
1354 refuse()
1355 continue
1356 }
1357 // limitnoreset:<email> is a refusal with no reset time reported;
1358 // authrefused:<email> the provider refusing the credential.
1359 if m := noResetWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() {
1360 emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": map[string]any{"status": "rejected"}, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
1361 emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "limit reached", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
1362 continue
1363 }
1364 if m := authWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() {
1365 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_auth_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": "Invalid API key"}}}, "error": "authentication_failed", "uuid": fmt.Sprintf("assistant-%d", turn)})
1366 emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "Invalid API key", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
1367 continue
1368 }
1369 if stepLimited(prompt) {
1370 if l := limitLeave.FindStringSubmatch(prompt); l != nil {
1371 _ = os.WriteFile(filepath.Clean("/" + l[1])[1:], []byte("left by a refused attempt\n"), 0644)
1372 }
1373 refuse()
1374 continue
1375 }
1376 if m := reviewLimitWord.FindStringSubmatch(prompt); m != nil && m[1] == accountEmail() && strings.HasPrefix(prompt, "[Equipo: review]") {
1377 refuse()
1378 continue
1379 }
1380 // reviewauth:<email> refuses a Review step's credential.
1381 if m := reviewAuthWord.FindStringSubmatch(prompt); m != nil && m[1] == accountEmail() && strings.HasPrefix(prompt, "[Equipo: review]") {
1382 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_auth_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": "Invalid API key"}}}, "error": "authentication_failed", "uuid": fmt.Sprintf("assistant-%d", turn)})
1383 emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "Invalid API key", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
1384 continue
1385 }
1386 if strings.HasPrefix(prompt, "[Equipo: engineering]") {
1387 newest = ""
1388 reply = f.engineer(prompt, turn, emit)
1389 if f.resume {
1390 reply += " (resumed session)"
1391 }
1392 }
1393 if strings.HasPrefix(prompt, "[Equipo: design]") {
1394 newest = ""
1395 reply = f.designer(prompt, turn, emit)
1396 }
1397 if strings.HasPrefix(prompt, "[Equipo: review]") {
1398 newest = ""
1399 reply = f.reviewer(prompt, turn, emit)
1400 }
1401 if strings.HasPrefix(prompt, "[Equipo: research]") {
1402 newest = ""
1403 reply = f.researcher(prompt, turn, emit)
1404 }
1405 if strings.HasPrefix(prompt, "[Equipo: question]") {
1406 newest = ""
1407 reply = f.answer(questionText(prompt), turn, emit)
1408 }
1409 if settle {
1410 reply = intro
1411 pause := time.Duration(0)
1412 if m := moveInPause.FindStringSubmatch(prompt); m != nil {
1413 ms, _ := strconv.Atoi(m[1])
1414 pause = time.Duration(ms) * time.Millisecond
1415 }
1416 var read []string
1417 for i, st := range steps {
1418 time.Sleep(pause)
1419 id := fmt.Sprintf("toolu_fake_%d_mi%d", turn, i)
1420 if f.partial {
1421 emit(map[string]any{"type": "stream_event", "session_id": f.session, "parent_tool_use_id": nil, "event": map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__" + st.name, "input": map[string]any{}}}, "uuid": fmt.Sprintf("tool-%d-mi%d", turn, i)})
1422 }
1423 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_tool_%d_mi%d", turn, i), "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__" + st.name, "input": st.input}}}, "uuid": fmt.Sprintf("assistant-tool-%d-mi%d", turn, i)})
1424 text, isError := f.callTool(id, st.name, st.input)
1425 emit(map[string]any{"type": "user", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"role": "user", "content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "content": text, "is_error": isError}}}, "uuid": fmt.Sprintf("user-tool-%d-mi%d", turn, i)})
1426 if st.name == "read_file" && !isError {
1427 read = append(read, st.input["repo"].(string))
1428 }
1429 if st.name == "write_note" && isError {
1430 reply += " [write_note failed: " + text + "]"
1431 }
1432 }
1433 if len(read) > 0 {
1434 reply += " I read " + strings.Join(read, ", ") + "."
1435 }
1436 }
1437 if strings.Contains(newest, "think") && f.partial {
1438 emit(map[string]any{"type": "stream_event", "session_id": f.session, "parent_tool_use_id": nil, "event": map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "thinking", "thinking": ""}}, "uuid": fmt.Sprintf("think-%d", turn)})
1439 time.Sleep(50 * time.Millisecond)
1440 }
1441 // obey: a gullible model reads each attached file and follows any
1442 // tool words in it, as a prompt injection would have it.
1443 steer := newest
1444 if newest == "Create a new project called oficina/suite-site" {
1445 steer = "tool:create_project:oficina/suite-site"
1446 }
1447 if strings.Contains(newest, "obey") {
1448 for i, path := range attachmentPath.FindAllString(prompt, -1) {
1449 text, isError := f.callTool(fmt.Sprintf("toolu_fake_%d_obey%d", turn, i), "read_file", map[string]any{"repo": "attachments", "path": path})
1450 reply += fmt.Sprintf(" [read %s: error=%v]", path, isError)
1451 if !isError {
1452 steer += "\n" + text
1453 }
1454 }
1455 }
1456 // A job's news steers only by what it says (news); an answer to
1457 // the Coordinator's question by what it planned for one.
1458 newsSteer, newsReply, isNews := news(prompt)
1459 if isNews {
1460 steer = newsSteer
1461 }
1462 if strings.Contains(newest, answerPrefix) {
1463 steer += "\n" + f.onAnswer()
1464 }
1465 for i, m := range toolWord.FindAllStringSubmatch(steer, -1) {
1466 id := fmt.Sprintf("toolu_fake_%d_%d", turn, i)
1467 if f.partial {
1468 emit(map[string]any{"type": "stream_event", "session_id": f.session, "parent_tool_use_id": nil, "event": map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__" + m[1], "input": map[string]any{}}}, "uuid": fmt.Sprintf("tool-%d-%d", turn, i)})
1469 }
1470 input := toolInput(m[1], strings.NewReplacer("$task", f.lastTask, "$similar", f.lastSimilar).Replace(m[2]))
1471 // reword: each account words its writes its own way, as another
1472 // model taking the turn over would.
1473 if strings.Contains(newest, "reword") {
1474 for _, k := range []string{"question", "title", "brief"} {
1475 if v, ok := input[k].(string); ok {
1476 input[k] = v + " (as " + accountEmail() + " puts it)"
1477 }
1478 }
1479 }
1480 if m[1] == "write_note" && strings.HasPrefix(strings.TrimSpace(m[2]), "+") {
1481 input = f.keepAll(fmt.Sprintf("toolu_fake_%d_%d_read", turn, i), input)
1482 }
1483 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_tool_%d_%d", turn, i), "type": "message", "role": "assistant", "content": []any{map[string]any{"type": "tool_use", "id": id, "name": "mcp__equipo__" + m[1], "input": input}}}, "uuid": fmt.Sprintf("assistant-tool-%d-%d", turn, i)})
1484 text, isError := f.callTool(id, m[1], input)
1485 emit(map[string]any{"type": "user", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"role": "user", "content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "content": text, "is_error": isError}}}, "uuid": fmt.Sprintf("user-tool-%d-%d", turn, i)})
1486 if m[1] == "record_task" && !isError {
1487 var v struct {
1488 Task string `json:"task"`
1489 Similar []struct {
1490 Task string `json:"task"`
1491 } `json:"similar"`
1492 }
1493 if json.Unmarshal([]byte(text), &v) == nil && v.Task != "" {
1494 f.lastTask = v.Task
1495 }
1496 if len(v.Similar) > 0 {
1497 f.lastSimilar = v.Similar[0].Task
1498 }
1499 }
1500 reply += fmt.Sprintf(" [%s: %s]", m[1], text)
1501 }
1502 for _, im := range images {
1503 reply += " [image " + im + "]"
1504 }
1505 // probe: try each attached path inside the namespace.
1506 if strings.Contains(newest, "probe") {
1507 for _, path := range attachmentPath.FindAllString(prompt, -1) {
1508 reply += probeFile(path)
1509 }
1510 }
1511 // limitafter:<email>: the tools ran, then the limit hit.
1512 if m := limitAfterWord.FindStringSubmatch(newest); m != nil && m[1] == accountEmail() {
1513 refuse()
1514 continue
1515 }
1516 if strings.Contains(prompt, "Already done in this turn") {
1517 reply += " (earlier effects in context)"
1518 }
1519 if m := pauseWord.FindStringSubmatch(newest); m != nil {
1520 ms, _ := strconv.Atoi(m[1])
1521 time.Sleep(time.Duration(ms) * time.Millisecond)
1522 }
1523 pause := time.Duration(0)
1524 if m := sleepWord.FindStringSubmatch(newest); m != nil {
1525 ms, _ := strconv.Atoi(m[1])
1526 pause = time.Duration(ms) * time.Millisecond
1527 }
1528 if byToken {
1529 reply += " (signed in by token)"
1530 }
1531 if isNews {
1532 // Nothing for the person but a stop it could not get past.
1533 reply = newsReply
1534 }
1535 chunks := split(reply, chunkCount(newest))
1536 for i, chunk := range chunks {
1537 if f.partial {
1538 emit(map[string]any{"type": "stream_event", "session_id": f.session, "parent_tool_use_id": nil, "event": map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]string{"type": "text_delta", "text": chunk}}, "uuid": fmt.Sprintf("delta-%d-%d", turn, i)})
1539 }
1540 if pause > 0 && (i == 0 || strings.Contains(newest, "slowstream")) {
1541 time.Sleep(pause)
1542 }
1543 if i == 0 && strings.Contains(newest, "crash") {
1544 return 3
1545 }
1546 }
1547 f.record(prompt, reply)
1548 emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_fake_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": reply}}, "usage": map[string]int{"input_tokens": len(prompt) / 4, "output_tokens": len(reply) / 4}}, "uuid": fmt.Sprintf("assistant-%d", turn)})
1549 info := map[string]any{"status": "allowed", "resetsAt": time.Now().Add(100 * time.Hour).Truncate(time.Hour).Unix(), "rateLimitType": "seven_day", "utilization": 0.25}
1550 if check {
1551 // The check's answer carries the windows, as the CLI's does.
1552 info["unifiedWindows"] = map[string]any{
1553 "five_hour": map[string]any{"utilization": 0.12, "resetsAt": time.Now().Add(3 * time.Hour).Truncate(time.Hour).Unix(), "status": "allowed"},
1554 "seven_day": map[string]any{"utilization": 0.25, "resetsAt": time.Now().Add(100 * time.Hour).Truncate(time.Hour).Unix(), "status": "allowed"},
1555 }
1556 }
1557 emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": info, "uuid": fmt.Sprintf("limit-%d", turn), "session_id": f.session})
1558 failed := strings.Contains(newest, "fail")
1559 subtype := "success"
1560 if failed {
1561 subtype = "error_during_execution"
1562 }
1563 usage := map[string]int{"input_tokens": len(prompt) / 4, "output_tokens": len(reply) / 4}
1564 if cacheRead > 0 {
1565 usage["cache_read_input_tokens"] = cacheRead
1566 }
1567 emit(map[string]any{"type": "result", "subtype": subtype, "is_error": failed, "result": reply, "session_id": session, "num_turns": requests, "usage": usage, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)})
1568 }
1569 return 0
1570}
1571
1572var moveInPause = regexp.MustCompile(`movein-pause:([0-9]+)`)
1573
1574// batchHeader opens each message of a turn that carries several, as the
1575// instance writes them: "Message 2 of 3" and, when it has files,
1576// " (attached: a.png, b.md)", then a colon and the message.
1577var batchHeader = regexp.MustCompile(`(?m)^Message ([0-9]+) of ([0-9]+)(?: \(attached: ([^)\n]*)\))?:$`)
1578
1579// batchMessages reads the separate messages of a turn that carries
1580// several, in the order the prompt gives them: each message's first line,
1581// with its files in brackets. Nothing when the turn has one message.
1582func batchMessages(newest string) []string {
1583 heads := batchHeader.FindAllStringSubmatchIndex(newest, -1)
1584 out := make([]string, 0, len(heads))
1585 for i, h := range heads {
1586 end := len(newest)
1587 if i+1 < len(heads) {
1588 end = heads[i+1][0]
1589 }
1590 body := strings.TrimSpace(newest[h[1]:end])
1591 first, _, _ := strings.Cut(body, "\n")
1592 if h[6] >= 0 {
1593 first += " [" + newest[h[6]:h[7]] + "]"
1594 }
1595 out = append(out, newest[h[2]:h[3]]+"/"+newest[h[4]:h[5]]+" "+first)
1596 }
1597 return out
1598}
1599
1600// attachmentPath is an attached file's path in the namespace.
1601var attachmentPath = regexp.MustCompile(`/workspace/attachments/at_[a-z0-9]+/[^\s:]+`)
1602
1603// userContent reads a user frame's content: a string, or blocks of text
1604// and images (source base64), as the Agent SDK's streaming input sends
1605// them. Each image is described by type, size and the start of its
1606// SHA-256, so a test sees exactly what arrived.
1607func userContent(raw json.RawMessage) (string, []string, error) {
1608 var text string
1609 if json.Unmarshal(raw, &text) == nil {
1610 return text, nil, nil
1611 }
1612 var blocks []struct {
1613 Type string `json:"type"`
1614 Text string `json:"text"`
1615 Source *struct {
1616 Type string `json:"type"`
1617 MediaType string `json:"media_type"`
1618 Data []byte `json:"data"`
1619 } `json:"source"`
1620 }
1621 if err := json.Unmarshal(raw, &blocks); err != nil {
1622 return "", nil, err
1623 }
1624 var parts, images []string
1625 for _, b := range blocks {
1626 switch b.Type {
1627 case "text":
1628 parts = append(parts, b.Text)
1629 case "image":
1630 if b.Source == nil || b.Source.Type != "base64" || len(b.Source.Data) == 0 {
1631 return "", nil, fmt.Errorf("image block")
1632 }
1633 images = append(images, describeImage(b.Source.MediaType, b.Source.Data))
1634 default:
1635 return "", nil, fmt.Errorf("content block %q", b.Type)
1636 }
1637 }
1638 return strings.Join(parts, "\n"), images, nil
1639}
1640
1641// describeImage is "<media type> <w>x<h> sha256:<12 hex>".
1642func describeImage(media string, data []byte) string {
1643 sum := sha256.Sum256(data)
1644 w, h := 0, 0
1645 if c, _, err := image.DecodeConfig(bytes.NewReader(data)); err == nil {
1646 w, h = c.Width, c.Height
1647 }
1648 return fmt.Sprintf("%s %dx%d sha256:%s", media, w, h, hex.EncodeToString(sum[:6]))
1649}
1650
1651// DescribeImage is describeImage for the codex fake and tests.
1652func DescribeImage(media string, data []byte) string { return describeImage(media, data) }
1653
1654// probeFile reads an attached file inside the namespace and tries to
1655// change it and to plant a file beside it, saying what happened.
1656func probeFile(path string) string {
1657 out := " [file " + path + ": "
1658 data, err := os.ReadFile(path)
1659 if err != nil {
1660 out += "unreadable"
1661 } else {
1662 sum := sha256.Sum256(data)
1663 out += fmt.Sprintf("read %d bytes sha256:%s", len(data), hex.EncodeToString(sum[:6]))
1664 }
1665 if w, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0); err == nil {
1666 w.Close()
1667 out += ", WRITABLE"
1668 } else {
1669 out += ", write refused"
1670 }
1671 planted := filepath.Join(filepath.Dir(path), "planted.txt")
1672 if w, err := os.OpenFile(planted, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600); err == nil {
1673 w.Close()
1674 os.Remove(planted)
1675 out += ", CREATABLE"
1676 } else {
1677 out += ", create refused"
1678 }
1679 return out + "]"
1680}
1681
1682// limitWord is limit:<email>.
1683var limitWord = regexp.MustCompile(`\blimit:([^\s|]+@[^\s|]+[a-z])`)
1684
1685var limitAfterWord = regexp.MustCompile(`\blimitafter:([^\s|]+@[^\s|]+[a-z])`)
1686var noResetWord = regexp.MustCompile(`\blimitnoreset:([^\s|]+@[^\s|]+[a-z])`)
1687var authWord = regexp.MustCompile(`\bauthrefused:([^\s|]+@[^\s|]+[a-z])`)
1688
1689// reviewLimitWord is reviewlimit:<email>, for a Review step only.
1690var reviewLimitWord = regexp.MustCompile(`\breviewlimit:([^\s|]+@[^\s|]+[a-z])`)
1691
1692// reviewAuthWord is reviewauth:<email>, for a Review step only.
1693var reviewAuthWord = regexp.MustCompile(`\breviewauth:([^\s|]+@[^\s|]+[a-z])`)
1694
1695// stepLimitWord is steplimit:<email>, for an Engineering or Design step
1696// only; any of them may name this account.
1697var stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`)
1698
1699// stepLimited: the step's prompt refuses this account on quota.
1700func stepLimited(prompt string) bool {
1701 if !strings.HasPrefix(prompt, "[Equipo: engineering]") && !strings.HasPrefix(prompt, "[Equipo: design]") {
1702 return false
1703 }
1704 for _, m := range stepLimitWord.FindAllStringSubmatch(prompt, -1) {
1705 if m[1] == accountEmail() {
1706 return true
1707 }
1708 }
1709 return false
1710}
1711
1712const (
1713 tokenEnv = "CLAUDE_CODE_OAUTH_TOKEN"
1714 tokenFDEnv = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR"
1715)
1716
1717// CheckPrompt is the runner's token check, word for word (thin's
1718// tokenCheckPrompt).
1719const CheckPrompt = "Reply with the single word OK."
1720
1721// Token is a setup token the fake accepts, for email ("" for a token
1722// whose account the CLI does not name). Any other value is refused.
1723func Token(email string) string {
1724 return "sk-ant-oat01-fake-" + hex.EncodeToString([]byte(email)) + "-ok"
1725}
1726
1727// Accepts reports whether a turn on tok would run: whether Token made it.
1728func Accepts(tok string) bool {
1729 _, ok := tokenEmail(tok)
1730 return ok
1731}
1732
1733// tokenEmail reads a token Token made.
1734func tokenEmail(tok string) (string, bool) {
1735 mid, ok := strings.CutPrefix(tok, "sk-ant-oat01-fake-")
1736 if !ok {
1737 return "", false
1738 }
1739 if mid, ok = strings.CutSuffix(mid, "-ok"); !ok {
1740 return "", false
1741 }
1742 email, err := hex.DecodeString(mid)
1743 return string(email), err == nil
1744}
1745
1746// signedIn is whether a turn may run: on a token, one Token made; else
1747// a login file in the home.
1748func signedIn() (byToken, ok bool) {
1749 if tok, set := os.LookupEnv(tokenEnv); set {
1750 _, ok = tokenEmail(tok)
1751 return true, ok
1752 }
1753 _, err := os.Stat(filepath.Join(home(), ".credentials.json"))
1754 return false, err == nil
1755}
1756
1757// accountEmail is the signed-in account of the home the fake runs in.
1758func accountEmail() string {
1759 if tok := os.Getenv(tokenEnv); tok != "" {
1760 if email, ok := tokenEmail(tok); ok && email != "" {
1761 return email
1762 }
1763 }
1764 var v struct {
1765 Account struct {
1766 Email string `json:"emailAddress"`
1767 } `json:"oauthAccount"`
1768 }
1769 raw, _ := os.ReadFile(filepath.Join(home(), ".claude.json"))
1770 _ = json.Unmarshal(raw, &v)
1771 return v.Account.Email
1772}
1773
1774var noteID = regexp.MustCompile(`\[(n[0-9]+)\]`)
1775
1776// keepAll reads the notebook and keeps every entry before the new ones.
1777func (f *fake) keepAll(id string, input map[string]any) map[string]any {
1778 text, _ := f.callTool(id, "read_notes", map[string]any{})
1779 entries := []map[string]string{}
1780 for _, m := range noteID.FindAllStringSubmatch(text, -1) {
1781 entries = append(entries, map[string]string{"keep": m[1]})
1782 }
1783 entries = append(entries, input["entries"].([]map[string]string)...)
1784 return map[string]any{"entries": entries}
1785}
1786
1787type step struct {
1788 name string
1789 input map[string]any
1790}
1791
1792// settling scripts a move-in or explore turn: the tool calls and the
1793// reply. Repositories are read from the prompt's lists ("name: summary").
1794func settling(prompt string) ([]step, string, bool) {
1795 listed := func(after string) []string {
1796 _, rest, ok := strings.Cut(prompt, after)
1797 if !ok {
1798 return nil
1799 }
1800 var out []string
1801 for _, line := range strings.Split(rest, "\n")[1:] {
1802 name, _, _ := strings.Cut(line, ":")
1803 name, _, _ = strings.Cut(name, " [")
1804 if line == "" || !strings.Contains(name, "/") || strings.Contains(name, " ") {
1805 break
1806 }
1807 out = append(out, name)
1808 }
1809 return out
1810 }
1811 note := func(title string, repos []string) step {
1812 entries := []map[string]string{{"source": "own", "text": title}}
1813 for _, r := range repos {
1814 entries = append(entries, map[string]string{"source": "repo", "repo": r, "path": "README.md", "text": r + " has a README."})
1815 }
1816 return step{"write_note", map[string]any{"entries": entries}}
1817 }
1818 switch {
1819 case strings.Contains(prompt, "[Equipo: moving in"):
1820 repos := listed("Repositories you can reach (name: what it is):")
1821 steps := []step{{"status", map[string]any{}}}
1822 for i, r := range repos {
1823 if i == 3 {
1824 break
1825 }
1826 steps = append(steps, step{"read_file", map[string]any{"repo": r, "path": "README.md"}})
1827 }
1828 steps = append(steps, note("Repositories I looked at:", repos[:min(len(repos), 3)]))
1829 return steps, fmt.Sprintf("Hi, I'm your coordinator. I can see %d repositories: %s.", len(repos), strings.Join(repos, ", ")), true
1830 case strings.Contains(prompt, "[Equipo: access changed]"):
1831 if strings.Contains(prompt, "Nothing changed after all") {
1832 return nil, "", true
1833 }
1834 repos := listed("Its repositories:")
1835 if len(repos) == 0 {
1836 return []step{note("Some access was removed.", nil)}, "I can no longer reach some of what I could; my notebook says so now.", true
1837 }
1838 var steps []step
1839 for _, r := range repos {
1840 steps = append(steps, step{"read_file", map[string]any{"repo": r, "path": "README.md"}})
1841 }
1842 steps = append(steps, note("Newly reachable:", repos))
1843 return steps, "Now I can also see " + strings.Join(repos, ", ") + ".", true
1844 }
1845 return nil, "", false
1846}
1847
1848// split cuts s into n parts on character boundaries, as the CLI streams
1849// whole characters.
1850func split(s string, n int) []string {
1851 runes := []rune(s)
1852 size := (len(runes) + n - 1) / n
1853 var out []string
1854 for len(runes) > size {
1855 out = append(out, string(runes[:size]))
1856 runes = runes[size:]
1857 }
1858 return append(out, string(runes))
1859}
1860
1861func (f *fake) turns() int {
1862 raw, err := os.ReadFile(f.transcript())
1863 if err != nil {
1864 return 0
1865 }
1866 return strings.Count(string(raw), `"type":"assistant"`)
1867}
1868
1869func (f *fake) record(prompt, reply string) {
1870 path := f.transcript()
1871 _ = os.MkdirAll(filepath.Dir(path), 0700)
1872 fh, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
1873 if err != nil {
1874 return
1875 }
1876 defer fh.Close()
1877 for _, line := range []map[string]string{{"type": "user", "text": prompt}, {"type": "assistant", "text": reply}} {
1878 raw, _ := json.Marshal(line)
1879 fh.Write(append(raw, '\n'))
1880 }
1881}
1882
1883// connectMCP starts the configured stdio server and completes the MCP
1884// handshake, as the CLI does before reporting a server connected.
1885func (f *fake) connectMCP() string {
1886 raw, err := os.ReadFile(f.mcpConfig)
1887 if err != nil {
1888 return "failed"
1889 }
1890 var cfg struct {
1891 Servers map[string]struct {
1892 Command string `json:"command"`
1893 Args []string `json:"args"`
1894 } `json:"mcpServers"`
1895 }
1896 if json.Unmarshal(raw, &cfg) != nil || len(cfg.Servers) != 1 {
1897 return "failed"
1898 }
1899 s, ok := cfg.Servers["equipo"]
1900 if !ok {
1901 return "failed"
1902 }
1903 cmd := exec.Command(s.Command, s.Args...)
1904 in, _ := cmd.StdinPipe()
1905 outPipe, _ := cmd.StdoutPipe()
1906 if cmd.Start() != nil {
1907 return "failed"
1908 }
1909 r := bufio.NewReader(outPipe)
1910 call := func(id int, method string, params any) bool {
1911 raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})
1912 if _, err := in.Write(append(raw, '\n')); err != nil {
1913 return false
1914 }
1915 line, err := r.ReadBytes('\n')
1916 var reply struct {
1917 Result json.RawMessage `json:"result"`
1918 }
1919 return err == nil && json.Unmarshal(line, &reply) == nil && len(reply.Result) > 0
1920 }
1921 if !call(1, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]string{"name": "fake-claude", "version": Version}}) {
1922 return "failed"
1923 }
1924 note, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"})
1925 in.Write(append(note, '\n'))
1926 raw, _ = json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": map[string]any{}})
1927 if _, err := in.Write(append(raw, '\n')); err != nil {
1928 return "failed"
1929 }
1930 line, err := r.ReadBytes('\n')
1931 var list struct {
1932 Result struct {
1933 Tools []struct {
1934 Name string `json:"name"`
1935 } `json:"tools"`
1936 } `json:"result"`
1937 }
1938 if err != nil || json.Unmarshal(line, &list) != nil {
1939 return "failed"
1940 }
1941 // The pinned CLI hides the permission callback from the model.
1942 for _, t := range list.Result.Tools {
1943 if t.Name != "permission" {
1944 f.tools = append(f.tools, "mcp__equipo__"+t.Name)
1945 }
1946 }
1947 f.mcpIn, f.mcpOut = in, r
1948 return "connected"
1949}
1950