swbase.bend source
swbase.bend on the hub · documented module
import Baseimport ./json.bend as Jsonimport ./store.bend as Storeimport ./store/base.bend as SBaseimport ./store/ops.bend as SOpsimport ./store/seq.bend as SSeq# Switch, part 1: error codes, results, and the edits to ~/.claude.json.# Error codes, by the reference's exception class.def e_config() -> U32: 1def e_validation() -> U32: 2def e_not_found() -> U32: 3# A switch that did not stick: a keychain login overrode the files.def e_overridden() -> U32: 20def error_type(+code: U32) -> String: SBase.sel.s(U32.is_eq(code, 1), "ConfigError", SBase.sel.s(U32.is_eq(code, 2), "ValidationError", SBase.sel.s(U32.is_eq(code, 3), "AccountNotFoundError", SBase.sel.s(U32.is_eq(code, 4), "SwitchError", SBase.sel.s(U32.is_eq(code, 5), "CredentialReadError", SBase.sel.s(U32.is_eq(code, 20), "live-login-overridden", "Error"))))))# oauthAccount replaced in place (or appended), every other key kept in order.def merge_oauth(+cfg: Json.Json, +oauth: Json.Json) -> Json.Json: Json.set("oauthAccount", oauth, cfg)def approved_form(+key: String) -> String: String.drop(String.trim(key), Nat.sub(String.length(String.trim(key)), 20n))def has_text(+xs: Json.Json, +t: String) -> Bool: match xs: case Json.JCons{Json.JStr{s}, rest}: String.eq(s, t) || has_text(rest, t) case Json.JCons{h, rest}: has_text(rest, t) case _: False{}def snoc(+xs: Json.Json, +x: Json.Json) -> Json.Json: match xs: case Json.JCons{h, t}: Json.JCons{h, snoc(t, x)} case _: Json.JCons{x, Json.JNil{}}def approved_list(+responses: Json.Json) -> Json.Json: SSeq.unwrap_arr(SSeq.get_or("approved", responses, Json.JNull{}))def with_rejected(+has: Bool, +r: Json.Json) -> Json.Json: match has: case True{}: r case False{}: Json.set("rejected", Json.JArr{Json.JNil{}}, r)def responses2(+j: Json.Json) -> Json.Json: match j: case Json.JObj{f}: Json.JObj{f} case _: Json.JObj{Json.JNil{}}def responses_of(+cfg: Json.Json) -> Json.Json: responses2(SSeq.get_or("customApiKeyResponses", cfg, Json.JNull{}))def add_approved(+items: Json.Json, +key20: String) -> Json.Json: Store.sel.j(has_text(items, key20), items, snoc(items, Json.JStr{key20}))def is_some_json(+m: Maybe<&2, Json.Json>) -> Bool: match m: case Some{x}: True{} case None{}: False{}def managed_responses(+responses: Json.Json, +key20: String) -> Json.Json: with_rejected(is_some_json(Json.get("rejected", responses)), Json.set("approved", Json.JArr{add_approved(approved_list(responses), key20)}, responses))# A managed API key goes in as primaryApiKey and is approved by its last 20# characters (credentials.py _write_managed_credentials, file backend).def set_managed(+cfg: Json.Json, +key: String) -> Json.Json: Json.set("primaryApiKey", Json.JStr{String.trim(key)}, Json.set("customApiKeyResponses", managed_responses(responses_of(cfg), approved_form(key)), cfg))def activate2(+api_key: Bool, +cfg: Json.Json, +oauth: Json.Json, +target_creds: String) -> Json.Json: match api_key: case True{}: merge_oauth(set_managed(cfg, target_creds), oauth) case False{}: merge_oauth(Json.del("primaryApiKey", cfg), oauth)# The live config after activating a target: its oauthAccount, and primaryApiKey# either set (target is an API key) or dropped (target is OAuth).def activate_config(+cfg: Json.Json, +oauth: Json.Json, +target_creds: String) -> Json.Json: activate2(SBase.looks_like_api_key(target_creds), cfg, oauth, target_creds)def num_json(+m: Maybe<&2, String>) -> Json.Json: match m: case Some{n}: Json.JNum{n} case None{}: Json.JNull{}def ref(+num: Maybe<&2, String>, +email: String) -> Json.Json: Json.JObj{Json.JField{"number", num_json(num), Json.JField{"email", Json.JStr{email}, Json.JNil{}}}}def strs_json(+xs: List<&2, String>) -> List<&2, Json.Json>: match xs: case Nil{}: [] case Con{h, t}: Json.JStr{h} <> strs_json(t)def result(+switched: Bool, +from: Json.Json, +to: Json.Json, +strategy: String, +reason: String, +message: String, +warnings: List<&2, String>) -> Json.Json: Json.JObj{Json.JField{"schemaVersion", Json.JNum{"1"}, Json.JField{"switched", Json.JBool{switched}, Json.JField{"from", from, Json.JField{"to", to, Json.JField{"strategy", Json.JStr{strategy}, Json.JField{"reason", Json.JStr{reason}, Json.JField{"message", Json.JStr{message}, Json.JField{"warnings", Json.arr(strs_json(warnings)), Json.JNil{}}}}}}}}}}# {"schemaVersion": 1, "error": {"type", "message"}}def error_envelope(+code: U32, +msg: String) -> Json.Json: Json.JObj{Json.JField{"schemaVersion", Json.JNum{"1"}, Json.JField{"error", Json.JObj{Json.JField{"type", Json.JStr{error_type(code)}, Json.JField{"message", Json.JStr{msg}, Json.JNil{}}}}, Json.JNil{}}}}def ref_text(+r: Json.Json) -> String: "Account-" ++ SOps.field_json(r, "number") ++ " (" ++ SSeq.field_str(r, "email") ++ ")"def same_ref(+a: Json.Json, +b: Json.Json) -> Bool: String.eq(SOps.field_json(a, "number"), SOps.field_json(b, "number")) && String.eq(SSeq.field_str(a, "email"), SSeq.field_str(b, "email"))def switched_msg(+sw: Bool, +to: Json.Json) -> String: SBase.sel.s(sw, "Switched to ", "Already on ") ++ ref_text(to)def result_of_op4(+sw: Bool, +f: Json.Json, +t: Json.Json, +strategy: String, +warns: List<&2, String>) -> Json.Json: result(sw, f, t, strategy, SBase.sel.s(sw, "switched", "already-active"), switched_msg(sw, t), warns)def texts_chain(+items: Json.Json) -> List<&2, String>: match items: case Json.JCons{h, t}: SSeq.str_or(Json.as_string(h), "") <> texts_chain(t) case _: []def texts_of(+w: Json.Json) -> List<&2, String>: match w: case Json.JArr{items}: texts_chain(items) case _: []def result_of_op3(+f: Json.Json, +t: Json.Json, +strategy: String, +extra: List<&2, String>, +op: Json.Json) -> Json.Json: result_of_op4(Bool.not(same_ref(f, t)), f, t, strategy, List.append(&2, String, extra, texts_of(SSeq.get_or("warnings", op, Json.JNull{}))))def result_of_op2(+from: Maybe<&2, Json.Json>, +to: Maybe<&2, Json.Json>, +strategy: String, +extra: List<&2, String>, +op: Json.Json) -> Json.Json: result_of_op3(SSeq.get_or("from", op, Json.JNull{}), SSeq.get_or("to", op, Json.JNull{}), strategy, extra, op)# `_switch_result_from_op`: the op is {"from", "to", "warnings"}.def result_of_op(+op: Json.Json, +strategy: String, +extra: List<&2, String>) -> Json.Json: result_of_op2(Json.get("from", op), Json.get("to", op), strategy, extra, op)def text_or(+m: Maybe<&2, String>) -> String: SSeq.str_or(m, "")def unwrap_json(+m: Maybe<&2, Json.Json>) -> Json.Json: match m: case Some{j}: j case None{}: Json.JNull{}def is_some_str(+m: Maybe<&2, String>) -> Bool: match m: case Some{x}: True{} case None{}: False{}def from_ref(+email: String, +slot: Maybe<&2, String>) -> Json.Json: Store.sel.j(String.is_empty(email), Json.JNull{}, ref(slot, email))def op_json(+from: Json.Json, +to: Json.Json, +warns: List<&2, String>, +org: String) -> Json.Json: Json.JObj{Json.JField{"from", from, Json.JField{"to", to, Json.JField{"warnings", Json.arr(strs_json(warns)), Json.JField{"targetOrg", Json.JStr{org}, Json.JNil{}}}}}}def slot_strs(+xs: List<&2, U32>) -> List<&2, String>: match xs: case Nil{}: [] case Con{h, t}: U32.show(h) <> slot_strs(t)# The slots listed in `sequence`, in order, as slot-key strings.def slots_of(+seq: Json.Json) -> List<&2, String>: slot_strs(SSeq.seq_nums(seq))def sel_ms(+c: Bool, +x: Maybe<&2, String>, +y: Maybe<&2, String>) -> Maybe<&2, String>: match c: case True{}: x case False{}: ydef override_msg(+target: String, +temail: String, +observed: String) -> String: "live-login-overridden: after switching to Account-" ++ target ++ " (" ++ temail ++ ") the live login reads " ++ SBase.sel.s(String.is_empty(observed), "no account", observed) ++ "; a Claude Code keychain login is overriding cswap; remove the 'Claude Code-credentials' keychain item"def noop(+strategy: String, +reason: String, +message: String, +to: Json.Json, +warns: List<&2, String>) -> Json.Json: result(False{}, to, to, strategy, reason, message, warns)def forced2(+rewrite: Bool, +r: Json.Json) -> Json.Json: Store.sel.j(rewrite, Json.set("message", Json.JStr{"Activated " ++ ref_text(SSeq.get_or("to", r, Json.JNull{})) ++ " from stored backup"}, Json.set("reason", Json.JStr{"activated"}, r)), r)def is_true(+m: Maybe<&2, Json.Json>) -> Bool: match m: case Some{Json.JBool{True{}}}: True{} case _: False{}def forced_result(+force: Bool, +r: Json.Json) -> Json.Json: forced2(force && Bool.not(is_true(Json.get("switched", r))), r)def sel_ls(+c: Bool, +x: List<&2, String>, +y: List<&2, String>) -> List<&2, String>: match c: case True{}: x case False{}: y# A JSON number as its text; None for anything else and for 0 (falsy).def num_str(+m: Maybe<&2, Json.Json>) -> Maybe<&2, String>: match m: case Some{Json.JNum{t}}: sel_ms(String.eq(t, "0"), None{}, Some{t}) case _: None{}def sel_s(+c: Bool, +x: String, +y: String) -> String: SBase.sel.s(c, x, y)# `--model` limits ride on the result: {"models": [...], "modelSource": "cli"}.def with_models(+r: Json.Json, +models: List<&2, String>, +source: String) -> Json.Json: Store.sel.j(List.is_empty(&2, String, models), r, Json.set("modelSource", Json.JStr{source}, Json.set("models", Json.arr(strs_json(models)), r)))