diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 674445344..f4cbb055d 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -2025,7 +2025,11 @@ type Model struct { CapKey ID `json:"cap_key"` // CompactAt The window the user saved for this model, below its own; null or absent follows the model. - CompactAt *Counter `json:"compact_at,omitempty" nullable:"true"` + CompactAt *Counter `json:"compact_at,omitempty" nullable:"true"` + CyberAccess *struct { + Detail *string `json:"detail,omitempty"` + Status string `json:"status"` + } `json:"cyber_access,omitempty"` DefaultContextTokens *Counter `json:"default_context_tokens" nullable:"true"` EffectiveContextTokens *Counter `json:"effective_context_tokens" nullable:"true"` Efforts []struct { @@ -2097,7 +2101,10 @@ type ModelSettingsResource struct { // NewSessionIntent defines model for NewSessionIntent. type NewSessionIntent struct { // ContextWindow Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. - ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` + ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` + + // CyberAccess Explicit Blue at creation; null or omission selects standard. + CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` Effort *string `json:"effort" nullable:"true"` Kind string `json:"kind"` Model *ID `json:"model" nullable:"true"` @@ -2111,7 +2118,10 @@ type NewSessionIntent struct { // NewSessionRequest Examples: {"kind":"new","workspace":"/workspace/project"} type NewSessionRequest struct { // ContextWindow Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. - ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` + ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` + + // CyberAccess Explicit Blue at creation; null or omission selects standard. + CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` Effort *string `json:"effort,omitempty" nullable:"true"` Kind string `json:"kind"` Model *ID `json:"model,omitempty" nullable:"true"` @@ -2887,6 +2897,7 @@ type Session struct { Creation *Creation `json:"creation" nullable:"true"` CurrentProgress []ToolProgress `json:"current_progress"` Cursor *Cursor `json:"cursor" nullable:"true"` + CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` Depth int64 `json:"depth"` Effort *string `json:"effort" nullable:"true"` @@ -2975,8 +2986,11 @@ type SessionCompactedEvent struct { // SessionConfiguration Examples: {"effort":null,"fast":false,"id":"01a0fcea-2b00-7000-8000-000000000001","model":"example-model","name":null,"preferences":{"archived":false,"pin_order":null,"pinned":false},"provider_profile":"personal","revision":"config-1","selection":{"extensions":{},"instructions":{},"mcp":{},"skills":{}},"workspace":"/workspace/project"} type SessionConfiguration struct { // ContextWindow Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. - ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` - Effort *string `json:"effort" nullable:"true"` + ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` + + // CyberAccess Explicit session-scoped Codex Blue intent; null sends ordinary requests. + CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` + Effort *string `json:"effort" nullable:"true"` // Fast Provider fast-mode setting; defaults off and may affect billing. Fast bool `json:"fast"` @@ -3152,8 +3166,11 @@ type SessionPatch struct { CatalogRevision *ID `json:"catalog_revision,omitempty"` // ContextWindow Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. - ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` - Effort *string `json:"effort,omitempty" nullable:"true"` + ContextWindow *int64 `json:"context_window,omitempty" nullable:"true"` + + // CyberAccess Select Blue for this session; null explicitly clears it. + CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` + Effort *string `json:"effort,omitempty" nullable:"true"` // Fast Enable provider fast mode; enabling requires a supported capability and may affect billing. Fast *bool `json:"fast,omitempty"` @@ -3268,6 +3285,7 @@ type SessionSummary struct { CreatedAt *Timestamp `json:"created_at" nullable:"true"` CurrentProgress []ToolProgress `json:"current_progress"` Cursor *Cursor `json:"cursor" nullable:"true"` + CyberAccess *string `json:"cyber_access,omitempty" nullable:"true"` Depth int64 `json:"depth"` Effort *string `json:"effort" nullable:"true"` Fast bool `json:"fast"` @@ -4257,10 +4275,16 @@ type ListModelsParams struct { Host *string `form:"host,omitempty" json:"host,omitempty"` Model *ID `form:"model,omitempty" json:"model,omitempty"` ProviderProfile *ID `form:"provider_profile,omitempty" json:"provider_profile,omitempty"` - Provider *ID `form:"provider,omitempty" json:"provider,omitempty"` - Endpoint *string `form:"endpoint,omitempty" json:"endpoint,omitempty"` - Limit *Limit `form:"limit,omitempty" json:"limit,omitempty"` - Next *Next `form:"next,omitempty" json:"next,omitempty"` + + // Session Existing session whose selected account scopes Daybreak Blue support; with initial=true, a preallocated new session ID selects its exact future account. + Session *ID `form:"session,omitempty" json:"session,omitempty"` + + // Initial true permits preview with a new future session ID; requires provider_profile and session. Existing session IDs are rejected. + Initial *string `form:"initial,omitempty" json:"initial,omitempty"` + Provider *ID `form:"provider,omitempty" json:"provider,omitempty"` + Endpoint *string `form:"endpoint,omitempty" json:"endpoint,omitempty"` + Limit *Limit `form:"limit,omitempty" json:"limit,omitempty"` + Next *Next `form:"next,omitempty" json:"next,omitempty"` } // GetServerParams defines parameters for GetServer. @@ -12232,6 +12256,30 @@ func NewListModelsRequest(server string, params *ListModelsParams) (*http.Reques } + if params.Session != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "session", *params.Session, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Initial != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "initial", *params.Initial, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + if params.Provider != nil { if queryFrag, err := runtime.StyleParamWithOptions("form", true, "provider", *params.Provider, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 63ff79cc7..6a1ddaab1 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -2745,6 +2745,19 @@ paths: required: false schema: $ref: '#/components/schemas/ID' + - name: session + in: query + required: false + description: Existing session whose selected account scopes Daybreak Blue support; with initial=true, a preallocated new session ID selects its exact future account. + schema: + $ref: '#/components/schemas/ID' + - name: initial + in: query + required: false + description: true permits preview with a new future session ID; requires provider_profile and session. Existing session IDs are rejected. + schema: + type: string + enum: ['true'] - name: provider in: query required: false @@ -7806,6 +7819,9 @@ components: - type: 'null' fast: type: boolean + cyber_access: + type: [string, 'null'] + enum: [daybreak_blue, null] status: $ref: '#/components/schemas/SessionStatus' preview: @@ -8048,6 +8064,10 @@ components: fast: type: boolean description: Provider fast-mode setting; defaults off and may affect billing. + cyber_access: + type: [string, 'null'] + enum: [daybreak_blue, null] + description: Explicit session-scoped Codex Blue intent; null sends ordinary requests. context_window: description: Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. @@ -8124,6 +8144,10 @@ components: fast: type: boolean description: Enable provider fast mode; enabling requires a supported capability and may affect billing. + cyber_access: + type: [string, 'null'] + enum: [daybreak_blue, null] + description: Select Blue for this session; null explicitly clears it. context_window: description: Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. @@ -8197,6 +8221,10 @@ components: minimum: 1 maximum: 100000000 - type: 'null' + cyber_access: + type: [string, 'null'] + enum: [daybreak_blue, null] + description: Explicit Blue at creation; null or omission selects standard. required: [kind, workspace] additionalProperties: false examples: @@ -8235,6 +8263,10 @@ components: minimum: 1 maximum: 100000000 - type: 'null' + cyber_access: + type: [string, 'null'] + enum: [daybreak_blue, null] + description: Explicit Blue at creation; null or omission selects standard. required: [kind, workspace, name, provider_profile, model, effort] additionalProperties: false ForkSessionRequest: @@ -11263,6 +11295,16 @@ components: Model: type: object properties: + cyber_access: + type: object + properties: + status: + type: string + enum: [supported, unsupported, unknown] + detail: + type: string + required: [status] + additionalProperties: false id: $ref: '#/components/schemas/ID' label: diff --git a/priv/python/albedo_plugins/agents.py b/priv/python/albedo_plugins/agents.py index 9037b2d1e..0f2fde3ba 100644 --- a/priv/python/albedo_plugins/agents.py +++ b/priv/python/albedo_plugins/agents.py @@ -75,6 +75,7 @@ class Agent: evidence_bar: str | None = None, falsifier: str | None = None, verifier: str | None = None, + cyber_access: str | None = None, ) -> "Agent": """Start a child with `task`. Returns at once; its answer comes as mail.""" if self.id != agents.self.id: @@ -103,6 +104,10 @@ class Agent: payload: dict[str, object] = {"task": brief, "name": name, "model": model} if verifier is not None: payload["verifier"] = verifier.strip() + if cyber_access is not None: + if cyber_access != "daybreak_blue": + raise ValueError("cyber_access must be daybreak_blue or None") + payload["cyber_access"] = cyber_access return _agent(cast(dict, await _act("agents.spawn", payload))) async def children(self) -> list["Agent"]: @@ -285,11 +290,22 @@ def _brief( class Agents: self: Agent - async def models(self) -> list[str]: - """Models a child may run on. Required once before spawning.""" + async def models(self, *, cyber_access: str | None = None) -> list[str]: + """Canonical choices; daybreak_blue filters to advertised account-scoped Blue models.""" + if cyber_access not in (None, "daybreak_blue"): + raise ValueError("cyber_access must be daybreak_blue or None") global _models_seen _models_seen = True - models = [str(model) for model in cast(list, await host("agents.models", {}))] + models = [ + str(model) + for model in cast( + list, + await host( + "agents.models", + {"cyber_access": cyber_access} if cyber_access else {}, + ), + ) + ] if all("/" in model for model in models): return models # An older daemon lists bare ids for the caller's own profile. diff --git a/robot-docs/agents.md b/robot-docs/agents.md index 7904f7b23..286f308b8 100644 --- a/robot-docs/agents.md +++ b/robot-docs/agents.md @@ -41,6 +41,7 @@ found = await resources.query("cargo", cwd="~/proj/albedo") # across sessions lists](models.md#model-lists)) is read alone; one that must be fetched is asked together with every other profile's, so a lookup waits at most one first fetch (8 s), and the caller's answer still decides before any other's. A legacy session with no provider recorded resolves as the flat config's profile. +- `switch(model)` is the legacy Standard choice: even when selecting the same model, it clears a saved Daybreak Blue intent at the switch boundary before the next provider request. It never installs a Standard upstream while the saved configuration still says Blue. - `switch(model)` accepts a bare model id or `provider/model`, like spawn, but refuses any id no profile lists. It returns `{model: "provider/model", pending: bool}`: idle sessions change now; a running request and its tools finish on the @@ -175,3 +176,7 @@ Direct parent deletion requires a successful child lookup. Tree deletion collect `await mail.request(to, body)` creates a request; the recipient owes the sender until it sends any letter. Peer messages do not create obligations; a child still owes its parent after a task or ordinary message. `await mail.open()` returns bounded `owed` and `awaiting` entries. `await agents.set_role(text, id=None)` stores optional trimmed metadata for workspace views; it is not prompt context. Peers are root sessions started with `await agents.start(task, name, model, cwd=None, role=None)`. They have no family parent and do not count against child limits. The starter alone may cancel or close its peers. Session snapshots expose role, provenance, pinned state, and open request counts. + +## Blue child opt-in + +`agents.models()` still returns canonical `provider/model` strings. `agents.models(cyber_access="daybreak_blue")` filters the selected account of each profile by its authenticated Blue advertisement and reports metadata/credential errors, rather than treating unknown as unsupported. `agents.self.spawn(..., cyber_access="daybreak_blue")` explicitly opts the new child in; ordinary children and root peers remain standard. A human fork preserves the source session intent. An underlying model/provider change clears Blue; effort-only changes do not. A child’s fresh session ID may resolve a different unpinned account from its parent: discovery describes the parent-resolved account, not a guarantee that the child can run. Its first request validates its own actual account and fails closed before any Standard stream; pin the profile to a Blue-eligible account for reliable child opt-in. diff --git a/robot-docs/models.md b/robot-docs/models.md index 5de636b7c..f10bf5d38 100644 --- a/robot-docs/models.md +++ b/robot-docs/models.md @@ -191,3 +191,7 @@ A model whose catalog entry lists its inputs without `image` (the provider's own An image cut short is refused the same way, whatever the model: a PNG whose chunks stop before IEND, or a JPEG with no end-of-image marker after its frame header, still has a readable header, but the provider cannot decode it and would refuse every later request that carries it. `show_image` raises `ValueError: this 49152-byte image/png stops before its IEND chunk: ...` at the call, and `image.inspect`, which every attach path goes through, refuses it again; history loads check only headers, so an image already stored stays loadable. History can still hold images over the limit: ones an earlier, looser provider accepted before a model switch, or ones from before limits were declared. At the start of each model step, before the request is prepared, the loop has `albedo-render --fit EDGE` scale each such image down (aspect kept, Lanczos; a JPEG stays JPEG, anything else becomes PNG) and appends an image fit row to the transcript (`transcript.ImageFit`): the copy, stored in `images` like any payload, the original's payload hash, and a user note from origin `image scaled` (`An earlier image was scaled from WxH to WxH to fit this model's EDGEpx edge limit; the transcript keeps the original.`). Loading the history applies each fit to every row before it, so the transcript alone says what any request carried: provider request rows, `/context`, forks, and restarts all see the copy, and a fork from before the fit row starts from the original. Readers that only show rows see the fit as its note, which the chat shows once. The original row is never rewritten. A fit is permanent: switching back to a looser provider keeps the copy (fitting per edge is a TODO in `daemon/image_fit.gleam`). Snapcompact frames never need fitting, because they are rendered to fit. Without `albedo-render` the turn fails before sending, naming the binary, rather than getting the provider's 400. + +## Account-scoped Daybreak Blue + +Daybreak Blue is not a new model ID or a global models.dev fact. Codex `catalog.gleam` decodes `available_access_programs.cyber` from the authenticated `/backend-api/codex/models` response per account. Its one-hour entry binds to a fingerprint of the exact bearer; stale/changed bearers refresh, and legacy/missing cyber metadata gets one unconditional no-ETag refetch. Model listing resolves one selected account/bearer snapshot per `/models` request, with at most one forced refresh for any number of legacy rows; each missing row remains unknown while known eligible/ineligible rows stay distinct. Refresh failure means unknown, not unsupported. A successful response that explicitly excludes Blue means unsupported. Request-time Codex checks the current attempted account, bearer, and canonical model after each rotation and errors rather than silently sending an ordinary request. Only Codex Responses includes `access_programs.cyber=daybreak_blue` in the wire body. The explicit saved intent is session-wide for model inference, including auto-summary and background model requests: they must carry Blue and fail closed before inference if its current account/model is unverified. The web_search tool is an explicit exception: its separate search query is ordinary/Standard inference (and may fall through to another configured search provider), not a Blue session model request. Do not send Blue-only text in a search query assuming Blue protections; chat, auto-summary, and background session requests never downgrade. diff --git a/robot-docs/settings.md b/robot-docs/settings.md index 01a9bc42f..43bf4f152 100644 --- a/robot-docs/settings.md +++ b/robot-docs/settings.md @@ -71,3 +71,7 @@ Global settings remain in `config.json`, `extensions.json`, `capabilities.json`, Catalog revision includes inspected content and file identity, workspace, global composition revisions, and resolved choices. Unchanged inputs retain their revision. The settings lock (`albedo_lock`, a queued lock per key on this node) hands over the moment its holder releases or exits, so a read never sleeps behind another read; a caller waits at most 20 seconds before reporting the store busy. It does not make external filesystem edits atomic. Its key is the home path as given (the daemon absolutises its home once at start), so taking the lock makes no OS call: a settings read while the process is out of file descriptors reports an error, as every reader expects, instead of crashing the reader. Deletion removes the session's SQL preferences and selection. Discovered skill and instruction files remain on disk. Credential migration notices come from `GET /server`; dismissal belongs to `ui.dismissed_notices`. + +## Cyber access intent + +`sessions.cyber_access` is nullable with the sole non-null value `daybreak_blue`; `null` means ordinary. It is independent of provider fast mode and stored through the session configuration PATCH (`cyber_access: null | "daybreak_blue"`) with the normal ETag transaction. Unknown or Red values fail validation; Blue is admitted only when the currently selected account/model has verified advertisement. Changing model/provider without a concurrent explicit Blue opt-in clears it, while effort changes retain it. Neither ordinary requests nor fast mode imply Blue. diff --git a/robot-docs/web.md b/robot-docs/web.md index ac37861aa..76b36f96d 100644 --- a/robot-docs/web.md +++ b/robot-docs/web.md @@ -159,3 +159,7 @@ With no mounted picker, an already issued write settles but no new write starts. Unsaved state remains available when that session's picker returns. Quiescent, unreferenced lanes are removed. This state is not saved to localStorage or the daemon; reloading the page discards unsaved choices. + +## Blue model choices + +The existing-session model chooser requests `/models?provider_profile=...&session=...` so the daemon uses that profile's account resolved for this session, rather than the merged Codex model catalog. It offers separate Standard and Daybreak Blue rows only where the account advertises Blue; the rows use the same canonical model ID. Selecting Standard clears `cyber_access` explicitly, and effort changes preserve it. Metadata failures show `unknown` with a reason, not a Blue option. The chip shows saved Blue separately from Fast. After the first creation attempt, the new-session dialog locks its profile/model/Blue choice for retries; if the response was lost, its stable-ID retry only recovers a persisted session whose immutable submitted creation intent exactly matches, never allocating another ID or silently changing the selection. The new-session picker allocates its future session ID before requesting `/models?provider_profile=...&session=...&initial=true`, so profile account rotation hashes exactly the same ID at creation; it stores the explicit Blue choice on creation. Omitted/null intent remains standard. Preview is advisory: creation independently rechecks Blue off the registry actor, then each model request checks the exact attempted account and bearer after rotation; an ineligible or unverified attempt errors before inference, never silently downgrades to Standard. A spawned Blue child can hash to a different unpinned account than its parent; it may be created but its first request fails closed if that account lacks Blue. diff --git a/src/albedo/daemon/agents.gleam b/src/albedo/daemon/agents.gleam index 6ee0a15f0..587c4fb96 100644 --- a/src/albedo/daemon/agents.gleam +++ b/src/albedo/daemon/agents.gleam @@ -5,11 +5,18 @@ import albedo/daemon/conversation import albedo/daemon/family +import gleam/option pub type Op { /// `parent` starts a child named `name` on `model` ("" for its own) with /// `task` as its first letter. - Spawn(parent: String, name: String, task: String, model: String) + Spawn( + parent: String, + name: String, + task: String, + model: String, + cyber_access: option.Option(String), + ) /// Start a root peer owned by the caller. Start( caller: String, @@ -28,7 +35,7 @@ pub type Op { /// Whether a session is running a turn right now. Running(session: String) /// The models a child of `session` may run on. - Models(session: String) + Models(session: String, cyber_access: option.Option(String)) } pub type Reply { diff --git a/src/albedo/daemon/conversation.gleam b/src/albedo/daemon/conversation.gleam index 91655d3b4..3569315ed 100644 --- a/src/albedo/daemon/conversation.gleam +++ b/src/albedo/daemon/conversation.gleam @@ -45,6 +45,7 @@ pub type Info { last_assistant_at: Option(Int), effort: Option(String), fast: Bool, + cyber_access: Option(String), ) } @@ -1115,7 +1116,7 @@ pub fn assign_session_provider( /// What `info_decoder` reads. A name someone gave the session outranks the /// title its latest message suggests. pub const info_columns = - "id,COALESCE(NULLIF(name,''),NULLIF(title,''),'new session'),cwd,COALESCE(provider,''),model,protocol,stage,last_assistant_at,effort,fast" + "id,COALESCE(NULLIF(name,''),NULLIF(title,''),'new session'),cwd,COALESCE(provider,''),model,protocol,stage,last_assistant_at,effort,fast,cyber_access" /// Decodes `info_columns`. pub fn info_decoder() -> decode.Decoder(Info) { @@ -1129,6 +1130,7 @@ pub fn info_decoder() -> decode.Decoder(Info) { use last_assistant_at <- decode.field(7, decode.optional(decode.int)) use effort <- decode.field(8, decode.optional(decode.string)) use fast <- decode.field(9, sqlight.decode_bool()) + use cyber_access <- decode.field(10, decode.optional(decode.string)) decode.success(Info( id, title, @@ -1143,6 +1145,7 @@ pub fn info_decoder() -> decode.Decoder(Info) { last_assistant_at, effort, fast, + cyber_access, )) } @@ -1321,7 +1324,7 @@ pub fn create(store: store.Store, info: Info) -> Result(Nil, String) { fn create_in(db: sqlight.Connection, info: Info) -> Result(Nil, String) { store.run( db, - "INSERT INTO sessions(id,title,cwd,provider,model,protocol,fast,activity_seq,last_assistant_at,effort,created_at,activity_at) SELECT ?,?,?,?,?,?,?,COALESCE(MAX(activity_seq),0)+1,?,?,?,? FROM sessions", + "INSERT INTO sessions(id,title,cwd,provider,model,protocol,fast,cyber_access,activity_seq,last_assistant_at,effort,created_at,activity_at) SELECT ?,?,?,?,?,?,?,?,COALESCE(MAX(activity_seq),0)+1,?,?,?,? FROM sessions", [ sqlight.text(info.id), sqlight.text(info.title), @@ -1333,6 +1336,7 @@ fn create_in(db: sqlight.Connection, info: Info) -> Result(Nil, String) { True -> 1 False -> 0 }), + sqlight.nullable(sqlight.text, info.cyber_access), sqlight.nullable(sqlight.int, info.last_assistant_at), sqlight.nullable(sqlight.text, info.effort), sqlight.int(usage.now()), diff --git a/src/albedo/daemon/history.gleam b/src/albedo/daemon/history.gleam index 6dc326599..1b2efdfaa 100644 --- a/src/albedo/daemon/history.gleam +++ b/src/albedo/daemon/history.gleam @@ -141,6 +141,7 @@ fn fork_in( None, source.effort, source.fast, + source.cyber_access, )) } @@ -379,7 +380,7 @@ fn insert_session( ) -> Result(Nil, String) { store.run( db, - "INSERT INTO sessions(id,title,cwd,provider,model,protocol,effort,fast,stage,activity_seq,last_assistant_at,created_at,activity_at) SELECT ?,?,?,?,?,?,?,?,'idle',COALESCE(MAX(activity_seq),0)+1,NULL,?,? FROM sessions", + "INSERT INTO sessions(id,title,cwd,provider,model,protocol,effort,fast,cyber_access,stage,activity_seq,last_assistant_at,created_at,activity_at) SELECT ?,?,?,?,?,?,?,?,?,'idle',COALESCE(MAX(activity_seq),0)+1,NULL,?,? FROM sessions", [ sqlight.text(id), sqlight.text(title), @@ -392,6 +393,7 @@ fn insert_session( True -> 1 False -> 0 }), + sqlight.nullable(sqlight.text, source.cyber_access), sqlight.int(usage.now()), sqlight.int(usage.now()), ], diff --git a/src/albedo/daemon/http_api.gleam b/src/albedo/daemon/http_api.gleam index 40cfeb7cf..5fdea39ea 100644 --- a/src/albedo/daemon/http_api.gleam +++ b/src/albedo/daemon/http_api.gleam @@ -561,8 +561,9 @@ pub fn creation( req, [ "kind", "workspace", "name", "provider_profile", "model", "effort", - "context_window", "source_session_id", "checkpoint_id", "parent_id", - "address", "initial_input_id", "task", "client_id", "mcp_servers", + "context_window", "cyber_access", "source_session_id", "checkpoint_id", + "parent_id", "address", "initial_input_id", "task", "client_id", + "mcp_servers", ], decode.field("kind", decode.string, decode.success), )) @@ -578,7 +579,7 @@ pub fn creation( req, [ "kind", "workspace", "name", "provider_profile", "model", "effort", - "context_window", + "context_window", "cyber_access", ], { use workspace <- decode.field("workspace", bounded_string(4096, True)) @@ -591,6 +592,23 @@ pub fn creation( None, decode.optional(context_window()), ) + use cyber_access <- decode.optional_field( + "cyber_access", + None, + decode.optional( + decode.string + |> decode.then(fn(value) { + case value { + "daybreak_blue" -> decode.success(value) + _ -> + decode.failure( + value, + "cyber_access must be daybreak_blue or null", + ) + } + }), + ), + ) decode.success(creation.NewSession( workspace, name, @@ -598,6 +616,7 @@ pub fn creation( model, effort, window, + cyber_access, )) }, ) diff --git a/src/albedo/daemon/http_configuration.gleam b/src/albedo/daemon/http_configuration.gleam index 913d1166e..2f93b20b6 100644 --- a/src/albedo/daemon/http_configuration.gleam +++ b/src/albedo/daemon/http_configuration.gleam @@ -57,6 +57,7 @@ pub fn change( "model", "effort", "fast", + "cyber_access", "context_window", "preferences", "selection", @@ -89,6 +90,7 @@ pub fn change( "model", "effort", "fast", + "cyber_access", "context_window", "preferences", "selection", @@ -112,6 +114,22 @@ pub fn change( decode.optional(http_api.bounded_string(100, False)), )) use fast <- decode.then(optional_edit("fast", decode.bool)) + use cyber_access <- decode.then(optional_edit( + "cyber_access", + decode.optional( + decode.string + |> decode.then(fn(value) { + case value { + "daybreak_blue" -> decode.success(value) + _ -> + decode.failure( + value, + "cyber_access must be daybreak_blue or null", + ) + } + }), + ), + )) use context_window <- decode.then(optional_edit( "context_window", decode.optional(http_api.context_window()), @@ -145,6 +163,7 @@ pub fn change( model, effort, fast, + cyber_access, context_window, preferences.0, preferences.1, @@ -192,6 +211,7 @@ pub fn encode(value: session_configuration.Configuration) -> json.Json { }), #("effort", json.nullable(value.effort, json.string)), #("fast", json.bool(value.fast)), + #("cyber_access", json.nullable(value.cyber_access, json.string)), #("context_window", json.nullable(value.context_window, json.int)), #("preferences", preferences(value.preferences, False)), #("selection", selection(value.selection)), diff --git a/src/albedo/daemon/http_resources.gleam b/src/albedo/daemon/http_resources.gleam index 8a4df702a..96d0666e3 100644 --- a/src/albedo/daemon/http_resources.gleam +++ b/src/albedo/daemon/http_resources.gleam @@ -17,6 +17,7 @@ import albedo/harness/extension/selection import albedo/harness/location import albedo/harness/runtime import albedo/harness/ssh +import albedo/openai_api/types import gleam/bytes_tree import gleam/dict import gleam/dynamic/decode @@ -535,6 +536,8 @@ pub fn models( "host", "model", "provider_profile", + "session", + "initial", "provider", "endpoint", "limit", @@ -692,7 +695,67 @@ pub fn models( None -> model } }) - let encoded = json.array(models, model_json(_, provider.0, provider.1)) + let session = list.key_find(parameters, "session") |> result.unwrap("") + let initial = list.key_find(parameters, "initial") |> result.unwrap("") + use _ <- result.try(case initial, session { + "", "" -> Ok(Nil) + "", id -> + conversation.get(runtime.ledger(host), id) + |> result.map(fn(_) { Nil }) + |> result.map_error(http_api.failure) + "true", id if id != "" && profile != None -> + case conversation.get(runtime.ledger(host), id) { + Ok(_) -> + Error(http_api.invalid( + "initial preview requires a new session ID", + )) + Error("session not found") -> Ok(Nil) + Error(reason) -> Error(http_api.failure(reason)) + } + _, _ -> + Error(http_api.invalid( + "initial=true requires session and provider_profile", + )) + }) + // Resolve the selected account/bearer once: legacy rows trigger at + // most one unconditional refresh for this page, not one per model. + let catalog = case profile, provider.0 { + Some(profile_name), "codex" -> + Some(runtime.cyber_catalog( + host, + session, + config.home, + profile_name, + provider.0, + types.Responses, + )) + _, _ -> None + } + let catalog = + option.map(catalog, fn(snapshot) { + result.map(snapshot, dict.from_list) + }) + let blue = + list.map(models, fn(model) { + let access = case catalog { + None -> None + Some(Error(reason)) -> Some(Error(reason)) + Some(Ok(rows)) -> + Some(case dict.get(rows, model.id) { + Error(_) -> Ok(False) + Ok(Some(available)) -> Ok(available) + Ok(None) -> + Error( + "ChatGPT account catalog does not advertise cyber-access metadata", + ) + }) + } + #(model, access) + }) + let encoded = + json.array(blue, fn(pair) { + model_json(pair.0, provider.0, provider.1, pair.1) + }) let revision = http_api.etag(json.to_string(encoded)) use offset <- result.try(http_api.page_offset( config.token, @@ -701,7 +764,7 @@ pub fn models( revision, 0, )) - let shown = list.drop(models, offset) |> list.take(limit) + let shown = list.drop(blue, offset) |> list.take(limit) let next = case offset + list.length(shown) < list.length(models) { True -> http_api.continuation( @@ -716,7 +779,12 @@ pub fn models( Ok(http_api.reply( 200, json.object([ - #("items", json.array(shown, model_json(_, provider.0, provider.1))), + #( + "items", + json.array(shown, fn(pair) { + model_json(pair.0, provider.0, provider.1, pair.1) + }), + ), #("next", next), ]), )) @@ -731,6 +799,7 @@ fn model_json( model: runtime.ListedModel, provider: String, endpoint: Option(String), + access: Option(Result(Bool, String)), ) -> json.Json { let fact = fn(read) { option.then(model.info, read) } let host = @@ -744,7 +813,34 @@ fn model_json( let ttl = option.then(policy, cache_ttl.clock_tier) |> option.map(fn(tier) { tier.seconds }) + let cyber = case access { + Some(Ok(True)) -> json.object([#("status", json.string("supported"))]) + Some(Ok(False)) -> + json.object([ + #("status", json.string("unsupported")), + #( + "detail", + json.string("this account/model does not advertise Daybreak Blue"), + ), + ]) + Some(Error(reason)) -> + json.object([ + #("status", json.string("unknown")), + #("detail", json.string(reason)), + ]) + None -> + json.object([ + #("status", json.string("unsupported")), + #( + "detail", + json.string( + "select a Codex profile to inspect account-specific access", + ), + ), + ]) + } json.object([ + #("cyber_access", cyber), #("id", json.string(model.id)), #("label", json.string(model.id)), #( diff --git a/src/albedo/daemon/http_sessions.gleam b/src/albedo/daemon/http_sessions.gleam index 03020b6b5..dd226e30c 100644 --- a/src/albedo/daemon/http_sessions.gleam +++ b/src/albedo/daemon/http_sessions.gleam @@ -5,6 +5,7 @@ import albedo/daemon/acp_attachments import albedo/daemon/acp_session import albedo/daemon/bus import albedo/daemon/child_models +import albedo/daemon/configuration import albedo/daemon/context_snapshot import albedo/daemon/conversation import albedo/daemon/family @@ -102,6 +103,68 @@ fn creation_failure( ) } +/// Network catalog verification happens in the HTTP caller, never the registry actor. +/// Existing IDs still reach the registry's normal retry/conflict decision. +fn blue_creation_preflight( + config: Config, + host: runtime.Runtime, + ledger: store.Store, + id: String, + intent: session_creation.Intent, +) -> Result(Nil, http_api.Failure) { + case intent { + session_creation.NewSession( + provider_profile: profile, + model: model, + cyber_access: Some("daybreak_blue"), + .., + ) -> { + use prior <- result.try( + conversation.creation(ledger, id) |> result.map_error(http_api.failure), + ) + case prior { + Some(_) -> Ok(Nil) + None -> + case conversation.get(ledger, id) { + Ok(_) -> Ok(Nil) + Error("session not found") -> { + use provider <- result.try( + case profile { + Some(name) -> configuration.named(config.home, name) + None -> configuration.active(config.home) + } + |> result.map_error(http_api.failure), + ) + case + runtime.cyber_access( + host, + id, + config.home, + provider.name, + provider.extension, + option.unwrap(model, provider.model), + provider.protocol, + ) + { + Ok(True) -> Ok(Nil) + Ok(False) -> + Error(http_api.failure( + "Daybreak Blue unavailable for selected account/model", + )) + Error(reason) -> + Error(http_api.failure( + "cannot verify Daybreak Blue: " <> reason, + )) + } + } + Error(reason) -> Error(http_api.failure(reason)) + } + } + } + _ -> Ok(Nil) + } +} + pub fn create( config: Config, registry: Subject(Message), @@ -137,6 +200,13 @@ pub fn create( |> option.from_result _ -> None } + use _ <- result.try(blue_creation_preflight( + config, + host, + ledger, + id, + submitted, + )) case registry.create_session_identified(registry, id, submitted, choice) { Error("session_exists") -> creation_failure(ledger, id, http_api.failure("session_exists"), None) @@ -1225,6 +1295,7 @@ fn changes_execution(change: http_configuration.Change) -> Bool { patch.provider_profile != None || patch.model != None || patch.effort != None + || patch.cyber_access != None || patch.context_window != None || patch.selection != session_configuration.SelectionPatch(None, None, None, None) @@ -1256,6 +1327,7 @@ pub fn patch( model: Some(_), effort: None, fast: None, + cyber_access: None, context_window: None, pinned: None, archived: None, @@ -1456,6 +1528,7 @@ pub fn fast_mode( model: None, effort: None, fast: Some(enabled), + cyber_access: None, context_window: None, pinned: None, archived: None, diff --git a/src/albedo/daemon/http_wire.gleam b/src/albedo/daemon/http_wire.gleam index 019147c66..7bd24fd3b 100644 --- a/src/albedo/daemon/http_wire.gleam +++ b/src/albedo/daemon/http_wire.gleam @@ -107,6 +107,7 @@ pub fn summary_fields(capture: session.Capture) -> List(#(String, json.Json)) { }), #("effort", json.nullable(capture.info.effort, json.string)), #("fast", json.bool(capture.info.fast)), + #("cyber_access", json.nullable(capture.info.cyber_access, json.string)), #("status", status(capture.status)), #("current_progress", json.array(capture.current_progress, progress)), #("activity", activity(capture.activity)), @@ -214,6 +215,7 @@ pub fn summary( }), #("effort", json.nullable(info.effort, json.string)), #("fast", json.bool(info.fast)), + #("cyber_access", json.nullable(info.cyber_access, json.string)), #("preview", session_preview(durable.preview)), #("status", status(status_value)), #("activity", activity(activity_value)), diff --git a/src/albedo/daemon/registry.gleam b/src/albedo/daemon/registry.gleam index aa486610d..b90ccc901 100644 --- a/src/albedo/daemon/registry.gleam +++ b/src/albedo/daemon/registry.gleam @@ -220,6 +220,7 @@ fn serve(state: State, message: Message) -> actor.Next(State, a) { None, effort, False, + None, ) case string.trim(info.model) != "" @@ -664,13 +665,51 @@ pub fn start( |> result.try(child_models.resolve(host, config.home, _, model)) } case op { - agents.Models(id) -> - Ok( - agents.AvailableModels(case conversation.get(ledger, id) { - Ok(info) -> child_models.available(host, config.home, info) - Error(_) -> [] - }), - ) + agents.Models(id, intent) -> { + use info <- result.try(conversation.get(ledger, id)) + let choices = child_models.available(host, config.home, info) + case intent { + None -> Ok(agents.AvailableModels(choices)) + Some("daybreak_blue") -> + list.try_fold(choices, [], fn(found, choice) { + use #(provider, model) <- result.try(child_models.resolve( + host, + config.home, + info, + choice, + )) + case provider.extension { + "codex" -> + case + runtime.cyber_access( + host, + info.id, + config.home, + provider.name, + provider.extension, + model, + provider.protocol, + ) + { + Ok(True) -> Ok([choice, ..found]) + Ok(False) -> Ok(found) + Error(reason) -> + Error( + "cannot verify Daybreak Blue for " + <> choice + <> ": " + <> reason, + ) + } + _ -> Ok(found) + } + }) + |> result.map(fn(found) { + agents.AvailableModels(list.reverse(found)) + }) + Some(_) -> Error("unsupported cyber_access") + } + } agents.Switch(caller, id, model) -> { use info <- result.try(conversation.get(ledger, id)) use #(provider, model) <- result.try(child_models.resolve_switch( @@ -685,13 +724,35 @@ pub fn start( agents.Switched(provider.name <> "/" <> model, pending) }) } - agents.Spawn(parent, _, _, model) -> - actor.call(self, 60_000, AgentOp( - op, - Some(resolve(parent, model)), - _, - )) + agents.Spawn(parent, _, _, model, intent) -> { + let choice = resolve(parent, model) + let checked = case choice, intent { + Ok(#(provider, selected)), Some("daybreak_blue") -> + case + runtime.cyber_access( + host, + parent, + config.home, + provider.name, + provider.extension, + selected, + provider.protocol, + ) + { + Ok(True) -> choice + Ok(False) -> + Error( + "Daybreak Blue unavailable for selected account/model", + ) + Error(reason) -> + Error("cannot verify Daybreak Blue: " <> reason) + } + _, None -> choice + _, Some(_) -> Error("unsupported cyber_access") + } + actor.call(self, 60_000, AgentOp(op, Some(checked), _)) |> result.try(run_agent_plan(self, _)) + } agents.Start(caller, _, _, model, _, _) -> actor.call(self, 60_000, AgentOp( op, @@ -963,6 +1024,7 @@ fn create_peer( selected_model, )), fast: False, + cyber_access: None, ) let role = string.trim(role) Ok(CreateAgent( @@ -993,6 +1055,7 @@ fn create_child( name: String, task: String, choice: child_models.Choice, + cyber_access: Option(String), ) -> Result(AgentPlan, String) { let db = runtime.ledger(state.host) use #(cached, _) <- result.try( @@ -1025,6 +1088,7 @@ fn create_child( protocol: provider.protocol, effort: extension.default_effort(efforts), fast: False, + cyber_access: cyber_access, ) Ok(CreateAgent( commit: fn() { @@ -1113,9 +1177,9 @@ fn agent_op( } } case op { - agents.Spawn(parent, name, task, _) -> #( + agents.Spawn(parent, name, task, _, intent) -> #( state, - create_child(state, parent, name, task, choice), + create_child(state, parent, name, task, choice, intent), ) agents.Start(caller, task, name, _, cwd, role) -> #( state, @@ -1162,7 +1226,7 @@ fn agent_op( #(state, closed |> result.replace(Answered(agents.Closed))) } // The agents seam answers this itself; listing can wait on endpoints. - agents.Models(_) | agents.Switch(..) -> #( + agents.Models(..) | agents.Switch(..) -> #( state, Error("models are listed outside the registry"), ) @@ -1338,6 +1402,7 @@ fn create_checked( model, effort, _, + cyber_access, ) -> { use workspace <- result.try( location.workspace(workspace) @@ -1382,6 +1447,7 @@ fn create_checked( None, effort, False, + cyber_access, )) } session_creation.AcpSession(workspace, _, _) -> { @@ -1408,6 +1474,7 @@ fn create_checked( None, effort, False, + None, )) } session_creation.ForkSession(source, _, _name) -> { @@ -1453,6 +1520,7 @@ fn create_checked( last_assistant_at: None, effort: effort, fast: False, + cyber_access: None, ), ) } @@ -1466,7 +1534,7 @@ fn create_checked( Ok(info) -> { let resolved = conversation.resolved_creation(info) let name = case intent { - session_creation.NewSession(_, name, _, _, _, _) + session_creation.NewSession(_, name, _, _, _, _, _) | session_creation.ForkSession(_, _, name) -> name session_creation.ChildSession(_, _, name, _, _, _, _) -> Some(name) session_creation.AcpSession(..) -> None diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 929b05bd5..8e38bc202 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -636,6 +636,7 @@ fn daemon( provider.protocol, None, False, + None, ) }, fn(provider, endpoint) { runtime.model_names(host, provider, endpoint) }, diff --git a/src/albedo/daemon/session/creation.gleam b/src/albedo/daemon/session/creation.gleam index 5908b3b52..e0185b8f8 100644 --- a/src/albedo/daemon/session/creation.gleam +++ b/src/albedo/daemon/session/creation.gleam @@ -20,6 +20,7 @@ pub type Intent { effort: Option(String), /// The window this session compacts against, instead of the model's. context_window: Option(Int), + cyber_access: Option(String), ) ForkSession( source_session_id: String, @@ -49,7 +50,7 @@ pub type Intent { /// this representation affects retries of previously recorded decisions. pub fn encode(intent: Intent) -> json.Json { json.object(case intent { - NewSession(workspace, name, provider, model, effort, window) -> + NewSession(workspace, name, provider, model, effort, window, cyber_access) -> list.flatten([ [ #("kind", json.string("new")), @@ -59,6 +60,10 @@ pub fn encode(intent: Intent) -> json.Json { #("model", json.nullable(model, json.string)), #("effort", json.nullable(effort, json.string)), ], + case cyber_access { + Some(access) -> [#("cyber_access", json.string(access))] + None -> [] + }, // Absent unless set, so earlier requests keep their fingerprints. case window { Some(tokens) -> [#("context_window", json.int(tokens))] diff --git a/src/albedo/daemon/session_configuration.gleam b/src/albedo/daemon/session_configuration.gleam index 58236338a..52e8b4636 100644 --- a/src/albedo/daemon/session_configuration.gleam +++ b/src/albedo/daemon/session_configuration.gleam @@ -40,6 +40,7 @@ pub type Configuration { model: String, effort: Option(String), fast: Bool, + cyber_access: Option(String), /// The window compaction measures against, instead of the model's. context_window: Option(Int), revision: Int, @@ -69,6 +70,7 @@ pub type Patch { model: Option(String), effort: Option(Option(String)), fast: Option(Bool), + cyber_access: Option(Option(String)), context_window: Option(Option(Int)), pinned: Option(Bool), archived: Option(Bool), @@ -149,6 +151,7 @@ pub fn apply(current: Configuration, patch: Patch) -> Configuration { model: option.unwrap(patch.model, current.model), effort: option.unwrap(patch.effort, current.effort), fast: option.unwrap(patch.fast, current.fast), + cyber_access: option.unwrap(patch.cyber_access, current.cyber_access), context_window: option.unwrap(patch.context_window, current.context_window), preferences: preferences, selection: Selection( @@ -243,7 +246,7 @@ pub fn commit_in( use _ <- result.try( store.run( db, - "UPDATE sessions SET name=?,provider=?,model=?,protocol=?,effort=?,fast=?,context_window=?,pinned=?,pin_order=?,archived=?,config_revision=config_revision+1 WHERE id=?", + "UPDATE sessions SET name=?,provider=?,model=?,protocol=?,effort=?,fast=?,cyber_access=?,context_window=?,pinned=?,pin_order=?,archived=?,config_revision=config_revision+1 WHERE id=?", [ nullable_text(candidate.name), sqlight.text(candidate.provider_profile), @@ -254,6 +257,7 @@ pub fn commit_in( True -> 1 False -> 0 }), + nullable_text(candidate.cyber_access), sqlight.nullable(sqlight.int, candidate.context_window), sqlight.int(case pinned { True -> 1 @@ -467,6 +471,10 @@ pub fn initialise_in(db: sqlight.Connection) -> Result(Nil, String) { #("pin_order", "INTEGER"), #("archived", "INTEGER NOT NULL DEFAULT 0 CHECK(archived IN (0,1))"), #("opens", "INTEGER NOT NULL DEFAULT 0 CHECK(opens >= 0)"), + #( + "cyber_access", + "TEXT CHECK(cyber_access IS NULL OR cyber_access = 'daybreak_blue')", + ), ]), ) store.exec( @@ -514,7 +522,7 @@ pub fn read_in( use selection <- result.try(selection_in(db, id)) store.one( db, - "SELECT name,title,COALESCE(desired_workspace,cwd),COALESCE(provider,''),model,effort,config_revision,pinned,pin_order,archived,opens,context_window,fast FROM sessions WHERE id=?", + "SELECT name,title,COALESCE(desired_workspace,cwd),COALESCE(provider,''),model,effort,config_revision,pinned,pin_order,archived,opens,context_window,fast,cyber_access FROM sessions WHERE id=?", [sqlight.text(id)], { use name <- decode.field(0, decode.optional(decode.string)) @@ -530,6 +538,7 @@ pub fn read_in( use opens <- decode.field(10, decode.int) use context_window <- decode.field(11, decode.optional(decode.int)) use fast <- decode.field(12, sqlight.decode_bool()) + use cyber_access <- decode.field(13, decode.optional(decode.string)) decode.success(Configuration( id, option.then(name, clean_name), @@ -539,6 +548,7 @@ pub fn read_in( model, effort, fast, + cyber_access, context_window, revision, family, diff --git a/src/albedo/daemon/session_configure.gleam b/src/albedo/daemon/session_configure.gleam index 403db5bc7..acaf0ed94 100644 --- a/src/albedo/daemon/session_configure.gleam +++ b/src/albedo/daemon/session_configure.gleam @@ -71,6 +71,15 @@ pub fn change( True -> config.Configuration(..candidate, fast: False) False -> candidate } + let candidate = case + patch.cyber_access, + candidate.provider_profile != current.provider_profile + || candidate.model != current.model + { + None, True -> config.Configuration(..candidate, cyber_access: None) + _, _ -> candidate + } + let cyber_changed = candidate.cyber_access != current.cyber_access let fast_changed = candidate.fast != current.fast let model_changed = candidate.provider_profile != current.provider_profile @@ -82,7 +91,10 @@ pub fn change( case { selection_changed - || { { model_changed || fast_changed } && !is_switch(request) } + || { + { model_changed || fast_changed || cyber_changed } + && !is_switch(request) + } } && { turn.running(state.activity) != None || state.booting != None } { @@ -133,6 +145,41 @@ pub fn change( } }, ) + use observed_provider <- result.try(case candidate.cyber_access { + None -> Ok(observed_provider) + Some("daybreak_blue") + if patch.cyber_access == None + && candidate.cyber_access == current.cyber_access + && candidate.model == current.model + && candidate.provider_profile == current.provider_profile + -> Ok(observed_provider) + Some("daybreak_blue") -> { + use provider <- result.try(configuration.named( + state.home, + candidate.provider_profile, + )) + use _ <- result.try( + case + runtime.cyber_access( + state.host, + state.info.id, + state.home, + candidate.provider_profile, + provider.extension, + candidate.model, + provider.protocol, + ) + { + Ok(True) -> Ok(Nil) + Ok(False) -> + Error("Daybreak Blue unavailable for selected account/model") + Error(reason) -> Error("cannot verify Daybreak Blue: " <> reason) + }, + ) + Ok(Some(provider)) + } + Some(_) -> Error("unsupported cyber_access") + }) let protocol = case observed_provider { Some(provider) -> provider.protocol None -> state.info.protocol @@ -202,7 +249,7 @@ pub fn change( saved, renumbered, model_changed, - window_changed || fast_changed, + window_changed || fast_changed || cyber_changed, )) } case prepared { @@ -227,6 +274,7 @@ pub fn change( protocol: protocol, effort: saved.effort, fast: saved.fast, + cyber_access: saved.cyber_access, ), history: history, context: case model_changed || context_changed { @@ -275,7 +323,12 @@ pub fn validate_switch( ) validate_model( state, - config.Configuration(..current, model: model, provider_profile: provider), + config.Configuration( + ..current, + model: model, + provider_profile: provider, + cyber_access: None, + ), True, SwitchModel(model, provider, "", 0), ) @@ -293,6 +346,7 @@ fn request_patch( model: None, effort: None, fast: None, + cyber_access: None, context_window: None, pinned: None, archived: None, @@ -311,6 +365,7 @@ fn request_patch( ..empty, model: Some(model), provider_profile: Some(provider), + cyber_access: Some(None), ), )) SelectModel(model, provider, effort, _) -> { diff --git a/src/albedo/daemon/session_provider.gleam b/src/albedo/daemon/session_provider.gleam index cfef94a7e..034446443 100644 --- a/src/albedo/daemon/session_provider.gleam +++ b/src/albedo/daemon/session_provider.gleam @@ -56,6 +56,7 @@ pub fn configured_client( state.info.protocol, state.info.effort, state.info.fast, + state.info.cyber_access, )) Ok(#(state, client)) } diff --git a/src/albedo/daemon/session_switch.gleam b/src/albedo/daemon/session_switch.gleam index 0155b7062..9601cf6c6 100644 --- a/src/albedo/daemon/session_switch.gleam +++ b/src/albedo/daemon/session_switch.gleam @@ -92,6 +92,7 @@ fn apply( provider.protocol, candidate.effort, False, + None, )) use inputs <- result.try(session_history.projected_for( loaded.history, diff --git a/src/albedo/harness/extension.gleam b/src/albedo/harness/extension.gleam index 240fe3567..800b65b28 100644 --- a/src/albedo/harness/extension.gleam +++ b/src/albedo/harness/extension.gleam @@ -266,6 +266,7 @@ pub type ModelContext { effort: Option(String), /// Whether this session explicitly requested provider fast mode. fast: Bool, + cyber_access: Option(String), ) } @@ -332,6 +333,14 @@ pub type Plugin { ModelsPlugin(catalog: ModelCatalog) /// A provider turns one tagged saved profile into its upstream. ModelProviderPlugin(provider: ModelProvider) + /// Authenticated capability for the exact selected account; unavailable is False, + /// a failed verification is Error. Only Codex contributes Blue. + CyberAccessPlugin(check: fn(ModelContext) -> Result(Bool, String)) + /// One authenticated account snapshot for all models in a picker page. + /// None is unverified metadata; never infer unsupported from a missing field. + CyberCatalogPlugin( + check: fn(ModelContext) -> Result(List(#(String, Option(Bool))), String), + ) /// A browser sign-in the daemon runs on behalf of clients. LoginPlugin(login: oauth.Login) /// Sign-ins named at request time, such as one per configured MCP server. @@ -1204,6 +1213,50 @@ pub fn fast_mode( )) } +pub fn cyber_catalog( + installed: List(Extension), + context: ModelContext, +) -> Result(List(#(String, Option(Bool))), String) { + installed + |> list.find_map(fn(item) { + case item.name == context.provider { + False -> Error(Nil) + True -> + item.plugins + |> list.find_map(fn(plugin) { + case plugin { + CyberCatalogPlugin(check) -> Ok(check(context)) + _ -> Error(Nil) + } + }) + } + }) + |> result.unwrap(Error( + "no enabled model provider extension verifies Daybreak Blue", + )) +} + +pub fn cyber_access( + installed: List(Extension), + context: ModelContext, +) -> Result(Bool, String) { + installed + |> list.find_map(fn(item) { + case item.name == context.provider { + False -> Error(Nil) + True -> + item.plugins + |> list.find_map(fn(plugin) { + case plugin { + CyberAccessPlugin(check) -> Ok(check(context)) + _ -> Error(Nil) + } + }) + } + }) + |> result.unwrap(Ok(False)) +} + pub fn upstream( installed: List(Extension), context: ModelContext, diff --git a/src/albedo/harness/extension/selection.gleam b/src/albedo/harness/extension/selection.gleam index db978c74a..3cf225883 100644 --- a/src/albedo/harness/extension/selection.gleam +++ b/src/albedo/harness/extension/selection.gleam @@ -566,6 +566,8 @@ pub fn summaries( extension.FoldPlugin(_) -> "folds" extension.ModelsPlugin(_) -> "models" extension.ModelProviderPlugin(_) -> "model_provider" + extension.CyberAccessPlugin(_) -> "cyber_access" + extension.CyberCatalogPlugin(_) -> "cyber_access" extension.LoginPlugin(_) -> "login" extension.LoginResolverPlugin(_) -> "login" extension.ServicePlugin(_) -> "service" diff --git a/src/albedo/harness/extensions/agents/extension.gleam b/src/albedo/harness/extensions/agents/extension.gleam index 8503d8998..0a388c53b 100644 --- a/src/albedo/harness/extensions/agents/extension.gleam +++ b/src/albedo/harness/extensions/agents/extension.gleam @@ -29,7 +29,7 @@ import gleam/string import sqlight const instructions = - "Agents are sessions you spawn to work in parallel; every call is async. A lead session can keep a few long-lived peers for distinct areas, reusing useful context and starting fresh when context is unrelated; the right set depends on the project. agents.self is your handle (id, name, depth, parent). Call await agents.models() once before spawning; every entry is provider/model, your own provider's included, and selecting one routes the child through that provider. Within the same model tier and family, prefer the one with the newest version number or release date: later versions are generally better, while usually being no more expensive. This doesn't change what tier you pick for a task. If the user asks for a specific model, use that one. Then child = await agents.self.spawn(task, name=\"scout\", model=, deliverable=None, evidence_bar=None, falsifier=None, verifier=None): it returns as soon as the child exists, and its answer arrives later as and wakes your next turn, so spawn independent children back to back and end your turn (verifier is an optional shell command that must exit 0 before the child can mail its parent or finish). Talk with await mail.submit(child, text). await agents.self.children() and siblings() return live snapshots (running, closed). running=False means no active turn; a new child may still be waiting for its kernel and have no transcript yet. It does not prove spawn failed; wait for its mail rather than cancelling it on that snapshot. await child.switch(model) returns {model: provider/model, pending: bool}; it switches your own child or peer at its next request without stopping its turn, replacing any pending switch, and mails you if late history projection fails. await child.cancel() stops its turn, and child.cancel(tree=True) the turns of everything beneath it; await agents.cancel_all(tree=True) stops every child you have, and their descendants, in one call, so use it when the user says to stop the swarm; await child.close() when you are done with it keeps its messages and files and frees its kernel. await agents.get(to) returns a live handle for \"parent\", a family name, or any session id. On any handle, await h.messages(seq=0, offset=0, limit=4000) reads a page of that session's messages from row seq on (content, next_offset) and await h.search_messages(pattern) finds rows by seq: any session may read any other, so you can see what a child or another session did without waiting for mail. await agents.sessions(query=\"\", cwd=None, limit=20, offset=0) lists every session, most recently active first, as snapshots that also carry cwd, model, last_active, and matches; with a query it keeps sessions whose title or name contains it or whose messages do, and matches holds up to 3 of each one's newest matching rows as {seq, preview} to read with messages(seq=...). cwd keeps one directory. await h.resources() on any handle returns the CPU and memory its session's kernel, jobs and their children use on this machine, with each process; await resources.query(query=\"\", process=None, cwd=None, session=None) totals the matching processes across sessions, filtered by name or command text, directory, or one session. await agents.start(task, name, model, cwd=None, role=None) starts a root peer you own, and await agents.set_role(text, id=None) labels one; failures raise AgentsError. Only the user deletes agents: if one should go, ask them. Children nest at most 3 deep and 12 open per parent; mail any session by id instead of nesting to reach it. Children share your workspace, so give two children the same files only if one only reads." + "Agents are sessions you spawn to work in parallel; every call is async. A lead session can keep a few long-lived peers for distinct areas, reusing useful context and starting fresh when context is unrelated; the right set depends on the project. agents.self is your handle (id, name, depth, parent). Call await agents.models() once before spawning; every entry is provider/model, your own provider's included, and selecting one routes the child through that provider. Call await agents.models(cyber_access=\"daybreak_blue\") for only models that the currently resolved Codex account of each profile advertises as Blue; unknown account/catalog state raises an error, and the provider can still refuse at request time. Blue children require agents.self.spawn(..., model=\"provider/model\", cyber_access=\"daybreak_blue\"); children without that opt-in are standard. Within the same model tier and family, prefer the one with the newest version number or release date: later versions are generally better, while usually being no more expensive. This doesn't change what tier you pick for a task. If the user asks for a specific model, use that one. Then child = await agents.self.spawn(task, name=\"scout\", model=, deliverable=None, evidence_bar=None, falsifier=None, verifier=None, cyber_access=None): it returns as soon as the child exists, and its answer arrives later as and wakes your next turn, so spawn independent children back to back and end your turn (verifier is an optional shell command that must exit 0 before the child can mail its parent or finish). Talk with await mail.submit(child, text). await agents.self.children() and siblings() return live snapshots (running, closed). running=False means no active turn; a new child may still be waiting for its kernel and have no transcript yet. It does not prove spawn failed; wait for its mail rather than cancelling it on that snapshot. await child.switch(model) returns {model: provider/model, pending: bool}; it switches your own child or peer at its next request without stopping its turn, replacing any pending switch, and mails you if late history projection fails. await child.cancel() stops its turn, and child.cancel(tree=True) the turns of everything beneath it; await agents.cancel_all(tree=True) stops every child you have, and their descendants, in one call, so use it when the user says to stop the swarm; await child.close() when you are done with it keeps its messages and files and frees its kernel. await agents.get(to) returns a live handle for \"parent\", a family name, or any session id. On any handle, await h.messages(seq=0, offset=0, limit=4000) reads a page of that session's messages from row seq on (content, next_offset) and await h.search_messages(pattern) finds rows by seq: any session may read any other, so you can see what a child or another session did without waiting for mail. await agents.sessions(query=\"\", cwd=None, limit=20, offset=0) lists every session, most recently active first, as snapshots that also carry cwd, model, last_active, and matches; with a query it keeps sessions whose title or name contains it or whose messages do, and matches holds up to 3 of each one's newest matching rows as {seq, preview} to read with messages(seq=...). cwd keeps one directory. await h.resources() on any handle returns the CPU and memory its session's kernel, jobs and their children use on this machine, with each process; await resources.query(query=\"\", process=None, cwd=None, session=None) totals the matching processes across sessions, filtered by name or command text, directory, or one session. await agents.start(task, name, model, cwd=None, role=None) starts a root peer you own, and await agents.set_role(text, id=None) labels one; failures raise AgentsError. Only the user deletes agents: if one should go, ask them. Children nest at most 3 deep and 12 open per parent; mail any session by id instead of nesting to reach it. Children share your workspace, so give two children the same files only if one only reads." pub fn extension() -> extension.Extension { extension.Extension( @@ -180,6 +180,23 @@ fn handle( ) } +fn cyber_arg(args: dynamic.Dynamic) -> Result(Option(String), String) { + use intent <- result.try(rpc.args( + args, + decode.optional_field( + "cyber_access", + None, + decode.optional(decode.string), + decode.success, + ), + "cyber_access must be daybreak_blue or null", + )) + case intent { + None | Some("daybreak_blue") -> Ok(intent) + Some(_) -> Error("cyber_access must be daybreak_blue or null") + } +} + fn text(args: dynamic.Dynamic, name: String) -> Result(String, String) { rpc.args( args, @@ -215,13 +232,15 @@ fn dispatch( ), ) } - "agents.models" -> - case agents.call(agents.Models(session)) { + "agents.models" -> { + use cyber_access <- result.try(cyber_arg(args)) + case agents.call(agents.Models(session, cyber_access)) { Ok(agents.AvailableModels(models)) -> Ok(json.array(models, json.string)) Ok(_) -> Ok(json.array([], json.string)) Error(error) -> Error(error) } + } "agents.start" -> { use task <- result.try(text(args, "task")) use name <- result.try(text(args, "name")) @@ -270,8 +289,9 @@ fn dispatch( _, _, True -> Ok(Nil) }, ) + use cyber_access <- result.try(cyber_arg(args)) use spawned <- result.try( - agents.call(agents.Spawn(session, name, task, model)), + agents.call(agents.Spawn(session, name, task, model, cyber_access)), ) case spawned { agents.Spawned(member) -> { diff --git a/src/albedo/harness/extensions/agents/sessions.gleam b/src/albedo/harness/extensions/agents/sessions.gleam index 1d345a78f..f45cc2dee 100644 --- a/src/albedo/harness/extensions/agents/sessions.gleam +++ b/src/albedo/harness/extensions/agents/sessions.gleam @@ -89,7 +89,8 @@ fn listed( [sqlight.text(cwd), sqlight.text(cwd)], { use info <- decode.then(conversation.info_decoder()) - use name <- decode.field(10, decode.string) + // info_columns has 11 fields; the appended family name follows cyber_access. + use name <- decode.field(11, decode.string) decode.success(#(info, name)) }, ) diff --git a/src/albedo/harness/extensions/claude/extension.gleam b/src/albedo/harness/extensions/claude/extension.gleam index 34f31d8e7..39888dcd4 100644 --- a/src/albedo/harness/extensions/claude/extension.gleam +++ b/src/albedo/harness/extensions/claude/extension.gleam @@ -198,6 +198,7 @@ fn search(query: web_search.Query) -> Result(web_search.Answer, String) { types.ChatCompletions, None, False, + None, )), ) use model <- result.try(case web_search.configured_model(search_settings()) { diff --git a/src/albedo/harness/extensions/codex/catalog.gleam b/src/albedo/harness/extensions/codex/catalog.gleam index 50a811dc2..a410338e0 100644 --- a/src/albedo/harness/extensions/codex/catalog.gleam +++ b/src/albedo/harness/extensions/codex/catalog.gleam @@ -4,6 +4,8 @@ //// soon as the backend lists it. import albedo/clock +import gleam/bit_array +import gleam/crypto import albedo/harness/extension import albedo/openai_api/types @@ -30,6 +32,7 @@ pub type Model { input: List(String), efforts: List(String), service_tiers: Option(List(#(String, String))), + cyber_programs: Option(List(String)), visible: Bool, priority: Int, ) @@ -215,6 +218,198 @@ fn account_fast_mode( } } +/// A successful refresh identifies the bearer that supplied the account's +/// metadata. Another refresh between validation and reading fails closed. +pub fn blue_models( + home: String, + access: String, + account: String, +) -> Result(List(String), String) { + blue_models_at(home, access, account, clock.os_system_ms(), native_get) +} + +/// Scripted transport seam for account/bearer capability regressions. +pub fn blue_models_at( + home: String, + access: String, + account: String, + now: Int, + get: fn(String, List(#(String, String))) -> Result(Response, Nil), +) -> Result(List(String), String) { + use _ <- result.try(refresh_at(home, access, account, max_age_ms, now, get)) + blue_models_from_cache(home, access, account, now, get, None, False) +} + +pub fn blue_model( + home: String, + access: String, + account: String, + model: String, +) -> Result(Bool, String) { + blue_model_at(home, access, account, model, clock.os_system_ms(), native_get) +} + +/// The same per-attempt capability path with an injected clock and transport. +pub fn blue_model_at( + home: String, + access: String, + account: String, + model: String, + now: Int, + get: fn(String, List(#(String, String))) -> Result(Response, Nil), +) -> Result(Bool, String) { + use _ <- result.try(refresh_at(home, access, account, max_age_ms, now, get)) + blue_models_from_cache(home, access, account, now, get, Some(model), False) + |> result.map(fn(models) { list.contains(models, model) }) +} + +/// A single account/bearer snapshot for model lists. Missing legacy metadata +/// stays unknown after one forced authenticated refresh, not unsupported. +pub fn blue_statuses_at( + home: String, + access: String, + account: String, + now: Int, + get: fn(String, List(#(String, String))) -> Result(Response, Nil), +) -> Result(List(#(String, Option(Bool))), String) { + use _ <- result.try(refresh_at(home, access, account, max_age_ms, now, get)) + use rows <- result.try(verified_models(home, access, account)) + let checked = rows + let rows = case + list.any(checked, fn(model) { model.cyber_programs == None }) + { + False -> Ok(checked) + True -> + case refresh_with(home, access, account, max_age_ms, now, get, True) { + Ok(_) -> verified_models(home, access, account) + // A stale/missing legacy row does not invalidate known metadata from + // this verified bearer. Its own status remains unknown (None). + Error(_) -> Ok(checked) + } + } + use rows <- result.try(rows) + Ok( + list.map(rows, fn(model) { + #( + model.slug, + option.map(model.cyber_programs, fn(programs) { + list.contains(programs, "daybreak_blue") + }), + ) + }), + ) +} + +pub fn blue_statuses( + home: String, + access: String, + account: String, +) -> Result(List(#(String, Option(Bool))), String) { + blue_statuses_at(home, access, account, clock.os_system_ms(), native_get) +} + +fn verified_models( + home: String, + access: String, + account: String, +) -> Result(List(Model), String) { + use bytes <- result.try( + native_read(home) + |> result.replace_error("Codex model metadata is unavailable"), + ) + use fields <- result.try( + json.parse_bits(bytes, decode.dict(decode.string, decode.dynamic)) + |> result.replace_error("Codex model metadata is invalid"), + ) + use accounts <- result.try( + dict.get(fields, "accounts") + |> result.replace_error("ChatGPT account metadata is unavailable") + |> result.try(fn(raw) { + decode.run(raw, decode.dict(decode.string, decode.dynamic)) + |> result.replace_error("ChatGPT account metadata is invalid") + }), + ) + use raw <- result.try( + dict.get(accounts, account) + |> result.replace_error( + "this ChatGPT account has no verified model metadata", + ), + ) + use entry <- result.try( + decode.run(raw, decode.dict(decode.string, decode.dynamic)) + |> result.replace_error("ChatGPT account metadata is invalid"), + ) + use _ <- result.try( + case value(entry, "accessHash", decode.string, "") == access_hash(access) { + True -> Ok(Nil) + False -> + Error("ChatGPT account bearer changed during capability verification") + }, + ) + use rows <- result.try( + dict.get(entry, "models") + |> result.replace_error("ChatGPT account model metadata is unavailable") + |> result.try(fn(raw) { + decode.run(raw, decode.list(model_decoder())) + |> result.replace_error("ChatGPT account model metadata is invalid") + }), + ) + Ok(rows) +} + +fn blue_models_from_cache( + home: String, + access: String, + account: String, + now: Int, + get: fn(String, List(#(String, String))) -> Result(Response, Nil), + selected: Option(String), + retried: Bool, +) -> Result(List(String), String) { + use rows <- result.try(verified_models(home, access, account)) + let checked = case selected { + Some(slug) -> list.filter(rows, fn(model) { model.slug == slug }) + None -> list.filter(rows, fn(model) { model.visible }) + } + let missing = list.any(checked, fn(model) { model.cyber_programs == None }) + let unverified = + selected != None + || list.all(checked, fn(model) { model.cyber_programs == None }) + case missing, retried { + True, False -> { + use _ <- result.try(refresh_with( + home, + access, + account, + max_age_ms, + now, + get, + True, + )) + blue_models_from_cache(home, access, account, now, get, selected, True) + } + True, True if unverified -> + Error("ChatGPT account catalog does not advertise cyber-access metadata") + _, _ -> + Ok( + checked + |> list.filter(fn(model) { + { selected != None || model.visible } + && list.contains( + option.unwrap(model.cyber_programs, []), + "daybreak_blue", + ) + }) + |> list.map(fn(model) { model.slug }), + ) + } +} + +fn access_hash(access: String) -> String { + crypto.hash(crypto.Sha256, bit_array.from_string(access)) + |> bit_array.base16_encode +} + /// Every account's models, the first account's first, each slug once. fn models(home: String) -> List(Model) { case cache(home) { @@ -298,6 +493,11 @@ fn model_decoder() -> decode.Decoder(Model) { decode.success(None), ]), ) + use cyber_programs <- decode.optional_field( + "cyber_programs", + None, + decode.optional(decode.list(decode.string)), + ) use visible <- decode.optional_field("visible", True, decode.bool) use priority <- decode.optional_field("priority", 1_000_000, decode.int) decode.success(Model( @@ -308,6 +508,7 @@ fn model_decoder() -> decode.Decoder(Model) { input, usable_efforts(efforts), service_tiers, + cyber_programs, visible, priority, )) @@ -335,6 +536,18 @@ pub fn refresh_at( max_age_ms: Int, now: Int, get: fn(String, List(#(String, String))) -> Result(Response, Nil), +) -> Result(Nil, String) { + refresh_with(home, access, account, max_age_ms, now, get, False) +} + +fn refresh_with( + home: String, + access: String, + account: String, + max_age_ms: Int, + now: Int, + get: fn(String, List(#(String, String))) -> Result(Response, Nil), + force: Bool, ) -> Result(Nil, String) { let cached = case native_read(home) { Ok(bytes) -> @@ -359,11 +572,17 @@ pub fn refresh_at( let fresh = now - value(entry, "fetchedAt", decode.int, 0) < max_age_ms && value(entry, "clientVersion", decode.string, "") == version - case fresh { + && value(entry, "accessHash", decode.string, "") == access_hash(access) + case fresh && !force { True -> Ok(Nil) False -> { use etag <- result.try( - case value(entry, "clientVersion", decode.string, "") == version { + case + !force + && value(entry, "clientVersion", decode.string, "") == version + && value(entry, "accessHash", decode.string, "") + == access_hash(access) + { True -> case dict.get(entry, "etag") { Error(_) -> Ok("") @@ -398,6 +617,7 @@ pub fn refresh_at( selected |> dict.insert("fetchedAt", json.int(now)) |> dict.insert("clientVersion", json.string(version)) + |> dict.insert("accessHash", json.string(access_hash(access))) let accounts = encode_fields(accounts) |> dict.insert(account, encode_object(selected)) @@ -573,6 +793,17 @@ pub fn normalize(rows: List(Dynamic)) -> List(Model) { decode.run(raw_tiers, decode.list(service_tier_decoder())) |> option.from_result } + let cyber_programs = case + dict.get(fields, "available_access_programs") + { + Error(_) -> None + Ok(raw) -> + decode.run(raw, { + use cyber <- decode.field("cyber", decode.list(decode.string)) + decode.success(cyber) + }) + |> option.from_result + } Ok(Model( slug, case name { @@ -584,6 +815,7 @@ pub fn normalize(rows: List(Dynamic)) -> List(Model) { input, usable_efforts(efforts), service_tiers, + cyber_programs, case dict.get(fields, "visibility") { Error(_) -> True Ok(raw) -> decode.run(raw, decode.string) == Ok("list") @@ -613,6 +845,13 @@ fn encode_model(model: Model) -> json.Json { #("visible", json.bool(model.visible)), #("priority", json.int(model.priority)), ] + let fields = case model.cyber_programs { + None -> fields + Some(programs) -> [ + #("cyber_programs", json.array(programs, json.string)), + ..fields + ] + } let fields = case model.service_tiers { None -> fields Some(tiers) -> [ @@ -639,6 +878,7 @@ fn validate_metadata( #(cached, "clientVersion", decode.string |> decode.map(fn(_) { Nil })), #(cached, "versionCheckedAt", decode.int |> decode.map(fn(_) { Nil })), #(entry, "clientVersion", decode.string |> decode.map(fn(_) { Nil })), + #(entry, "accessHash", decode.string |> decode.map(fn(_) { Nil })), #(entry, "fetchedAt", decode.int |> decode.map(fn(_) { Nil })), ] list.try_each(checks, fn(check) { diff --git a/src/albedo/harness/extensions/codex/extension.gleam b/src/albedo/harness/extensions/codex/extension.gleam index 8153150f0..28bc42d04 100644 --- a/src/albedo/harness/extensions/codex/extension.gleam +++ b/src/albedo/harness/extensions/codex/extension.gleam @@ -40,6 +40,8 @@ pub fn extension() -> extension.Extension { resolve, Some(fast_mode), )), + extension.CyberAccessPlugin(blue_mode), + extension.CyberCatalogPlugin(blue_catalog), extension.LoginPlugin(login()), extension.ModelsPlugin(extension.ModelCatalog(lookup, list_models, None)), extension.SearchPlugin(web_search.Provider("codex", "ChatGPT", search)), @@ -164,6 +166,31 @@ fn fast_mode(context: extension.ModelContext) -> extension.FastMode { } } +fn blue_catalog( + context: extension.ModelContext, +) -> Result(List(#(String, Option(Bool))), String) { + use access <- result.try(account( + context.home, + context.session, + context.profile, + )) + catalog.blue_statuses(context.home, access.token, access.account_id) +} + +fn blue_mode(context: extension.ModelContext) -> Result(Bool, String) { + use access <- result.try(account( + context.home, + context.session, + context.profile, + )) + catalog.blue_model( + context.home, + access.token, + access.account_id, + context.model, + ) +} + fn resolve( context: extension.ModelContext, ) -> Option(Result(extension.Upstream, String)) { @@ -182,6 +209,7 @@ fn resolve( context.session, context.profile, context.fast, + context.cyber_access, openai_api.stream, ), client_for(access, context.session), @@ -230,7 +258,7 @@ pub fn pool( stream: fn(types.Client, types.Request, fn(types.Event) -> types.Control) -> Result(types.Turn, types.Error), ) -> rotation.Pool(types.Client) { - profile_pool_with_fast(home, session, "", fast, stream) + profile_pool_with_fast(home, session, "", fast, None, stream) } /// The profile's pinned account, explicit rotation, or single plain account. @@ -241,7 +269,7 @@ pub fn profile_pool( stream: fn(types.Client, types.Request, fn(types.Event) -> types.Control) -> Result(types.Turn, types.Error), ) -> rotation.Pool(types.Client) { - profile_pool_with_fast(home, session, profile, False, stream) + profile_pool_with_fast(home, session, profile, False, None, stream) } fn profile_pool_with_fast( @@ -249,6 +277,7 @@ fn profile_pool_with_fast( session: String, profile: String, fast: Bool, + cyber_access: Option(String), stream: fn(types.Client, types.Request, fn(types.Event) -> types.Control) -> Result(types.Turn, types.Error), ) -> rotation.Pool(types.Client) { @@ -260,6 +289,9 @@ fn profile_pool_with_fast( same: rotation.same_client, stream: fn(client, request, on_event) { request_for_mode(home, client, request, fast) + |> result.try(fn(request) { + request_for_cyber(home, client, request, cyber_access) + }) |> result.try(fn(request) { stream(client, request, on_event) }) }, reject: fn(client) { @@ -309,6 +341,61 @@ fn request_for_mode( } } +fn request_for_cyber( + home: String, + client: types.Client, + request: types.Request, + intent: Option(String), +) -> Result(types.Request, types.Error) { + request_for_cyber_with(home, client, request, intent, catalog.blue_model) +} + +/// Per-attempt Blue gate; the verifier is injectable for offline rotation tests. +pub fn request_for_cyber_with( + home: String, + client: types.Client, + request: types.Request, + intent: Option(String), + verify: fn(String, String, String, String) -> Result(Bool, String), +) -> Result(types.Request, types.Error) { + case intent, client.policy { + None, _ -> + Ok( + types.Request( + ..request, + options: types.Options(..request.options, cyber_access: None), + ), + ) + Some("daybreak_blue"), types.Codex(account_id, _) -> + case verify(home, client.api_key, account_id, request.model) { + Ok(eligible) -> + case eligible { + True -> + Ok( + types.Request( + ..request, + options: types.Options( + ..request.options, + cyber_access: Some("daybreak_blue"), + ), + ), + ) + False -> + Error(types.InvalidRequest( + "Daybreak Blue unavailable for attempted ChatGPT account/model", + )) + } + Error(reason) -> + Error(types.InvalidRequest( + "cannot verify Daybreak Blue for attempted ChatGPT account: " + <> reason, + )) + } + _, _ -> + Error(types.InvalidRequest("Daybreak Blue requires a Codex account")) + } +} + /// Records the limit a 429 reports against this client's account. fn limited( home: String, diff --git a/src/albedo/harness/extensions/codex/search.gleam b/src/albedo/harness/extensions/codex/search.gleam index 08a231ea0..6befe0675 100644 --- a/src/albedo/harness/extensions/codex/search.gleam +++ b/src/albedo/harness/extensions/codex/search.gleam @@ -85,7 +85,8 @@ pub fn run( )) } -fn body(model: String, text: String) -> json.Json { +/// Search is a separate Standard Responses request; it never inherits a session's Blue model-inference intent. +pub fn body(model: String, text: String) -> json.Json { json.object([ #("model", json.string(model)), #("instructions", json.string(web_search.instructions)), diff --git a/src/albedo/harness/extensions/proxy/chat.gleam b/src/albedo/harness/extensions/proxy/chat.gleam index a5d5c6d29..56718547e 100644 --- a/src/albedo/harness/extensions/proxy/chat.gleam +++ b/src/albedo/harness/extensions/proxy/chat.gleam @@ -310,6 +310,7 @@ fn options_decoder() -> decode.Decoder(types.Options) { parallel, option.or(effort, nested_effort), None, + None, format, True, True, diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index e3ec8982f..74f022e06 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -1626,11 +1626,66 @@ pub fn fast_mode( protocol, effort, False, + None, ), ) } } +/// Resolve one account/bearer capability snapshot for a whole model-list request. +/// Missing metadata is None (unknown), not an unsupported model. +pub fn cyber_catalog( + runtime: Runtime, + session: String, + home: String, + profile: String, + provider: String, + protocol: types.Protocol, +) -> Result(List(#(String, Option(Bool))), String) { + use selected <- result.try(enabled_for(runtime, session)) + extension.cyber_catalog( + selected, + extension.ModelContext( + home, + session, + profile, + provider, + "", + protocol, + None, + False, + None, + ), + ) +} + +/// Check account-specific Blue advertisement without starting a kernel. +pub fn cyber_access( + runtime: Runtime, + session: String, + home: String, + profile: String, + provider: String, + model: String, + protocol: types.Protocol, +) -> Result(Bool, String) { + use selected <- result.try(enabled_for(runtime, session)) + extension.cyber_access( + selected, + extension.ModelContext( + home, + session, + profile, + provider, + model, + protocol, + None, + False, + None, + ), + ) +} + pub fn upstream( runtime: Runtime, session: String, @@ -1641,6 +1696,7 @@ pub fn upstream( protocol: types.Protocol, effort: Option(String), fast: Bool, + cyber_access: Option(String), ) -> Result(extension.Upstream, String) { use edge <- result.try(case profile { "" -> Ok(None) @@ -1659,6 +1715,7 @@ pub fn upstream( protocol, effort, fast, + cyber_access, ) use _ <- result.try(case fast { False -> Ok(Nil) @@ -1671,6 +1728,11 @@ pub fn upstream( Error("cannot verify fast mode: " <> reason) } }) + use _ <- result.try(case cyber_access { + None -> Ok(Nil) + Some("daybreak_blue") -> Ok(Nil) + Some(_) -> Error("unsupported cyber_access") + }) use upstream <- result.map(extension.upstream(selected, context)) let upstream = case reads_text_only( diff --git a/src/albedo/openai_api/request.gleam b/src/albedo/openai_api/request.gleam index eebd48285..d9fa1fded 100644 --- a/src/albedo/openai_api/request.gleam +++ b/src/albedo/openai_api/request.gleam @@ -166,6 +166,16 @@ pub fn encode_with_policy( types.OpenCodeGo(_, _) | types.OpenCodeZen(_, _, _) | types.Mistral(_) -> fields } + let fields = case policy, protocol, options.cyber_access { + Codex(_, _), Responses, Some("daybreak_blue") -> [ + #( + "access_programs", + json.object([#("cyber", json.string("daybreak_blue"))]), + ), + ..fields + ] + _, _, _ -> fields + } Ok(json.to_string_tree(json.object(fields))) } diff --git a/src/albedo/openai_api/types.gleam b/src/albedo/openai_api/types.gleam index 9026a2abd..b3f452205 100644 --- a/src/albedo/openai_api/types.gleam +++ b/src/albedo/openai_api/types.gleam @@ -254,6 +254,8 @@ pub type Options { effort: Option(String), /// Explicit provider processing tier; absent keeps its normal default. service_tier: Option(String), + /// Explicit Codex-only cyber program. Never interpreted as a model ID. + cyber_access: Option(String), format: Option(Format), /// Whether the request asks the provider to write a prompt cache. A /// one-off request, such as a summary nobody sends again, should not @@ -266,7 +268,7 @@ pub type Options { } pub const defaults = - Options(None, None, [], None, None, None, None, None, True, True) + Options(None, None, [], None, None, None, None, None, None, True, True) pub type ToolChoice { AnyTool diff --git a/test.sh b/test.sh index e0d6c1d45..debaeb3e1 100755 --- a/test.sh +++ b/test.sh @@ -99,7 +99,7 @@ changed() { suite "gleam test" gleam test suite "python harness" python3 test/python_test_runner.py --jobs "$ALBEDO_TEST_HARNESS_JOBS" test/harness/*_test.py suite "go test" go -C cli test ./internal/... ./cmd/... -suite "web client" node --test web/scripts/search.test.mjs web/scripts/commands.test.mjs web/scripts/transcript.test.mjs web/scripts/context.test.mjs web/scripts/shell-output.test.mjs web/scripts/dev-proxy.test.mjs web/scripts/agent-order.test.mjs web/scripts/terminal-theme.test.mjs +suite "web client" node --test web/scripts/search.test.mjs web/scripts/new-session.test.mjs web/scripts/commands.test.mjs web/scripts/transcript.test.mjs web/scripts/context.test.mjs web/scripts/shell-output.test.mjs web/scripts/dev-proxy.test.mjs web/scripts/agent-order.test.mjs web/scripts/terminal-theme.test.mjs # the Go e2e suite builds its own CLI and boots a hermetic daemon, so it must # never reuse a cached run. Bound parallel scenarios while the other suites run. go_parallel="$ALBEDO_TEST_GO_JOBS" diff --git a/test/daemon/bedrock_replay_preflight_test.gleam b/test/daemon/bedrock_replay_preflight_test.gleam index 32ac54597..7278aebf2 100644 --- a/test/daemon/bedrock_replay_preflight_test.gleam +++ b/test/daemon/bedrock_replay_preflight_test.gleam @@ -143,6 +143,7 @@ fn state(home: String, host: runtime.Runtime) -> session_state.State(Nil) { None, None, False, + None, ) let ledger = runtime.ledger(host) let assert Ok(_) = conversation.create(ledger, info) @@ -348,6 +349,62 @@ pub fn same_model_native_reasoning_and_tool_metadata_switch_still_applies_test() Nil } +/// Unrelated actor-side edits do not wait on a stale Blue catalog or fail +/// merely because its capability could not be reverified now. +pub fn blue_rename_skips_capability_lookup_and_preserves_saved_intent_test() -> Nil { + use home <- with_home + use original <- fixture(home) + let info = + conversation.Info( + ..original.info, + id: "blue-unrelated-rename", + cyber_access: Some("daybreak_blue"), + ) + let assert Ok(_) = conversation.create(runtime.ledger(original.host), info) + let state = + session_state.State(..original, info: info, booting: Some(#(1, []))) + let #(changed, outcome) = + session_configure.change( + state, + session_configure.SelectName(Some("safe rename")), + ) + let assert Ok(_) = outcome + saved(changed).name |> should.equal(Some("safe rename")) + saved(changed).cyber_access |> should.equal(Some("daybreak_blue")) +} + +/// A queued legacy switch must never run a Standard upstream with persisted Blue. +pub fn busy_blue_switch_clears_intent_for_same_and_changed_model_test() -> Nil { + use home <- with_home + use original <- fixture(home) + list.each([origin, target], fn(model) { + let info = + conversation.Info( + ..original.info, + id: "blue-" <> model, + cyber_access: Some("daybreak_blue"), + ) + let assert Ok(_) = conversation.create(runtime.ledger(original.host), info) + let state = + session_state.State(..original, info: info, booting: Some(#(1, []))) + let assert Some("daybreak_blue") = saved(state).cyber_access + let assert Ok(#(_, _, candidate)) = + session_configure.validate_switch(state, model, "converse") + candidate.cyber_access |> should.equal(None) + let #(queued, result) = + session_switch.queue(state, "parent", "converse", model) + result |> should.equal(Ok(True)) + saved(queued).cyber_access |> should.equal(Some("daybreak_blue")) + let #(changed, selection) = + session_switch.apply_pending(session_state.State(..queued, booting: None)) + let assert Some(applied) = selection + applied.model |> should.equal(model) + changed.info.cyber_access |> should.equal(None) + saved(changed).cyber_access |> should.equal(None) + saved(changed).model |> should.equal(model) + }) +} + pub fn untyped_and_plaintext_history_accept_cross_model_and_other_modes_are_unchanged_test() -> Nil { use home <- with_home use state <- fixture(home) diff --git a/test/daemon/conversation_test.gleam b/test/daemon/conversation_test.gleam index a561f0fcc..bd48fde5c 100644 --- a/test/daemon/conversation_test.gleam +++ b/test/daemon/conversation_test.gleam @@ -27,6 +27,7 @@ fn session(id: String) -> conversation.Info { None, None, False, + None, ) } diff --git a/test/daemon/image_store_test.gleam b/test/daemon/image_store_test.gleam index 1c9d4567b..a30f4b866 100644 --- a/test/daemon/image_store_test.gleam +++ b/test/daemon/image_store_test.gleam @@ -54,6 +54,7 @@ fn session(id: String) -> conversation.Info { None, None, False, + None, ) } diff --git a/test/daemon/mail_commit_test.gleam b/test/daemon/mail_commit_test.gleam index 50a459ab3..de523f787 100644 --- a/test/daemon/mail_commit_test.gleam +++ b/test/daemon/mail_commit_test.gleam @@ -35,6 +35,7 @@ pub fn close_before_mail_commit_rolls_back_turn_and_preserves_letter_test() -> N None, None, False, + None, ) let assert Ok(_) = conversation.create(ledger, parent) let assert Ok(_) = diff --git a/test/daemon/transcript_sources_test.gleam b/test/daemon/transcript_sources_test.gleam index 259c27d57..748d03c4a 100644 --- a/test/daemon/transcript_sources_test.gleam +++ b/test/daemon/transcript_sources_test.gleam @@ -66,6 +66,7 @@ fn session() -> conversation.Info { None, None, False, + None, ) } diff --git a/test/e2e/bedrock_effort_catalog_test.py b/test/e2e/bedrock_effort_catalog_test.py index f8ae2f835..d2adc814b 100644 --- a/test/e2e/bedrock_effort_catalog_test.py +++ b/test/e2e/bedrock_effort_catalog_test.py @@ -130,12 +130,14 @@ class BedrockEffortCatalogTests(unittest.TestCase): def test_profile_catalog_list_manual_and_legacy_are_consistent(self): [generic] = self.models(provider="bedrock", model=KNOWN) self.assertEqual(self.efforts(generic), GENERIC) + self.assertEqual(generic["cyber_access"]["status"], "unsupported") rows = {row["id"]: row for row in self.models(provider_profile="converse")} self.assertEqual(set(rows), {KNOWN, UNKNOWN, OPAQUE}) for model, expected in ((KNOWN, VERIFIED), (UNKNOWN, []), (OPAQUE, [])): with self.subTest(model=model): [manual] = self.models(provider_profile="converse", model=model) self.assertEqual(manual, rows[model]) + self.assertEqual(manual["cyber_access"]["status"], "unsupported") self.assertEqual(self.efforts(manual), expected) # Only effort changes. Existing catalog windows remain facts. [prior] = self.models( diff --git a/test/e2e/fast_mode_test.py b/test/e2e/fast_mode_test.py index 4b976307e..521d70d29 100644 --- a/test/e2e/fast_mode_test.py +++ b/test/e2e/fast_mode_test.py @@ -4,6 +4,7 @@ These offline real-daemon scenarios cover adapters without fast mode, conditiona state updates, and the account-specific Codex tier cache without live requests. """ +import hashlib import json import time import threading @@ -160,6 +161,9 @@ class CodexFastModeTests(unittest.TestCase): "acct-one": { "fetchedAt": now, "clientVersion": "1.2.3", + "accessHash": hashlib.sha256(b"dummy-access") + .hexdigest() + .upper(), "models": [ { "slug": "fixture-codex", @@ -195,6 +199,11 @@ class CodexFastModeTests(unittest.TestCase): "protocol": "responses", "accountId": "one", }, + "codex-unpinned": { + "extension": "codex", + "model": "fixture-codex", + "protocol": "responses", + }, }, ) app.__enter__() @@ -211,6 +220,177 @@ class CodexFastModeTests(unittest.TestCase): ) as response: return json.load(response) + def test_blue_capability_and_configuration_are_account_bound_and_persisted(self): + + def prepare_blue(app): + self.prepare_codex(app) + path = app.home / "codex-models.json" + cache = json.loads(path.read_text()) + entry = cache["accounts"]["acct-one"] + entry["accessHash"] = hashlib.sha256(b"dummy-access").hexdigest().upper() + entry["models"][0]["cyber_programs"] = ["daybreak_blue"] + path.write_text(json.dumps(cache)) + + app = self.app_with_codex(prepare=prepare_blue) + session = app.session() + route = f"/sessions/{session}?view=configuration" + query = ( + f"/models?provider_profile=codex-fixture&model=fixture-codex" + f"&session={session}" + ) + with app.api(query) as response: + [model] = json.load(response)["items"] + self.assertEqual(model["cyber_access"]["status"], "supported") + + self.patch_configuration( + app, + session, + {"provider_profile": "codex-fixture", "model": "fixture-codex"}, + ) + saved = self.patch_configuration( + app, session, {"cyber_access": "daybreak_blue"} + ) + self.assertEqual(saved["resource"]["value"]["cyber_access"], "daybreak_blue") + initial_id = operation_id() + with app.api( + f"/models?provider_profile=codex-fixture&model=fixture-codex&session={initial_id}&initial=true" + ) as response: + [preview] = json.load(response)["items"] + self.assertEqual(preview["cyber_access"]["status"], "supported") + with self.assertRaises(urllib.error.HTTPError) as existing: + app.api( + f"/models?provider_profile=codex-fixture&model=fixture-codex&session={session}&initial=true" + ) + self.assertEqual(existing.exception.code, 400) + with app.api( + f"/sessions/{initial_id}", + { + "kind": "new", + "workspace": str(app.workspace), + "provider_profile": "codex-fixture", + "model": "fixture-codex", + "cyber_access": "daybreak_blue", + }, + method="PUT", + headers={"If-None-Match": "*"}, + ) as response: + self.assertEqual(json.load(response)["cyber_access"], "daybreak_blue") + app.restart() + with app.api(route) as response: + self.assertEqual(json.load(response)["cyber_access"], "daybreak_blue") + etag = response.headers["ETag"] + with self.assertRaises(urllib.error.HTTPError) as refused: + app.api( + route, + {"cyber_access": "daybreak_red"}, + method="PATCH", + headers={"If-Match": etag}, + ) + self.assertEqual(refused.exception.code, 400) + with app.api(route) as response: + self.assertEqual(json.load(response)["cyber_access"], "daybreak_blue") + self.assertEqual(response.headers["ETag"], etag) + cleared = self.patch_configuration(app, session, {"cyber_access": None}) + self.assertIsNone(cleared["resource"]["value"]["cyber_access"]) + + def test_blue_initial_preview_matches_unpinned_account_at_creation(self): + import hashlib + + def prepare_dual(app): + self.prepare_codex(app) + app.store_secrets( + "accounts", + { + "openai-codex": [ + { + "type": "oauth", + "_albedo_account_id": label, + "access": f"dummy-{label}", + "refresh": f"refresh-{label}", + "accountId": f"acct-{label}", + "expires": 9999999999999, + } + for label in ("one", "two") + ] + }, + ) + path = app.home / "codex-models.json" + cache = json.loads(path.read_text()) + source = cache["accounts"].pop("acct-one") + cache["accounts"] = { + f"acct-{label}": { + **source, + "accessHash": hashlib.sha256(f"dummy-{label}".encode()) + .hexdigest() + .upper(), + "models": [ + { + **source["models"][0], + "cyber_programs": ["daybreak_blue"] + if label == "one" + else [], + } + ], + } + for label in ("one", "two") + } + path.write_text(json.dumps(cache)) + + app = self.app_with_codex(prepare=prepare_dual) + + def account_slot(identity): + value = 0x811C9DC5 + for byte in identity.encode(): + value = ((value ^ byte) * 16777619) & 0xFFFFFFFF + return value % 2 + + first = operation_id() + second = first[:-1] + ("1" if ord(first[-1]) % 2 == 0 else "0") + self.assertNotEqual(account_slot(first), account_slot(second)) + blue_id, ordinary_id = ( + (first, second) if account_slot(first) == 0 else (second, first) + ) + for session_id, status in ( + (blue_id, "supported"), + (ordinary_id, "unsupported"), + ): + with app.api( + f"/models?provider_profile=codex-unpinned&model=fixture-codex" + f"&session={session_id}&initial=true" + ) as response: + [model] = json.load(response)["items"] + self.assertEqual(model["cyber_access"]["status"], status) + body = { + "kind": "new", + "workspace": str(app.workspace), + "provider_profile": "codex-unpinned", + "model": "fixture-codex", + "cyber_access": "daybreak_blue", + } + with app.api( + f"/sessions/{blue_id}", body, method="PUT", headers={"If-None-Match": "*"} + ) as response: + self.assertEqual(json.load(response)["cyber_access"], "daybreak_blue") + with self.assertRaises(urllib.error.HTTPError) as refused: + app.api( + f"/sessions/{ordinary_id}", + body, + method="PUT", + headers={"If-None-Match": "*"}, + ) + self.assertEqual(refused.exception.code, 503) + self.assertIn( + "Daybreak Blue unavailable for selected account/model", + refused.exception.read().decode(), + ) + with app.api( + f"/sessions/{operation_id()}", + {**body, "cyber_access": None}, + method="PUT", + headers={"If-None-Match": "*"}, + ) as response: + self.assertIsNone(json.load(response)["cyber_access"]) + def test_implemented_check_keeps_legacy_metadata_unknown(self): def prepare_legacy(app): self.prepare_codex(app) diff --git a/test/harness/agents_models_payload_test.py b/test/harness/agents_models_payload_test.py new file mode 100644 index 000000000..e6ef9c37d --- /dev/null +++ b/test/harness/agents_models_payload_test.py @@ -0,0 +1,42 @@ +"""Legacy host-route payload shape: E2E sees the decoder's rejection but cannot +assert the Python binding omitted a key instead of encoding JSON null.""" + +import asyncio +from pathlib import Path +import sys +import unittest + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / "priv" / "python")) +from albedo_plugins import agents as binding # noqa: E402 + + +class AgentsModelsPayloadTests(unittest.TestCase): + def test_ordinary_omits_optional_field_and_blue_sends_explicit_value(self): + calls = [] + previous = getattr(binding, "host", None) + + async def host(method, payload): + calls.append((method, payload)) + return ["codex/model"] + + binding.host = host + try: + client = binding.Agents() + self.assertEqual(asyncio.run(client.models()), ["codex/model"]) + self.assertEqual( + asyncio.run(client.models(cyber_access="daybreak_blue")), + ["codex/model"], + ) + self.assertEqual( + calls, + [ + ("agents.models", {}), + ("agents.models", {"cyber_access": "daybreak_blue"}), + ], + ) + finally: + if previous is None: + del binding.host + else: + binding.host = previous diff --git a/test/harness/bedrock_effort_catalog_test.gleam b/test/harness/bedrock_effort_catalog_test.gleam index f01cecc63..ac23cb655 100644 --- a/test/harness/bedrock_effort_catalog_test.gleam +++ b/test/harness/bedrock_effort_catalog_test.gleam @@ -180,6 +180,7 @@ fn upstream(home: String, profile: String) -> harness.Upstream { types.ChatCompletions, None, False, + None, )) upstream } diff --git a/test/harness/bedrock_test.gleam b/test/harness/bedrock_test.gleam index 626a27960..bf2bb083e 100644 --- a/test/harness/bedrock_test.gleam +++ b/test/harness/bedrock_test.gleam @@ -522,6 +522,7 @@ pub fn reused_upstream_refreshes( types.ChatCompletions, None, False, + None, )) // Invalid model deliberately stops before HTTP, after authentication. let invalid = request("llama", [types.User("hello")]) diff --git a/test/harness/cache_fade_test.gleam b/test/harness/cache_fade_test.gleam index 1d9f0c3fd..b25c1ec80 100644 --- a/test/harness/cache_fade_test.gleam +++ b/test/harness/cache_fade_test.gleam @@ -149,6 +149,7 @@ fn info(id: String) -> conversation.Info { None, None, False, + None, ) } diff --git a/test/harness/codex_catalog_test.gleam b/test/harness/codex_catalog_test.gleam index dc06ed99f..658866ccd 100644 --- a/test/harness/codex_catalog_test.gleam +++ b/test/harness/codex_catalog_test.gleam @@ -4,6 +4,9 @@ import albedo/clock import albedo/harness/extension import albedo/harness/extensions/codex/catalog +import albedo/harness/extensions/codex/extension as codex +import albedo/openai_api +import albedo/openai_api/types import gleam/bit_array import gleam/dynamic/decode import gleam/json @@ -354,3 +357,213 @@ pub fn not_modified_retains_models_and_updates_metadata_before_replacement_test( ) cleanup(home) } + +/// A Blue intent cannot reuse another account's catalog, an old bearer, or stale metadata. +pub fn blue_capability_tracks_exact_account_and_bearer_test() -> Nil { + let home = temporary_home() + let blue = + "{\"models\":[{\"slug\":\"reasoner\",\"available_access_programs\":{\"cyber\":[\"daybreak_blue\"]}}]}" + let standard = + "{\"models\":[{\"slug\":\"reasoner\",\"available_access_programs\":{\"cyber\":[]}}]}" + script([response(200, "{\"version\":\"1.2.3\"}"), response(200, blue)]) + let assert Ok(["reasoner"]) = + catalog.blue_models_at(home, "bearer-one", "account-one", 10_000, get) + script([]) + let assert Ok(["reasoner"]) = + catalog.blue_models_at(home, "bearer-one", "account-one", 10_001, get) + let assert [] = calls() + script([response(200, standard)]) + let assert Ok([]) = + catalog.blue_models_at(home, "bearer-one", "account-two", 10_002, get) + let assert [#(_, headers)] = calls() + let assert False = + list.any(headers, fn(header) { header.0 == "if-none-match" }) + script([response(200, standard)]) + let assert Ok([]) = + catalog.blue_models_at(home, "bearer-two", "account-one", 10_003, get) + let assert [#(_, changed_headers)] = calls() + let assert False = + list.any(changed_headers, fn(header) { header.0 == "if-none-match" }) + script([response(200, blue)]) + let assert Ok(["reasoner"]) = + catalog.blue_models_at(home, "bearer-one", "account-one", 10_004, get) + let assert [#(_, restored_headers)] = calls() + let assert False = + list.any(restored_headers, fn(header) { header.0 == "if-none-match" }) + script([Error(Nil)]) + let assert Error("Codex model list request failed") = + catalog.blue_models_at(home, "bearer-one", "account-one", 3_700_005, get) + cleanup(home) +} + +/// A rotated attempt must recheck its own account/bearer before any Blue wire request. +pub fn blue_request_gate_rejects_rotation_bearer_change_and_provider_failure_test() -> Nil { + let home = temporary_home() + let blue = + "{\"models\":[{\"slug\":\"reasoner\",\"available_access_programs\":{\"cyber\":[\"daybreak_blue\"]}}]}" + let standard = + "{\"models\":[{\"slug\":\"reasoner\",\"available_access_programs\":{\"cyber\":[]}}]}" + let request = openai_api.request("reasoner", [types.User("hello")]) + let verify = fn(home, bearer, account, model) { + catalog.blue_model_at(home, bearer, account, model, 10_000, get) + } + let first = + types.Client( + types.Responses, + "", + "bearer-one", + 1000, + 1_000_000, + types.Codex("account-one", "s"), + ) + let rotated = + types.Client( + ..first, + api_key: "bearer-two", + policy: types.Codex("account-two", "s"), + ) + let replaced = types.Client(..first, api_key: "replaced-bearer") + script([response(200, "{\"version\":\"1.2.3\"}"), response(200, blue)]) + let assert Ok(allowed) = + codex.request_for_cyber_with( + home, + first, + request, + Some("daybreak_blue"), + verify, + ) + let assert Some("daybreak_blue") = allowed.options.cyber_access + // Auto-summary is another session-model request. Its Blue-only input must + // pass the same account-scoped gate, never a Standard fallback stream. + let summary = + openai_api.request("reasoner", [types.User("Blue-only summary context")]) + let assert Ok(summary_blue) = + codex.request_for_cyber_with( + home, + first, + summary, + Some("daybreak_blue"), + verify, + ) + let assert Some("daybreak_blue") = summary_blue.options.cyber_access + script([response(200, standard)]) + let assert Error(types.InvalidRequest(_)) = + codex.request_for_cyber_with( + home, + rotated, + summary, + Some("daybreak_blue"), + verify, + ) + script([response(200, standard)]) + let assert Error(types.InvalidRequest(_)) = + codex.request_for_cyber_with( + home, + replaced, + request, + Some("daybreak_blue"), + verify, + ) + script([Error(Nil)]) + let failure_verify = fn(home, bearer, account, model) { + catalog.blue_model_at(home, bearer, account, model, 3_700_001, get) + } + let assert Error(types.InvalidRequest(reason)) = + codex.request_for_cyber_with( + home, + first, + request, + Some("daybreak_blue"), + failure_verify, + ) + let assert True = string.starts_with(reason, "cannot verify Daybreak Blue") + let assert Ok(ordinary) = + codex.request_for_cyber_with(home, rotated, request, None, verify) + let assert None = ordinary.options.cyber_access + cleanup(home) +} + +pub fn blue_known_model_survives_unrelated_legacy_row_test() -> Nil { + let home = temporary_home() + let mixed = + "{\"models\":[{\"slug\":\"eligible\",\"available_access_programs\":{\"cyber\":[\"daybreak_blue\"]}},{\"slug\":\"legacy\"}]}" + script([ + response(200, "{\"version\":\"1.2.3\"}"), + response(200, mixed), + response(200, mixed), + ]) + let assert Ok(["eligible"]) = + catalog.blue_models_at(home, "bearer", "account", 10_000, get) + let assert [_, _, #(_, headers)] = calls() + let assert False = + list.any(headers, fn(header) { header.0 == "if-none-match" }) + cleanup(home) +} + +pub fn blue_catalog_legacy_rows_are_one_batch_refresh_not_n_calls_test() -> Nil { + let home = temporary_home() + let legacy = + "{\"models\":[{\"slug\":\"legacy-0\"},{\"slug\":\"legacy-1\"},{\"slug\":\"legacy-2\"},{\"slug\":\"legacy-3\"},{\"slug\":\"legacy-4\"},{\"slug\":\"legacy-5\"},{\"slug\":\"legacy-6\"},{\"slug\":\"legacy-7\"},{\"slug\":\"legacy-8\"},{\"slug\":\"legacy-9\"},{\"slug\":\"legacy-10\"},{\"slug\":\"legacy-11\"},{\"slug\":\"legacy-12\"},{\"slug\":\"legacy-13\"},{\"slug\":\"legacy-14\"},{\"slug\":\"legacy-15\"},{\"slug\":\"legacy-16\"},{\"slug\":\"legacy-17\"},{\"slug\":\"legacy-18\"},{\"slug\":\"legacy-19\"},{\"slug\":\"legacy-20\"},{\"slug\":\"legacy-21\"},{\"slug\":\"legacy-22\"},{\"slug\":\"legacy-23\"}]}" + script([ + response(200, "{\"version\":\"1.2.3\"}"), + response(200, legacy), + response(200, legacy), + ]) + let assert Ok(statuses) = + catalog.blue_statuses_at(home, "bearer", "account", 10_000, get) + let assert 24 = list.length(statuses) + let assert True = list.all(statuses, fn(row) { row.1 == None }) + let assert [_, _, #(_, headers)] = calls() + let assert False = + list.any(headers, fn(header) { header.0 == "if-none-match" }) + cleanup(home) +} + +pub fn blue_catalog_mixed_rows_preserve_known_and_unknown_test() -> Nil { + let home = temporary_home() + let mixed = + "{\"models\":[{\"slug\":\"eligible\",\"available_access_programs\":{\"cyber\":[\"daybreak_blue\"]}},{\"slug\":\"unsupported\",\"available_access_programs\":{\"cyber\":[]}},{\"slug\":\"legacy\"}]}" + script([ + response(200, "{\"version\":\"1.2.3\"}"), + response(200, mixed), + response(200, mixed), + ]) + let assert Ok([ + #("eligible", Some(True)), + #("unsupported", Some(False)), + #("legacy", None), + ]) = catalog.blue_statuses_at(home, "bearer", "account", 10_000, get) + let assert [_, _, _] = calls() + cleanup(home) +} + +pub fn blue_catalog_failed_legacy_refresh_keeps_known_rows_test() -> Nil { + let home = temporary_home() + let mixed = + "{\"models\":[{\"slug\":\"eligible\",\"available_access_programs\":{\"cyber\":[\"daybreak_blue\"]}},{\"slug\":\"legacy\"}]}" + script([ + response(200, "{\"version\":\"1.2.3\"}"), + response(200, mixed), + Error(Nil), + ]) + let assert Ok([#("eligible", Some(True)), #("legacy", None)]) = + catalog.blue_statuses_at(home, "bearer", "account", 10_000, get) + let assert [_, _, _] = calls() + cleanup(home) +} + +pub fn blue_metadata_absence_is_unknown_not_confirmed_unsupported_test() -> Nil { + let home = temporary_home() + script([ + response(200, "{\"version\":\"1.2.3\"}"), + response(200, upstream), + response(200, upstream), + ]) + let assert Error( + "ChatGPT account catalog does not advertise cyber-access metadata", + ) = catalog.blue_models_at(home, "bearer", "account", 10_000, get) + let assert [_, _, #(_, headers)] = calls() + let assert False = + list.any(headers, fn(header) { header.0 == "if-none-match" }) + cleanup(home) +} diff --git a/test/harness/codex_search_test.gleam b/test/harness/codex_search_test.gleam new file mode 100644 index 000000000..a8b43b642 --- /dev/null +++ b/test/harness/codex_search_test.gleam @@ -0,0 +1,32 @@ +//// Search is separate Standard inference and may fall through to another +//// provider; this wire boundary must never imply Blue session protections. + +import albedo/harness/extensions/codex/search +import gleam/dynamic/decode +import gleam/json +import gleam/option.{None} + +pub fn codex_search_query_has_no_blue_access_program_test() -> Nil { + let encoded = + json.to_string(search.body("search-model", "literal search query")) + let assert Ok(#("search-model", [["literal search query"]], None)) = + json.parse(encoded, { + use model <- decode.field("model", decode.string) + let content = { + use text <- decode.field("text", decode.string) + decode.success(text) + } + let input = { + use texts <- decode.field("content", decode.list(content)) + decode.success(texts) + } + use text <- decode.field("input", decode.list(input)) + use programs <- decode.optional_field( + "access_programs", + None, + decode.optional(decode.dynamic), + ) + decode.success(#(model, text, programs)) + }) + Nil +} diff --git a/test/harness/extension_failure_test.gleam b/test/harness/extension_failure_test.gleam index 0f3be1849..3c568a093 100644 --- a/test/harness/extension_failure_test.gleam +++ b/test/harness/extension_failure_test.gleam @@ -52,6 +52,7 @@ fn host( None, None, False, + None, ), ) let assert Ok(session) = diff --git a/test/harness/lcm_preparation_test.gleam b/test/harness/lcm_preparation_test.gleam index 25d5a5cd4..bedcc011b 100644 --- a/test/harness/lcm_preparation_test.gleam +++ b/test/harness/lcm_preparation_test.gleam @@ -47,6 +47,7 @@ pub fn below_trigger_and_stored_prior_do_not_decode_archived_payloads_test() -> None, None, False, + None, ), ) let archived = diff --git a/test/harness/lcm_test.gleam b/test/harness/lcm_test.gleam index 5af79838b..10fb8379c 100644 --- a/test/harness/lcm_test.gleam +++ b/test/harness/lcm_test.gleam @@ -59,6 +59,7 @@ fn host_with( None, None, False, + None, ), ) let assert Ok(session) = runtime.open_session(host, "lcm-test", "/tmp") @@ -749,6 +750,7 @@ fn tight(capacity: Int, tail: Int) -> #(runtime.Runtime, runtime.Session) { None, None, False, + None, ), ) let assert Ok(session) = runtime.open_session(host, "lcm-test", "/tmp") diff --git a/test/harness/retrieval_performance_test.gleam b/test/harness/retrieval_performance_test.gleam index 59c3b3268..d10d3990b 100644 --- a/test/harness/retrieval_performance_test.gleam +++ b/test/harness/retrieval_performance_test.gleam @@ -51,6 +51,7 @@ fn fixture() -> #(runtime.Runtime, store.Store) { None, None, False, + None, ), ) }) diff --git a/test/harness/rotation_test.gleam b/test/harness/rotation_test.gleam index 5375c3670..e73bb8c11 100644 --- a/test/harness/rotation_test.gleam +++ b/test/harness/rotation_test.gleam @@ -372,6 +372,7 @@ pub fn antigravity_claude_declares_anthropic_image_limits_test() -> Nil { types.ChatCompletions, None, False, + None, )) upstream.images } diff --git a/test/harness/session_fixture.gleam b/test/harness/session_fixture.gleam index 0a3353205..f84748856 100644 --- a/test/harness/session_fixture.gleam +++ b/test/harness/session_fixture.gleam @@ -29,6 +29,7 @@ pub fn create(host: runtime.Runtime, id: String, workspace: String) -> Nil { None, None, False, + None, ), ) Nil diff --git a/test/openai_api/request_test.gleam b/test/openai_api/request_test.gleam index e4e92a8b1..4bf8b5fc2 100644 --- a/test/openai_api/request_test.gleam +++ b/test/openai_api/request_test.gleam @@ -94,6 +94,47 @@ pub fn service_tier_is_encoded_only_when_explicit_for_supported_policies_test() Nil } +pub fn codex_blue_wire_is_explicit_and_independent_of_fast_test() -> Nil { + let ordinary = openai.request("canonical-model", []) + let policy = types.Codex("account", "session") + let encoded = fn(request) { + string_tree.to_string(result.unwrap( + request.encode_with_policy(types.Responses, policy, request), + string_tree.from_string(""), + )) + } + let assert Ok(None) = + json.parse(encoded(ordinary), { + use _ <- decode.field("model", decode.string) + use programs <- decode.optional_field( + "access_programs", + None, + decode.optional(decode.dynamic), + ) + decode.success(programs) + }) + let blue = + types.Request( + ..ordinary, + options: types.Options( + ..types.defaults, + cyber_access: Some("daybreak_blue"), + service_tier: Some("priority"), + ), + ) + let assert Ok(#("canonical-model", "daybreak_blue", "priority")) = + json.parse(encoded(blue), { + use model <- decode.field("model", decode.string) + use cyber <- decode.then(decode.at( + ["access_programs", "cyber"], + decode.string, + )) + use tier <- decode.field("service_tier", decode.string) + decode.success(#(model, cyber, tier)) + }) + Nil +} + pub fn replay_preserves_unknown_fields_and_refuses_other_protocol_test() -> Result( string_tree.StringTree, types.Error, diff --git a/web/scripts/new-session.test.mjs b/web/scripts/new-session.test.mjs new file mode 100644 index 000000000..019582641 --- /dev/null +++ b/web/scripts/new-session.test.mjs @@ -0,0 +1,42 @@ +// Creation response loss cannot be tested by daemon E2E; exercise the real web API request/recovery path. +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { stripTypeScriptTypes } from 'node:module'; +import test from 'node:test'; + +const source = stripTypeScriptTypes((await readFile(new URL('../src/lib/api.ts', import.meta.url), 'utf8')).replace(/^import type .*;\n/gm, ''), { mode: 'transform' }); +const { createSession, ApiError } = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`); +const choice = { provider_profile: 'codex', model: 'gpt-6-sol', effort: 'high', cyber_access: 'daybreak_blue' }; +const intent = { kind: 'new', workspace: '/project', name: null, ...choice }; +const existing = { id: 'fixed-id', creation: { submitted: intent } }; +const response = (status, body) => ({ ok: status >= 200 && status < 300, status, statusText: 'rejected', headers: new Headers(), json: async () => body }); + +for (const lost of [true, false]) test(`create recovers exact persisted intent after ${lost ? 'lost response' : '412 retry'}`, async (t) => { + const seen = []; + globalThis.fetch = async (url, init) => { + seen.push({ url, init }); + if (init.method === 'PUT') return lost ? Promise.reject(new TypeError('response lost')) : response(412, { code: 'precondition_failed' }); + return response(200, existing); + }; + t.after(() => { delete globalThis.fetch; }); + assert.equal(await createSession('/project', choice, 'fixed-id'), existing); + assert.deepEqual(seen.map(({ url }) => url), ['/api/sessions/fixed-id', '/api/sessions/fixed-id?tail=0']); + assert.equal(seen[0].init.headers['if-none-match'], '*'); + assert.deepEqual(JSON.parse(seen[0].init.body), { kind: 'new', workspace: '/project', ...choice }); +}); + +test('different persisted Blue intent cannot be claimed by Standard retry', async (t) => { + globalThis.fetch = async (_, init) => init.method === 'PUT' + ? response(412, { code: 'precondition_failed' }) + : response(200, existing); + t.after(() => { delete globalThis.fetch; }); + await assert.rejects(createSession('/project', { ...choice, cyber_access: null }, 'fixed-id'), (error) => error instanceof ApiError && error.status === 412); +}); + +test('failed creation without persisted receipt remains failed', async (t) => { + globalThis.fetch = async (_, init) => init.method === 'PUT' + ? response(503, { code: 'capability_unavailable' }) + : response(404, { code: 'not_found' }); + t.after(() => { delete globalThis.fetch; }); + await assert.rejects(createSession('/project', choice, 'fixed-id'), (error) => error instanceof ApiError && error.status === 503); +}); diff --git a/web/src/lib/ModelChoice.svelte b/web/src/lib/ModelChoice.svelte index e924c782c..e7b462029 100644 --- a/web/src/lib/ModelChoice.svelte +++ b/web/src/lib/ModelChoice.svelte @@ -14,6 +14,9 @@ profile = $bindable(), model = $bindable(), effort = $bindable(), + cyberAccess = $bindable(null), + sessionId, + currentCyberAccess = null, currentProfile = null, currentModel = null, autofocus = false, @@ -23,13 +26,16 @@ profile: string | null; model: string | null; effort: string | null; + cyberAccess?: string | null; + sessionId?: string; + currentCyberAccess?: string | null; /** The session's current provider, sorted first and tagged `current`. */ currentProfile?: string | null; /** The session's current model id, tagged `current` on `currentProfile`. */ currentModel?: string | null; autofocus?: boolean; /** Called when a model row is picked (clicked or Enter on the first/highlighted match). */ - onpick?: (profile: string, model: string, effort: string | null) => void; + onpick?: (profile: string, model: string, effort: string | null, cyberAccess: string | null) => void; /** Called when an effort pill in the footer is clicked. */ oneffort?: (effort: string) => void; } = $props(); @@ -59,13 +65,14 @@ } await Promise.all( found.profiles.map((p) => - models(p.id) + models(p.id, sessionId) .then((items) => { byProfile = { ...byProfile, [p.id]: items }; if (profile === p.id && !model && items[0]) model = items[0].id; }) - .catch(() => { + .catch((error) => { byProfile = { ...byProfile, [p.id]: [] }; + problem = `Could not verify model access for ${p.id}: ${String((error as Error).message ?? error)}`; }), ), ); @@ -111,14 +118,14 @@ }), ); - function matchModel(words: string[], pId: string, mId: string): { rank: MatchRank; hits: number[] } | null { - const res = matchFields(words, mId, pId); + function matchModel(words: string[], pId: string, mId: string, blue: boolean): { rank: MatchRank; hits: number[] } | null { + const res = matchFields(words, blue ? `${mId} Daybreak Blue` : mId, pId); if (!res) return null; const whole = words.join(''); if (whole && whole === searchKey(pId + mId)) { res.rank[0] = 1; } - return res; + return { ...res, hits: res.hits.filter((index) => index < mId.length) }; } const groups = $derived.by(() => { @@ -127,14 +134,16 @@ const rawGroups: { profile: Profile; best: MatchRank; - scored: { profile: string; model: Model; hits: number[]; rank: MatchRank }[]; + scored: { profile: string; model: Model; hits: number[]; rank: MatchRank; blue: boolean }[]; }[] = []; for (const p of orderedProfiles) { - const scored: { profile: string; model: Model; hits: number[]; rank: MatchRank }[] = []; + const scored: { profile: string; model: Model; hits: number[]; rank: MatchRank; blue: boolean }[] = []; for (const m of rowsOf(p)) { - const matched = matchModel(words, p.id, m.id); - if (matched) scored.push({ profile: p.id, model: m, hits: matched.hits, rank: matched.rank }); + for (const blue of [false, ...(m.cyber_access?.status === 'supported' ? [true] : [])]) { + const matched = matchModel(words, p.id, m.id, blue || m.cyber_access?.status === 'unsupported' || m.cyber_access?.status === 'unknown'); + if (matched) scored.push({ profile: p.id, model: m, hits: matched.hits, rank: matched.rank, blue }); + } } if (!scored.length) continue; if (words.length) scored.sort((a, b) => compareRank(a.rank, b.rank)); @@ -152,6 +161,7 @@ profile: s.profile, model: s.model, hits: s.hits, + blue: s.blue, flatIndex: idx++, })), })); @@ -181,12 +191,13 @@ ); } - function selectRow(pId: string, m: Model) { + function selectRow(pId: string, m: Model, blue: boolean) { const nextEff = nextEffortFor(pId, m); profile = pId; model = m.id; effort = nextEff; - onpick?.(pId, m.id, nextEff); + cyberAccess = blue ? 'daybreak_blue' : null; + onpick?.(pId, m.id, nextEff, cyberAccess); } function selectEffort(nextEff: string) { @@ -214,7 +225,7 @@ if (!target) return; event.preventDefault(); event.stopPropagation(); - selectRow(target.profile, target.model); + selectRow(target.profile, target.model, target.blue); } } @@ -232,11 +243,11 @@ {group.profile.id} {group.items.length} - {#each group.items as item (`${item.profile}:${item.model.id}`)} + {#each group.items as item (`${item.profile}:${item.model.id}:${item.blue}`)} {@const isCurrent = currentProfile !== null - ? item.profile === currentProfile && item.model.id === currentModel - : item.profile === profile && item.model.id === model} - {@const isSelected = item.profile === profile && item.model.id === model} + ? item.profile === currentProfile && item.model.id === currentModel && item.blue === (currentCyberAccess === 'daybreak_blue') + : item.profile === profile && item.model.id === model && item.blue === (cyberAccess === 'daybreak_blue')} + {@const isSelected = item.profile === profile && item.model.id === model && item.blue === (cyberAccess === 'daybreak_blue')} {@const ctx = item.model.effective_context_tokens ?? item.model.default_context_tokens} {/each} {:else} @@ -363,6 +383,12 @@ font-weight: 600; border-radius: 4px; } + .tag.unknown { color: var(--muted); background: var(--field); } + .availability { grid-column: 1 / -1; color: var(--muted); font: calc(11px * var(--ui-scale))/1.4 var(--sans); white-space: normal; } + .tag.blue { + color: var(--accent); + background: color-mix(in oklab, var(--accent) 14%, transparent); + } .tag.current { color: var(--added); background: color-mix(in oklab, var(--added) 16%, transparent); diff --git a/web/src/lib/NewSession.svelte b/web/src/lib/NewSession.svelte index 6fbc9dd60..0d054f84d 100644 --- a/web/src/lib/NewSession.svelte +++ b/web/src/lib/NewSession.svelte @@ -18,7 +18,7 @@ // `inside` is a listed folder you can open; the listed folder itself has it false. type FolderRow = { key: string; name: string; note: string; location: string | null; complete: string; inside?: boolean }; - type ModelRow = { key: string; profile: string; model: string; efforts: string[] | null }; + type ModelRow = { key: string; profile: string; model: string; efforts: string[] | null; cyberAccess: null | "daybreak_blue"; blueReason: string | null }; const QUESTIONS = ['where to?', 'which model?', 'what should we do?']; const USED = 3; @@ -44,9 +44,11 @@ let text = $state(''); let starting = $state(false); + let choiceLocked = $state(false); let problem = $state(''); let made: Session | null = null; const sendId = uuidv7(); + const futureSessionId = uuidv7(); onDestroy(keepFocus()); @@ -59,9 +61,9 @@ all = found.profiles; fallback = found.fallback ?? found.profiles[0]?.id ?? null; for (const p of found.profiles) - models(p.id).then( + models(p.id, futureSessionId, true).then( (items) => (catalog = { ...catalog, [p.id]: items }), - () => {}, + (error) => (problem = `Could not verify model access for ${p.id}: ${String((error as Error).message ?? error)}`), ); }) .catch((error) => (problem = String((error as Error).message ?? error))); @@ -141,7 +143,7 @@ } function choose(row: FolderRow | undefined) { - if (!row) return; + if (!row || choiceLocked) return; if (!row.location) return setQuery(row.complete); folder = row.location; step = 1; @@ -175,14 +177,19 @@ const profileOf = (id: string) => all.find((p) => p.id === id); - function rowOf(profile: string, model: string): ModelRow { + function rowOf(profile: string, model: string, blue = false): ModelRow { const entry = catalog[profile]?.find((m) => m.id === model); - return { key: `${profile}/${model}`, profile, model, efforts: entry ? entry.efforts.map((e) => e.id) : null }; + return { key: `${profile}/${model}${blue ? ":daybreak_blue" : ""}`, profile, model, efforts: entry ? entry.efforts.map((e) => e.id) : null, cyberAccess: blue ? "daybreak_blue" : null, blueReason: !blue && entry?.cyber_access && entry.cyber_access.status !== "supported" ? entry.cyber_access.detail ?? "Blue access is unavailable for this account/model" : null }; + } + + function rowsOf(profile: string, model: string): ModelRow[] { + const entry = catalog[profile]?.find((m) => m.id === model); + return [rowOf(profile, model), ...(entry?.cyber_access?.status === "supported" ? [rowOf(profile, model, true)] : [])]; } // Each profile's catalogue, or its configured model until that arrives. const everyModel = $derived( - all.flatMap((p) => (catalog[p.id]?.length ? catalog[p.id].map((m) => rowOf(p.id, m.id)) : p.model ? [rowOf(p.id, p.model)] : [])), + all.flatMap((p) => (catalog[p.id]?.length ? catalog[p.id].flatMap((m) => rowsOf(p.id, m.id)) : p.model ? [rowOf(p.id, p.model)] : [])), ); const preset = $derived(fallback ? profileOf(fallback) : undefined); @@ -195,7 +202,7 @@ const key = `${profile}/${model}`; if (!profile || !model || keys.has(key) || !profileOf(profile)) return; keys.add(key); - rows.push(rowOf(profile, model)); + rows.push(...rowsOf(profile, model)); }; for (const session of [...sessions.list].sort((a, b) => (b.activity_at ?? '').localeCompare(a.activity_at ?? ''))) { if (rows.length >= USED) break; @@ -208,7 +215,7 @@ const modelRows = $derived( filter.trim() - ? rank(everyModel, filter, (row) => [row.model, row.profile]) + ? rank(everyModel, filter, (row) => [row.model, row.cyberAccess ? "Daybreak Blue" : row.blueReason ? "Daybreak Blue unavailable" : "Standard", row.profile]) : [...lead, ...everyModel.filter((row) => !lead.some((first) => first.key === row.key))], ); const mhi = $derived(Math.max(0, modelRows.findIndex((row) => row.key === (highlighted ?? (filter.trim() ? null : defaultKey))))); @@ -222,7 +229,7 @@ const shownEffort = $derived(effortOf(current)); function pickModel(row: ModelRow | undefined) { - if (!row) return; + if (!row || choiceLocked) return; picked = row; effort = effortOf(row); step = 2; @@ -259,6 +266,7 @@ }); function goto(card: number) { + if (choiceLocked) return; step = card; setQuery(''); filter = ''; @@ -267,6 +275,7 @@ function back() { if (starting) return; + if (choiceLocked) return onclose(); if (step > 0) step--; else if (query) setQuery(''); else onclose(); @@ -275,15 +284,16 @@ async function start() { if (!folder || !picked || starting) return; starting = true; + choiceLocked = true; problem = ''; try { - made ??= await createSession(folder, { provider_profile: picked.profile, model: picked.model, effort: pickedEffort }); + made ??= await createSession(folder, { provider_profile: picked.profile, model: picked.model, effort: pickedEffort, cyber_access: picked.cyberAccess }, futureSessionId); if (text.trim()) await sendMessage(made.id, sendId, text); await sessions.refresh(); onclose(); boards.openSession(made); } catch (error) { - problem = String((error as Error).message ?? error); + problem = `${String((error as Error).message ?? error)}. Retry this choice, or close to choose another.`; starting = false; } } @@ -331,7 +341,7 @@ {#if folder} in - {:else} @@ -342,8 +352,8 @@ {#if picked} using - {:else} using … @@ -424,9 +434,10 @@
{#each modelRows as row, i (row.key)} - {:else}

{all.length ? 'no models match' : 'loading models…'}

@@ -684,6 +695,8 @@ height: calc(31px * var(--ui-scale)); border-radius: 10px; } + .row.reason { height: auto; min-height: calc(31px * var(--ui-scale)); flex-wrap: wrap; padding-block: 6px; } + .availability { flex-basis: 100%; color: var(--muted); font-size: calc(11px * var(--ui-scale)); line-height: 1.4; white-space: normal; } .pickrow, button.row { diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index 0c2ff2b99..d3f5983b4 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -2423,6 +2423,8 @@ export interface components { model: components["schemas"]["ID"] | null; effort: string | null; fast: boolean; + /** @enum {string|null} */ + cyber_access?: "daybreak_blue" | null; status: components["schemas"]["SessionStatus"]; preview: components["schemas"]["Preview"]; preferences: components["schemas"]["SessionPreferences"]; @@ -2590,6 +2592,11 @@ export interface components { effort: string | null; /** @description Provider fast-mode setting; defaults off and may affect billing. */ fast: boolean; + /** + * @description Explicit session-scoped Codex Blue intent; null sends ordinary requests. + * @enum {string|null} + */ + cyber_access?: "daybreak_blue" | null; /** @description Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. */ context_window?: number | null; preferences: { @@ -2626,6 +2633,11 @@ export interface components { effort?: string | null; /** @description Enable provider fast mode; enabling requires a supported capability and may affect billing. */ fast?: boolean; + /** + * @description Select Blue for this session; null explicitly clears it. + * @enum {string|null} + */ + cyber_access?: "daybreak_blue" | null; /** @description Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. */ context_window?: number | null; preferences?: components["schemas"]["PreferencePatch"]; @@ -2659,6 +2671,11 @@ export interface components { effort?: string | null; /** @description Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. */ context_window?: number | null; + /** + * @description Explicit Blue at creation; null or omission selects standard. + * @enum {string|null} + */ + cyber_access?: "daybreak_blue" | null; }; NewSessionIntent: { /** @constant */ @@ -2670,6 +2687,11 @@ export interface components { effort: string | null; /** @description Tokens this session compacts against instead of the model's catalogued window. Null uses the model's window. */ context_window?: number | null; + /** + * @description Explicit Blue at creation; null or omission selects standard. + * @enum {string|null} + */ + cyber_access?: "daybreak_blue" | null; }; ForkSessionRequest: { /** @constant */ @@ -3935,6 +3957,11 @@ export interface components { failure: components["schemas"]["SafeReason"] | null; }; Model: { + cyber_access?: { + /** @enum {string} */ + status: "supported" | "unsupported" | "unknown"; + detail?: string; + }; id: components["schemas"]["ID"]; label: string; efforts: { @@ -7212,6 +7239,10 @@ export interface operations { host?: string; model?: components["schemas"]["ID"]; provider_profile?: components["schemas"]["ID"]; + /** @description Existing session whose selected account scopes Daybreak Blue support; with initial=true, a preallocated new session ID selects its exact future account. */ + session?: components["schemas"]["ID"]; + /** @description true permits preview with a new future session ID; requires provider_profile and session. Existing session IDs are rejected. */ + initial?: "true"; provider?: components["schemas"]["ID"]; endpoint?: string; limit?: components["parameters"]["Limit"]; diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index f17637e77..229530fb3 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -84,7 +84,7 @@ export function readRequests(sessionId: string, after = 0, limit = 200, signal?: } /** One session as the daemon has it now, without its history. */ -export function getSession(sessionId: string, signal?: AbortSignal): Promise { +export function getSession(sessionId: string, signal?: AbortSignal): Promise { return get(`/sessions/${sessionId}?tail=0`, signal); } @@ -355,25 +355,39 @@ export async function profiles(): Promise<{ fallback: string | null; profiles: P export type Model = components['schemas']['Model']; /** A profile's whole catalogue, every page of it. */ -export async function models(profile: string): Promise { +export async function models(profile: string, sessionId?: string, initial = false): Promise { const items: Model[] = []; let next: string | null = null; do { const query: string = next ? `&next=${encodeURIComponent(next)}` : ''; - const page: Page = await get(`/models?provider_profile=${encodeURIComponent(profile)}${query}`); + const page: Page = await get(`/models?provider_profile=${encodeURIComponent(profile)}${sessionId ? `&session=${encodeURIComponent(sessionId)}` : ""}${initial ? "&initial=true" : ""}${query}`); items.push(...page.items); next = page.next; } while (next); return items; } -export type Choice = Pick; +export type Choice = Pick & { cyber_access?: null | 'daybreak_blue' }; export type SessionConfiguration = components['schemas']['SessionConfiguration']; /** Starts a session in a folder; null choices take the defaults. */ -export function createSession(workspace: string, choice: Choice): Promise { +export async function createSession(workspace: string, choice: Choice, sessionId = uuidv7()): Promise { // If-None-Match makes the PUT a create: it never replaces a session. - return request('PUT', `/sessions/${uuidv7()}`, { body: { kind: 'new', workspace, ...choice }, headers: { 'if-none-match': '*' } }); + try { + return await request('PUT', `/sessions/${sessionId}`, { body: { kind: 'new', workspace, ...choice }, headers: { 'if-none-match': '*' } }); + } catch (error) { + // A lost response may follow a committed creation. Never allocate another + // identity or reuse an existing one without proving the submitted intent. + const existing = await getSession(sessionId).catch(() => null); + const submitted = existing?.creation?.submitted; + if (existing && submitted?.kind === 'new' && submitted.workspace === workspace && + submitted.name === null && submitted.context_window == null && + submitted.provider_profile === choice.provider_profile && + submitted.model === choice.model && + submitted.effort === (choice.effort ?? null) && + (submitted.cyber_access ?? null) === (choice.cyber_access ?? null)) return existing; + throw error; + } } /** Changes a session's profile, model, effort or pin and archive marks against a fresh read; a 412 from a write in between is retried once. */ diff --git a/web/src/lib/chat/ModelPicker.svelte b/web/src/lib/chat/ModelPicker.svelte index 199d37a9d..ed58f97bf 100644 --- a/web/src/lib/chat/ModelPicker.svelte +++ b/web/src/lib/chat/ModelPicker.svelte @@ -27,6 +27,7 @@ let profile = $state(null); let model = $state(null); let effort = $state(null); + let cyberAccess = $state(null); // Docked and undocked pickers share one session-bound save lane. let binding = $state.raw(null); let popupScope: object = {}; @@ -42,13 +43,14 @@ const shownProfile = $derived(queued ? queued.provider_profile : session.provider_profile); const shownModel = $derived(queued ? queued.model : session.model); const shownEffort = $derived(queued ? queued.effort : session.effort); + const shownCyber = $derived(queued ? queued.cyber_access ?? null : session.cyber_access ?? null); $effect(() => { const sessionId = pickerSessionId; const next = untrack(() => acquireModelChoice(sessionId, busy(session))); binding = next; untrack(() => { - [profile, model, effort] = [session.provider_profile, session.model, session.effort]; + [profile, model, effort, cyberAccess] = [session.provider_profile, session.model, session.effort, session.cyber_access ?? null]; popupScope = {}; open = false; }); @@ -105,6 +107,7 @@ [ shownModel ?? 'model', session.fast ? 'Fast mode on' : null, + shownCyber === 'daybreak_blue' ? 'Daybreak Blue selected' : null, shownEffort ? `effort: ${shownEffort}` : null, queued ? (problem ? 'model choice not saved' : 'queued for next turn') : null, problem || null, @@ -114,7 +117,7 @@ ); function show() { - [profile, model, effort] = [shownProfile, shownModel, shownEffort]; + [profile, model, effort, cyberAccess] = [shownProfile, shownModel, shownEffort, shownCyber]; popupScope = {}; open = !open; } @@ -134,12 +137,12 @@ return dismissal((target) => !!pane?.contains(target) || !!target.closest('.model-chip'), () => (open = false)); }); - function save(nextProfile: string | null, nextModel: string | null, nextEffort: string | null, closeAfter: boolean) { + function save(nextProfile: string | null, nextModel: string | null, nextEffort: string | null, nextCyber: string | null, closeAfter: boolean) { const current = binding; if (!current || current.sessionId !== session.id) return; const scope = popupScope; current.observe(busy(session)); - current.choose({ provider_profile: nextProfile, model: nextModel, effort: nextEffort }, closeAfter, () => { + current.choose({ provider_profile: nextProfile, model: nextModel, effort: nextEffort, cyber_access: nextCyber as 'daybreak_blue' | null }, closeAfter, () => { if (binding === current && popupScope === scope) open = false; }); if (closeAfter && busy(session)) open = false; @@ -177,11 +180,14 @@ bind:profile bind:model bind:effort + bind:cyberAccess + sessionId={session.id} + currentCyberAccess={shownCyber} currentProfile={shownProfile} currentModel={shownModel} autofocus - onpick={(p, m, e) => save(p, m, e, true)} - oneffort={(e) => save(profile, model, e, false)} + onpick={(p, m, e, c) => save(p, m, e, c, true)} + oneffort={(e) => save(profile, model, e, cyberAccess, false)} /> {#if problem}{/if} {#if queued && !queue?.inflight} @@ -199,6 +205,7 @@ {shownModel ?? 'model'} {@render fastIndicator()} + {#if shownCyber === 'daybreak_blue'}Blue{/if} {#if shownProfile} {shownProfile} {/if} @@ -208,7 +215,7 @@ {@render choicePane()}
{#if knownEfforts.length > 0} - save(shownProfile, shownModel, opt, false)} /> + save(shownProfile, shownModel, opt, shownCyber, false)} /> {/if} {#if problem && !open}

{problem}

{/if} @@ -234,6 +241,7 @@ > {shownModel ?? 'model'} {@render fastIndicator()} + {#if shownCyber === 'daybreak_blue'}Blue{/if} {#if problem}{/if} {#if tier && tier.total > 0} {/if} - {#if !open && (problem || session.fast)} + {#if !open && (problem || session.fast || shownCyber === 'daybreak_blue')} {/if} @@ -291,6 +300,7 @@ cursor: pointer; transition: background-color 120ms ease, color 120ms ease; } + .blue-indicator { color: var(--accent); font-size: calc(10px * var(--ui-scale)); font-weight: 650; } .fast-indicator { display: inline-flex; flex: none;