Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282// apigen derives Go wire types and HTTP requests from the daemon contract.package main
import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "flag" "fmt" "maps" "os" "path/filepath" "strings"
"github.com/getkin/kin-openapi/openapi3" "github.com/oapi-codegen/oapi-codegen/v2/pkg/codegen" "go.yaml.in/yaml/v3")
func main() { check := flag.Bool("check", false, "fail if generated code differs") flag.Parse() if err := generate(*check); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) }}
func generate(check bool) error { root := filepath.Join("..", "..", "..") data, err := os.ReadFile(filepath.Join(root, "docs", "openapi.yaml")) if err != nil { return err } var document map[string]any if err := yaml.Unmarshal(data, &document); err != nil { return err } digest, err := contractDigest(data) if err != nil { return err } // oapi-codegen supports 3.1. SSE item schemas stay in the canonical 3.2 // document; the adapter owns framing, delivery and cursor recovery. document["openapi"] = "3.1.0" schemas := document["components"].(map[string]any)["schemas"].(map[string]any) for name, schema := range schemas { project(schema) if name == "DynamicJSON" { schema.(map[string]any)["x-go-type"] = "json.RawMessage" } } projectParameters(document["paths"]) projectParameters(document["components"].(map[string]any)["parameters"]) data, err = json.Marshal(document) if err != nil { return err } spec, err := openapi3.NewLoader().LoadFromData(data) if err != nil { return err } version := "v2.8.0" source, err := codegen.Generate(spec, codegen.Configuration{ PackageName: "protocol", Generate: codegen.GenerateOptions{Models: true, Client: true}, Compatibility: codegen.CompatibilityOptions{DisableRequiredReadOnlyAsPointer: true}, OutputOptions: codegen.OutputOptions{ SkipPrune: true, SkipEnumValidate: true, NameNormalizer: "ToCamelCaseWithInitialisms", AdditionalInitialisms: []string{"UTF8", "TTL", "MCP", "HTTP", "JJ"}, UserTemplates: map[string]string{"client-with-responses.tmpl": "// Response decoding is owned by the daemon adapter.\n"}, }, NoVCSVersionOverride: &version, }) if err != nil { return err } outputs := []struct{ path, content string }{ {filepath.Join(root, "cli", "internal", "daemon", "protocol", "api.gen.go"), source}, {filepath.Join(root, "cli", "internal", "daemon", "protocol", "digest.gen.go"), "// Code generated by apigen. DO NOT EDIT.\n\npackage protocol\n\n// APIDigest identifies the wire contract these types were generated from.\n// The daemon reports its own in GET /server; a different value means this\n// client's decoders may reject what the daemon sends.\nconst APIDigest = \"" + digest + "\"\n"}, {filepath.Join(root, "src", "albedo", "daemon", "api_digest.gleam"), "//// Generated by cli/tools/apigen from docs/openapi.yaml. Do not edit.\n//// GET /server reports it so a client built from another contract can tell.\n\npub const digest =\n \"" + digest + "\"\n"}, } for _, output := range outputs { if check { current, err := os.ReadFile(output.path) if err != nil { return err } if !bytes.Equal(current, []byte(output.content)) { return fmt.Errorf("generated API is stale (%s); run go generate ./internal/daemon", output.path) } } else if err := os.WriteFile(output.path, []byte(output.content), 0644); err != nil { return err } } return nil}
// contractDigest hashes the contract as authored, without the prose and// examples, so rewording a description does not split clients from daemons// while any change to a shape, a required set or a route does.func contractDigest(data []byte) (string, error) { var document any if err := yaml.Unmarshal(data, &document); err != nil { return "", err } canonical, err := json.Marshal(withoutProse(document, false)) if err != nil { return "", err } sum := sha256.Sum256(canonical) return hex.EncodeToString(sum[:]), nil}
// withoutProse drops documentation keywords. Inside a properties map the keys// are field names, so a field called description stays.func withoutProse(value any, names bool) any { switch node := value.(type) { case []any: result := make([]any, len(node)) for index, child := range node { result[index] = withoutProse(child, false) } return result case map[string]any: result := make(map[string]any, len(node)) for key, child := range node { if !names && (key == "description" || key == "summary" || key == "example" || key == "examples") { continue } result[key] = withoutProse(child, !names && key == "properties") } return result } return value}
// project selects Go representations without changing the wire contract.// Unions remain raw JSON for the adapter's discriminated decoding. Scalars// keep their wire values; timestamps are parsed by the application adapter.func project(value any) { switch node := value.(type) { case []any: for _, child := range node { project(child) } case map[string]any: for _, key := range []string{"properties", "$defs", "items", "prefixItems", "anyOf", "oneOf", "allOf", "additionalProperties"} { child := node[key] if key == "properties" || key == "$defs" { if members, ok := child.(map[string]any); ok { for _, member := range members { project(member) } } } else { project(child) } } if properties, ok := node["properties"].(map[string]any); ok { for name, child := range properties { property := child.(map[string]any) if name == "etag" { property["x-go-name"] = "ETag" } if baseName, hasIDsSuffix := strings.CutSuffix(name, "_ids"); hasIDsSuffix { property["x-go-name"] = codegen.ToCamelCaseWithInitialisms(baseName) + "IDs" } kind, _ := property["type"].(string) if kind == "array" || property["x-go-type"] == "json.RawMessage" || (kind == "object" && property["properties"] == nil) { property["x-go-type-skip-optional-pointer"] = true } } } if items, ok := node["items"].(bool); ok && !items { // Object-form false schema keeps the tuple restriction while // avoiding the loader's unsupported boolean items schema. node["items"] = map[string]any{"not": map[string]any{}} } if constant, ok := node["const"]; ok { switch constant.(type) { case string: node["type"] = "string" case int, int64: node["type"] = "integer" case bool: node["type"] = "boolean" } } kind, _ := node["type"].(string) nullable := kind == "null" if kinds, ok := node["type"].([]any); ok { for _, member := range kinds { if member == "null" { nullable = true } } if len(kinds) == 2 && nullable { for _, member := range kinds { if member != "null" { kind = member.(string) } } } else { node["x-go-type"] = "json.RawMessage" } } for _, keyword := range []string{"anyOf", "oneOf"} { members, ok := node[keyword].([]any) if !ok { continue } var nonnull []any for _, member := range members { if member.(map[string]any)["type"] == "null" { nullable = true } else { nonnull = append(nonnull, member) } } if len(nonnull) == 1 && nullable && nonnull[0].(map[string]any)["type"] == "array" { // Inline nullable arrays otherwise lose their array shape in // oapi-codegen's single-branch union handling. maps.Copy(node, nonnull[0].(map[string]any)) node["type"] = []any{"array", "null"} delete(node, keyword) kind = "array" } else if node["properties"] != nil { delete(node, keyword) } else if len(nonnull) != 1 || !nullable { node["x-go-type"] = "json.RawMessage" } } switch kind { case "string": node["x-go-type"] = "string" case "integer": node["x-go-type"] = "int64" case "number": node["x-go-type"] = "float64" case "boolean": node["x-go-type"] = "bool" } if node["x-go-type"] == "json.RawMessage" { delete(node, "anyOf") delete(node, "oneOf") delete(node, "type") node["x-go-type-skip-optional-pointer"] = true } if kind == "array" { node["x-go-type-skip-optional-pointer"] = true } if nullable { node["x-oapi-codegen-extra-tags"] = map[string]any{"nullable": "true"} } if len(node) == 0 { node["x-go-type"] = "json.RawMessage" }
}}
func projectParameters(value any) { switch node := value.(type) { case []any: for _, child := range node { projectParameters(child) } case map[string]any: for key, child := range node { if key == "schema" || key == "itemSchema" { project(child) } else if key != "examples" && key != "example" { projectParameters(child) } } }}