// Package designstep is the Design step's tools on the runner (spec // 2026-11-28-dynamic-specialists.md, sections 1, 3 and 5; plan task 18): // render_page behind the instance's render check, submit_candidate's // options bound to this attempt's own captures, ask_person's fixed // reply, and the named captures as render_file chunks. The texts here // are for the model; people never read them. package designstep import ( "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "strconv" "sync" "amadan.net/oficina/equipo/internal/runner/renderpage" "amadan.net/oficina/equipo/internal/specialist" "amadan.net/oficina/equipo/internal/wire" ) // The Design step's tools, design-v1's. const ( ToolRenderPage = specialist.ToolRenderPage ToolSubmitCandidate = specialist.ToolSubmitCandidate ToolAskPerson = specialist.ToolAskPerson ) // ErrRenderRefused marks a render check the instance answered with a // refusal; any other failed check could not be made. var ErrRenderRefused = errors.New("designstep: the instance refused the render") // Fixed replies. const ( // RenderRefusedText and RenderUnconfirmedText answer render_page for // the rest of the step once a render check failed. RenderRefusedText = "render_page is stopped for the rest of this step: Equipo's instance refused to let this step render (its Design grant or this attempt no longer holds). Do not call render_page again. Finish without renders, submit what you have, and say in your summary that rendering was refused." RenderUnconfirmedText = "render_page is stopped for the rest of this step: Equipo's instance could not confirm that this step may render. Do not call render_page again. Finish without renders, submit what you have, and say in your summary that rendering was not available." // AskText answers ask_person: nobody is there during the step. AskText = "Nobody can answer during this step. Make the most reasonable choice, build it, and name the assumption in your summary and on the options page." renderCancelledText = "render_page: the call was cancelled." submitUnrecordedText = "submit_candidate could not record the options. Call it again with the same options." submitRulesText = "submit_candidate refused: at most 4 options and 12 captures in all; each option named once, in letters, digits, single spaces, hyphens and apostrophes, at most 60 bytes, starting and ending with a letter or digit; each capture named once. Nothing was recorded: fix it and call again." submitInputText = "submit_candidate refused: the input is {\"options\": [{\"name\": \"...\", \"captures\": [\"\", ...]}, ...]} and nothing else. Nothing was recorded: fix it and call again." ) // capture is one capture render_page made in this attempt, as it wrote // it: its file's SHA-256 and size, and the tree digest it showed. type capture struct { sha, digest string size int64 } // Attempt is one Design attempt's tools. Build one per attempt; it is // safe for concurrent calls, which it takes one at a time. type Attempt struct { // Confirm asks the instance whether this attempt may render now // (wire.LeasePurposeRender); an error wrapping ErrRenderRefused is // its refusal. nil: no render is allowed. Confirm func(context.Context) error // Render is render_page itself on the attempt's step. Render func(context.Context, json.RawMessage) (string, []renderpage.Capture, error) // Dir is the attempt's render directory, where Render writes. Dir string // Record keeps the options submit_candidate accepted, durably, for // this attempt (nil: kept in memory only). Record func(context.Context, []wire.DesignOption) error mu sync.Mutex stopped string captures map[string]capture options []wire.DesignOption } // Call answers one of the step's tools (a thin.ToolFunc). func (a *Attempt) Call(ctx context.Context, name, _ string, raw json.RawMessage) (string, bool) { a.mu.Lock() defer a.mu.Unlock() switch name { case ToolRenderPage: return a.render(ctx, raw) case ToolSubmitCandidate: return a.submit(ctx, raw) case ToolAskPerson: return AskText, false } return "unavailable", true } // render is render_page: the instance is asked first, every call; a // failed check stops rendering for the rest of the attempt. func (a *Attempt) render(ctx context.Context, raw json.RawMessage) (string, bool) { if a.stopped != "" { return a.stopped, true } err := errors.New("designstep: no render check") if a.Confirm != nil { err = a.Confirm(ctx) } switch { case ctx.Err() != nil: return renderCancelledText, true case errors.Is(err, ErrRenderRefused): a.stopped = RenderRefusedText return a.stopped, true case err != nil: a.stopped = RenderUnconfirmedText return a.stopped, true } text, caps, err := a.Render(ctx, raw) a.keep(caps) return text, err != nil } // keep records caps as written in Dir: only a regular file there, its // bytes hashed now, is a capture submit_candidate may name. func (a *Attempt) keep(caps []renderpage.Capture) { if a.captures == nil { a.captures = map[string]capture{} } for _, c := range caps { if !wire.ValidCaptureID(c.File) || !wire.ValidSHA256(c.Digest) { continue } b, err := readCapture(a.Dir, c.File) if err != nil { continue } sum := sha256.Sum256(b) a.captures[c.File] = capture{sha: hex.EncodeToString(sum[:]), digest: c.Digest, size: int64(len(b))} } } // submission is submit_candidate's input. type submission struct { Options *[]struct { Name string `json:"name"` Captures []string `json:"captures"` } `json:"options"` } // submit is submit_candidate: the options, each capture one this // attempt made, within the wire's bounds; they replace any before. func (a *Attempt) submit(ctx context.Context, raw json.RawMessage) (string, bool) { var in submission dec := json.NewDecoder(bytes.NewReader(raw)) dec.DisallowUnknownFields() if dec.Decode(&in) != nil || in.Options == nil || dec.Decode(new(json.RawMessage)) != io.EOF { return submitInputText, true } opts := []wire.DesignOption{} n := 0 for _, o := range *in.Options { opt := wire.DesignOption{Name: o.Name, Captures: []wire.DesignCapture{}} for _, id := range o.Captures { c, ok := a.captures[id] if !ok { return fmt.Sprintf("submit_candidate refused: %s is not a capture render_page made in this step. Name only the file names its replies gave under /render/. Nothing was recorded.", strconv.Quote(clip(id, 80))), true } opt.Captures = append(opt.Captures, wire.DesignCapture{ID: id, SHA256: c.sha, TreeDigest: c.digest}) n++ } opts = append(opts, opt) } if wire.ValidOptions(opts) != nil { return submitRulesText, true } if a.Record != nil && a.Record(ctx, opts) != nil { return submitUnrecordedText, true } a.options = opts return fmt.Sprintf("Recorded %d options with %d captures. They replace any you submitted before. Equipo commits and pushes your workspace when you finish: end with the reply the step prompt asks for.", len(opts), n), false } // Options are the options last recorded (nil: none). func (a *Attempt) Options() []wire.DesignOption { a.mu.Lock() defer a.mu.Unlock() return clone(a.options) } // Files are opts' captures read from dir, the attempt's render // directory, each as its render_file chunks bound to task, step and // attempt. A capture that is not a regular file there, or not the file // recorded (its SHA-256), refuses them all; so do options the wire // refuses. Only the captures opts name are read. func Files(dir, task, step string, attempt int64, opts []wire.DesignOption) ([][]wire.RenderFile, error) { if err := wire.ValidOptions(opts); err != nil { return nil, err } var out [][]wire.RenderFile for _, o := range opts { for _, c := range o.Captures { b, err := readCapture(dir, c.ID) if err != nil { return nil, err } sum := sha256.Sum256(b) if hex.EncodeToString(sum[:]) != c.SHA256 { return nil, fmt.Errorf("designstep: capture %s changed", c.ID) } total := (len(b) + wire.RenderFileChunk - 1) / wire.RenderFileChunk var chunks []wire.RenderFile for i := range total { part := b[i*wire.RenderFileChunk : min((i+1)*wire.RenderFileChunk, len(b))] f := wire.RenderFile{TaskID: task, StepID: step, Attempt: attempt, CaptureID: c.ID, Index: i, Total: total, Size: int64(len(b)), SHA256: c.SHA256, Data: base64.StdEncoding.EncodeToString(part)} if !wire.ValidRenderFile(f) { return nil, fmt.Errorf("designstep: capture %s chunk %d is not a render_file", c.ID, i) } chunks = append(chunks, f) } out = append(out, chunks) } } return out, nil } // readCapture is the capture id's bytes in dir: a regular file reached // through no link, of 1 to wire.MaxCaptureBytes bytes. func readCapture(dir, id string) ([]byte, error) { if !wire.ValidCaptureID(id) { return nil, fmt.Errorf("designstep: capture id %q", id) } root, err := os.OpenRoot(dir) if err != nil { return nil, err } defer root.Close() info, err := root.Lstat(id) if err != nil { return nil, err } if !info.Mode().IsRegular() { return nil, fmt.Errorf("designstep: capture %s is not a regular file", id) } f, err := root.Open(id) if err != nil { return nil, err } defer f.Close() b, err := io.ReadAll(io.LimitReader(f, wire.MaxCaptureBytes+1)) if err != nil { return nil, err } if len(b) == 0 || len(b) > wire.MaxCaptureBytes { return nil, fmt.Errorf("designstep: capture %s is %d bytes", id, len(b)) } return b, nil } func clone(opts []wire.DesignOption) []wire.DesignOption { if opts == nil { return nil } out := make([]wire.DesignOption, len(opts)) for i, o := range opts { out[i] = wire.DesignOption{Name: o.Name, Captures: append([]wire.DesignCapture{}, o.Captures...)} } return out } func clip(s string, n int) string { if len(s) > n { return s[:n] } return s }