From 8047218408efaa27d41a6aba0c6010813e22f9e8 Mon Sep 17 00:00:00 2001 From: Chayapat Sriwattanachote Date: Wed, 18 Nov 2026 02:20:57 +0700 Subject: [PATCH 1/3] feat(models): preserve exact Bot pins and expose observed usage --- CONTEXT.md | 2 + ...093-s16-model-choice-and-observed-usage.md | 29 ++++ docs/contracts/s16-bots-v1.md | 2 +- docs/contracts/s16-models-v1.md | 11 ++ docs/tickets/S16-rakazo-experience-roadmap.md | 2 + src/i18n/en.ts | 50 +++++- src/i18n/th.ts | 50 +++++- src/s15/composition.ts | 3 +- src/s15/model/service.ts | 13 +- src/s15/model/types.ts | 5 +- src/s16/bots/service.ts | 3 +- src/s16/bots/types.ts | 2 +- src/s16/client/client.ts | 25 +++ src/s16/client/contracts.ts | 21 ++- src/s16/http.ts | 14 +- src/s16/models.ts | 32 ++++ src/s16/web/BotsView.tsx | 26 ++- src/s16/web/ModelsPanel.tsx | 52 ++++++ src/s16/web/app.tsx | 4 +- src/s16/web/style.css | 3 + tests/s15-model-packed-consumer.test.ts | 19 ++- tests/s16-models.browser.test.ts | 55 +++++++ tests/s16-models.test.ts | 153 ++++++++++++++++++ 23 files changed, 552 insertions(+), 24 deletions(-) create mode 100644 docs/adr/0093-s16-model-choice-and-observed-usage.md create mode 100644 docs/contracts/s16-models-v1.md create mode 100644 src/s16/models.ts create mode 100644 src/s16/web/ModelsPanel.tsx create mode 100644 tests/s16-models.browser.test.ts create mode 100644 tests/s16-models.test.ts diff --git a/CONTEXT.md b/CONTEXT.md index b85fc322..ac9808ad 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -18,6 +18,8 @@ S15/S16 target terms below refine product intent. Definitions explicitly marked **Bot:** A persistent participant with a stable identity, responsibility, enabled generation, selected model/auth route and capability policy. It is not a model, provider session or container. Creating a permanent Bot requires owner acceptance of its exact proposal. +**Model pin (S16, MODEL16-01):** An owner's exact Bot route/model/effort choice. An unavailable or withdrawn choice holds new work instead of silently selecting the installation default. An explicit profile update affects new admission; already admitted work retains its POLICY pin. Recorded usage distinguishes conservative charges, measured subtotals and unknown values; it is evidence rather than authority. See ADR 0093 and `s16-client-models/v1`. + **Jit (main Bot):** The default conversational assistant and coordinator. It understands requested outcomes, chooses tools and approved team/model resources, and remains responsible for authorized work and evidence. It cannot widen policy or approve its own held actions. In implemented S14, coordinator-only chat has no tools or warm computer; work uses its separate grant path. **Team:** Bots using installation-approved work resources/accounts for the assigned purpose. S15 defaults to shared team access without repeated per-Bot setup; explicit narrower restrictions still apply. This does not retroactively declassify S14-private sources or expose raw session/credential material. diff --git a/docs/adr/0093-s16-model-choice-and-observed-usage.md b/docs/adr/0093-s16-model-choice-and-observed-usage.md new file mode 100644 index 00000000..ab76e51f --- /dev/null +++ b/docs/adr/0093-s16-model-choice-and-observed-usage.md @@ -0,0 +1,29 @@ +--- +status: implemented for MODEL16-01 (#421); deterministic and real-bundle checks passed; CI/review pending +date: 2026-11-18 +scope: S16-AC14; FR-02/13/14/27/31/38; NFR-02/03/06/09 +--- + +# Explicit Bot model pins and observed model usage + +## Context and alternatives + +BOT16-01 already stores an owner-selected route/model/effort and resolves it when admitting work. MODEL15 already owns physical-send authorization, exact effort controls, conservative reservations, provider telemetry and native contexts through Schway's public host API. The S16 client has Bot model controls but does not show these recorded observations. Its Bot resolver and form also silently return to the installation default when a saved selection disappears. + +Reusing the existing MODEL service and Bot controls is simpler than adapting Rakazo's provider settings, which would import assumptions about upstream accounts and execution. A separate model registry, provider SDK or session migration would duplicate protected authority. No upstream source or new dependency is needed for this slice. + +## Decision + +1. A non-null Bot selection is an exact pin. If no longer approved, interpretation/admission holds with `selection_pinned`; neither the resolver nor an unrelated profile edit substitutes the default. The owner can explicitly choose another approved selection or the installation default. This supersedes only the fallback behavior in ADR 0088 decision 6 and `s16-bots/v1`. +2. Updating a Bot's model applies to newly admitted work. Existing work retains its POLICY `selectionPin`, native context and reservations. Later requests retain the same Bot/conversation and current sourced memory, using a fresh native work context under the new selection. No native session or credential is copied between routes. +3. Add `s16-client-models/v1`: a protected read-only catalog/budget projection and bounded per-request observations in conversation snapshots. Show actual recorded provider/model, requested/sent/reported effort, tokens, physical sends, state and unknown measurements. Scripted sends remain explicitly unobservable; subscription spend remains unknown and configured upper bounds are not described as measured bills. +4. Display route/account/billing/recipient identities, current availability and finite limits alongside the existing Bot model controls. Sign-in uses the existing protected `/settings/provider` flow. A catalog read makes no provider/network call and cannot register a route, create an account, increase billing or approve disclosure. New route/account/billing configuration retains its existing owner boundary and current POLICY/DATA15 intersection. +5. Query observations by at most 32 already-authorized work identities, using an additive index and a bounded SQL result. No prompt, output, credential or native-session handle enters the client projection. No journal-format/default-runtime/policy migration occurs. Old clients ignore additive fields; services without MODEL omit the capability. + +## Verification + +Deterministic composed-client tests must cover unavailable pins without fallback, profile edits preserving explicit pins, active-work selection versus subsequent requests, retained Bot/conversation/memory, actual versus unknown telemetry, stale/authenticated reads, bounded SQL projections, current recipient/account/budget guards and no provider work on reads. Run the existing packed Schway consumer and model dispatch/renewal/disclosure/restart regressions. Real React bundle tests cover English/Thai controls and usage at desktop/mobile widths. Live subscription/account/device evidence remains separately attributed to #431; fixtures do not certify it. + +## Current evidence + +The composed client/model/Bot/dispatch/disclosure/restart/packed-consumer suites pass 118 tests. Reinstating the old resolver makes the withdrawn-pin regression fail. Real React bundle checks pass in English at 1440 px and Thai at 390 px, including an unavailable saved pin, an unrelated profile edit, explicit default selection, protected sign-in entry, recorded unknown usage and no horizontal overflow. The exact packed Schway artifact is loaded in a fresh process: importing/creating a headless host loads no unselected provider implementation or TUI, then the existing protocol consumer checks exact physical-send authorization, pins, caps and renewal. Local typecheck, provenance and diff checks pass. Live provider/account evidence remains unrun here and owned by #431. diff --git a/docs/contracts/s16-bots-v1.md b/docs/contracts/s16-bots-v1.md index 07df0a78..7601ded3 100644 --- a/docs/contracts/s16-bots-v1.md +++ b/docs/contracts/s16-bots-v1.md @@ -28,7 +28,7 @@ Bounds: name 1–60 characters, responsibility up to 2000, at most 32 created Bo ## Conversations -- `ConversationPolicy` (`createConversationPolicy({ bots })`) resolves `{ bot, selection, route, excluded }` per `conversationId`; interpretation and work both use that selection and route. `selection` is the Bot's choice when it is still in the policy's selections, else `conversation.selection`. Work `selectionPin` is that selection; physical reservations use the work's own selection. +- `ConversationPolicy` (`createConversationPolicy({ bots })`) resolves `{ bot, selection, route, excluded }` per `conversationId`; interpretation and work both use that selection and route. `selection` is the Bot's exact choice, or `conversation.selection` only when the owner selected the default. A saved choice no longer in policy holds `selection_pinned` (MODEL16-01, ADR 0093); it never falls back silently. Work `selectionPin` is that selection; physical reservations use the work's own selection. - `ConversationOptions.admitConversation(conversationId)` runs for every new request (message, clarification, routine occurrence, assignment) and refuses `bot_archived` / `bot_unavailable`. - Owner decisions for a work include `{"bot":{"name","responsibility"}}` when the profile has either, and `{"assignment":{…}}` for a child. diff --git a/docs/contracts/s16-models-v1.md b/docs/contracts/s16-models-v1.md new file mode 100644 index 00000000..22c9fc86 --- /dev/null +++ b/docs/contracts/s16-models-v1.md @@ -0,0 +1,11 @@ +# s16-client-models/v1 + +MODEL16-01 (#421), ADR 0093. This is an additive protected S16 projection over MODEL15 and BOT16-01, not another provider, registry or approval service. + +- `GET /api/s16/client/models` returns configured approved-route metadata, installed-policy availability and finite/unknown budget facts. Current owner authentication, exact Host, Fetch Metadata and no-store response rules apply. Reading never lists an account catalog, renews a credential or starts inference. +- `ClientCapabilities.models` advertises this projection only when MODEL is composed. Bot model/effort changes continue to use exact revision-bound `s16-bot-command/v1`; non-null selections are exact pins. Missing pins hold `selection_pinned`; a form never converts an unavailable saved selection to the default through an unrelated edit. +- Conversation snapshots add `modelUsage` with `records` keyed by request ID and an explicit `truncated` flag. Only the authorized snapshot's work identities are queried, at most 32. The protected journal query returns at most 128 recent steps; selection history outside the window is not inferred to be empty. +- Each step exposes recorded provider/model, exact selection, reason/state/code, effort observations, token samples/totals, physical-send counts and usage. No prompt/output/native-session handle is returned. Null telemetry remains unknown; provider effort reports do not prove internal computation, and configured spend bounds are not measured bills. +- Bot updates affect future work admission; an active work's POLICY selection pin is unchanged. New requests retain product Bot/conversation/source lineage while Schway creates compatible native contexts. Private-recipient, account, billing, limits and unknown-effect guards remain mandatory. + +The existing protected `/settings/provider` surface handles sign-in to configured supported Schway routes. This API has no route/account/credential/billing mutation. New routes are not synthesized from a model catalog or source document. S14 remains the default runtime and S15 remains opt-in; installed policies retain their exact meaning. diff --git a/docs/tickets/S16-rakazo-experience-roadmap.md b/docs/tickets/S16-rakazo-experience-roadmap.md index f999a2d9..08485f5c 100644 --- a/docs/tickets/S16-rakazo-experience-roadmap.md +++ b/docs/tickets/S16-rakazo-experience-roadmap.md @@ -132,3 +132,5 @@ CONN16-01 [#417](https://github.com/chayapats/jit/issues/417), MCP16-01 [#418](h Artifact revision/HTML preview (#407), file-to-VM collection (#433), and live steering (#406) remain required despite the first working file client. Search/organization (#428) is required; spaces are conditional on a reviewed single-owner isolation/availability decision, never implicit multi-user tenancy. Every substantial slice records reuse versus a simpler alternative; current frameworks/storage are not product scope limits. Publication validation rereads every issue, required sections, native parents/dependencies and readiness; checks the graph for cycles and verifies all rows/acceptances/requirements have owners. Documentation-only validation runs link checks and `git diff --check`; no runtime tests are claimed by this PR. + +MODEL16-01 [#421](https://github.com/chayapats/jit/issues/421) supplies exact Bot pins and protected route/usage projections through [s16-client-models/v1](../contracts/s16-models-v1.md), reusing MODEL15's public Schway composition. [ADR 0093](../adr/0093-s16-model-choice-and-observed-usage.md) records the no-fallback choice, current evidence and separate live-account gate. diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 8fdb6d70..f4caa419 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -6202,9 +6202,55 @@ export const en: Record = { "s16.bots.responsibility": "Responsibility", "s16.bots.responsibilityHint": "What this Bot looks after. It still works only within your rules.", "s16.bots.model": "Model", - "s16.bots.modelDefault": "Same as Jit (default)", + "s16.bots.modelDefault": "Use installation default", "s16.bots.modelInstallation": "Installation default", - "s16.bots.modelUnavailable": "The chosen model is not available now, so new work uses the default.", + "s16.bots.modelUnavailable": "The pinned model is unavailable. Choose an approved model or explicitly select the installation default before starting new work.", + "s16.bots.modelUnavailableChoice": "Unavailable pinned model (choose explicitly)", + "s16.models.title": "Model routes and usage", + "s16.models.pinHint": "This pins the exact route, model and effort for new work. Running work keeps its original pin.", + "s16.models.loadFailed": "Model information could not be refreshed.", + "s16.models.configuredHint": "These routes are configured for this installation. Configuration and local sign-in do not prove a successful live call.", + "s16.models.signIn": "Manage protected model sign-in", + "s16.models.empty": "No model routes are configured.", + "s16.models.held": "Unavailable for new work", + "s16.models.available": "Configured and approved; checked again at dispatch", + "s16.models.account": "Account reference", + "s16.models.billing": "Billing reference", + "s16.models.recipient": "Data recipient", + "s16.models.budget": "Limits and recorded usage", + "s16.models.budgetHint": "Reservations are conservative charges. Measurements may be unknown. Subscription access is not a measured zero cost.", + "s16.models.reserved": "Reserved", + "s16.models.measured": "Measured", + "s16.models.ceiling": "Ceiling", + "s16.models.unknown": "Unknown", + "s16.models.partial": "Some usage remains unknown; displayed numbers are measured subtotals.", + "s16.models.subscriptionLimits": "Subscription limits: {calls} calls, {steps} steps and {activeMs} ms per work; {concurrency} concurrent works.", + "s16.models.unsettled": "Unsettled reservations: {count}", + "s16.models.workUsage": "Recorded model usage", + "s16.models.truncated": "Only recent work steps are shown; earlier steps are retained by the service.", + "s16.models.stepState": "Recorded step state", + "s16.models.inputTokens": "Input tokens", + "s16.models.outputTokens": "Output tokens", + "s16.models.sends": "Observed physical sends", + "s16.models.reservedCalls": "Reserved calls", + "s16.models.spend": "Measured spend (minor units)", + "s16.models.effortHint": "Requested, sent and provider-reported effort are separate observations; they do not prove internal computation.", + "s16.models.sentEffort": "Sent effort", + "s16.models.reportedEffort": "Provider-reported effort", + "s16.models.requestedEffort": "Requested effort", + "s16.models.state.selected": "Selected; not yet dispatched", + "s16.models.state.running": "Running", + "s16.models.state.completed": "Completed", + "s16.models.state.held": "Held", + "s16.models.state.failed": "Failed", + "s16.models.state.reconcile_only": "Needs reconciliation", + "s16.models.dimension.attempts": "Attempts", + "s16.models.dimension.steps": "Steps", + "s16.models.dimension.calls": "Calls", + "s16.models.dimension.reads": "Reads", + "s16.models.dimension.outputBytes": "Output bytes", + "s16.models.dimension.activeMs": "Active milliseconds", + "s16.models.dimension.spendMinor": "Spend in minor units", "s16.bots.assignments": "Other Bots can hand it tasks", "s16.bots.resources": "Uses", "s16.bots.resourcesHint": "Team defaults. Untick anything this Bot should not use.", diff --git a/src/i18n/th.ts b/src/i18n/th.ts index a0660cf8..96b0bcc3 100644 --- a/src/i18n/th.ts +++ b/src/i18n/th.ts @@ -6206,9 +6206,55 @@ export const th = { "s16.bots.responsibility": "หน้าที่", "s16.bots.responsibilityHint": "สิ่งที่ Bot นี้ดูแล โดยยังทำงานภายใต้กฎของคุณเท่านั้น", "s16.bots.model": "โมเดล", - "s16.bots.modelDefault": "เหมือนจิต (ค่าเริ่มต้น)", + "s16.bots.modelDefault": "ใช้ค่าเริ่มต้นของเครื่องนี้", "s16.bots.modelInstallation": "ค่าเริ่มต้นของเครื่องนี้", - "s16.bots.modelUnavailable": "โมเดลที่เลือกใช้ไม่ได้ตอนนี้ งานใหม่จึงใช้ค่าเริ่มต้น", + "s16.bots.modelUnavailable": "โมเดลที่ pin ไว้ใช้ไม่ได้ กรุณาเลือกโมเดลที่อนุญาตหรือเลือกค่าเริ่มต้นของเครื่องอย่างชัดเจนก่อนเริ่มงานใหม่", + "s16.bots.modelUnavailableChoice": "โมเดลที่ pin ไว้ใช้ไม่ได้ (ต้องเลือกเอง)", + "s16.models.title": "Model routes และการใช้งาน", + "s16.models.pinHint": "ตัวเลือกนี้ pin route, model และ effort สำหรับงานใหม่ งานที่กำลังรันจะใช้ pin เดิมต่อ", + "s16.models.loadFailed": "รีเฟรชข้อมูลโมเดลไม่สำเร็จ", + "s16.models.configuredHint": "Routes เหล่านี้ถูกตั้งค่าไว้สำหรับเครื่องนี้ การตั้งค่าและการลงชื่อเข้าใช้ยังไม่ยืนยันว่าเรียกโมเดลจริงสำเร็จ", + "s16.models.signIn": "จัดการการลงชื่อเข้าใช้โมเดลในพื้นที่ป้องกัน", + "s16.models.empty": "ยังไม่ได้ตั้งค่า model route", + "s16.models.held": "ยังใช้เริ่มงานใหม่ไม่ได้", + "s16.models.available": "ตั้งค่าและอนุญาตแล้ว ระบบจะตรวจอีกครั้งก่อนส่ง", + "s16.models.account": "ข้อมูลอ้างอิงบัญชี", + "s16.models.billing": "ข้อมูลอ้างอิงการเรียกเก็บเงิน", + "s16.models.recipient": "ผู้รับข้อมูล", + "s16.models.budget": "ขอบเขตและการใช้งานที่บันทึกไว้", + "s16.models.budgetHint": "ยอดจองเป็นการคิดเผื่อไว้ ค่าที่วัดได้อาจยังไม่ทราบ การใช้ subscription ไม่ได้แปลว่าวัดค่าใช้จ่ายได้เป็นศูนย์", + "s16.models.reserved": "จองแล้ว", + "s16.models.measured": "วัดได้", + "s16.models.ceiling": "เพดาน", + "s16.models.unknown": "ไม่ทราบ", + "s16.models.partial": "การใช้งานบางส่วนยังไม่ทราบ ตัวเลขที่แสดงเป็นยอดรวมเฉพาะส่วนที่วัดได้", + "s16.models.subscriptionLimits": "ขอบเขต subscription: {calls} calls, {steps} steps และ {activeMs} ms ต่องาน; พร้อมกัน {concurrency} งาน", + "s16.models.unsettled": "ยอดจองที่ยังไม่ยุติ: {count}", + "s16.models.workUsage": "การใช้โมเดลที่บันทึกไว้", + "s16.models.truncated": "แสดงเฉพาะ steps ล่าสุด ระบบยังเก็บ steps ก่อนหน้าไว้", + "s16.models.stepState": "สถานะ step ที่บันทึกไว้", + "s16.models.inputTokens": "Input tokens", + "s16.models.outputTokens": "Output tokens", + "s16.models.sends": "จำนวนการส่งจริงที่สังเกตได้", + "s16.models.reservedCalls": "Calls ที่จองแล้ว", + "s16.models.spend": "ค่าใช้จ่ายที่วัดได้ (หน่วยย่อยของสกุลเงิน)", + "s16.models.effortHint": "Effort ที่ขอ ที่ส่ง และที่ provider รายงานเป็นคนละหลักฐาน และไม่ยืนยันการคำนวณภายใน", + "s16.models.sentEffort": "Effort ที่ส่ง", + "s16.models.reportedEffort": "Effort ที่ provider รายงาน", + "s16.models.requestedEffort": "Effort ที่ขอ", + "s16.models.state.selected": "เลือกแล้ว ยังไม่ส่ง", + "s16.models.state.running": "กำลังทำงาน", + "s16.models.state.completed": "เสร็จแล้ว", + "s16.models.state.held": "รอดำเนินการ", + "s16.models.state.failed": "ล้มเหลว", + "s16.models.state.reconcile_only": "ต้องตรวจสอบผลที่ยังไม่ชัดเจน", + "s16.models.dimension.attempts": "Attempts", + "s16.models.dimension.steps": "Steps", + "s16.models.dimension.calls": "Calls", + "s16.models.dimension.reads": "Reads", + "s16.models.dimension.outputBytes": "Output bytes", + "s16.models.dimension.activeMs": "เวลาทำงาน (ms)", + "s16.models.dimension.spendMinor": "ค่าใช้จ่ายในหน่วยย่อย", "s16.bots.assignments": "ให้ Bot อื่นมอบงานให้ได้", "s16.bots.resources": "ใช้", "s16.bots.resourcesHint": "ค่าเริ่มต้นของทีม เอาเครื่องหมายออกจากสิ่งที่ไม่ต้องการให้ Bot นี้ใช้", diff --git a/src/s15/composition.ts b/src/s15/composition.ts index 8230bf78..57446fd7 100644 --- a/src/s15/composition.ts +++ b/src/s15/composition.ts @@ -1,6 +1,7 @@ import { websiteHostSensitive } from "./browser/sites"; import { fsyncSync, lstatSync, mkdirSync, openSync, closeSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { isAbsolute, join, resolve } from 'node:path'; +import { createS16ModelsPort } from '../s16/models'; import { createS16ClientHandler } from '../s16/http'; import { ComputerScopes } from '../s16/computers/scopes'; import { ScreenControl } from '../s16/computers/screen'; @@ -759,7 +760,7 @@ export async function composeS15(options: S15CompositionOptions) { return (['owner_named_send', 'github_default'] as const).some(mode => proposed.rules.some(r => r.mode === mode) && !current.rules.some(r => r.mode === mode)); } catch { return false; } }; - const clientHandler = createS16ClientHandler(conversation, { origin: options.origin, cookieName, authentication, memory, policyUpdate, ...(routines ? { routines, wake: () => { void composed.drain().catch(() => {}); } } : {}), ...(notifications ? { notifications } : {}), ...(computers ? { computers } : {}), ...(screen ? { screen } : {}), ...(bots ? { bots } : {}), ...(connections ? { connections } : {}), ...(files ? { files, imageAvailable: () => { const route = options.model.registry.current(options.conversation.selection); return !!route && route.availability === "available" && !!options.files?.imageProbes?.some(probe => probe.verdict === "pass" && probe.route === route.provider && probe.model === route.modelId); } } : {}) }); + const clientHandler = createS16ClientHandler(conversation, { origin: options.origin, cookieName, authentication, memory, policyUpdate, models: createS16ModelsPort(models, options.model.registry, policy), ...(routines ? { routines, wake: () => { void composed.drain().catch(() => {}); } } : {}), ...(notifications ? { notifications } : {}), ...(computers ? { computers } : {}), ...(screen ? { screen } : {}), ...(bots ? { bots } : {}), ...(connections ? { connections } : {}), ...(files ? { files, imageAvailable: () => { const route = options.model.registry.current(options.conversation.selection); return !!route && route.availability === "available" && !!options.files?.imageProbes?.some(probe => probe.verdict === "pass" && probe.route === route.provider && probe.model === route.modelId); } } : {}) }); const s16Web = await createS16WebHandler(clientHandler); const vmHandler = createVmApi(enrollment, async request => authenticate(request), { service: vm, ...(managers instanceof VmManagers ? { managers } : {}) }); const modelHandler = createModelProjectionHandler(models, authenticate), workHandler = createResponsibilityProjectionHandler(work, authenticate); diff --git a/src/s15/model/service.ts b/src/s15/model/service.ts index daf139d8..e996124d 100644 --- a/src/s15/model/service.ts +++ b/src/s15/model/service.ts @@ -108,6 +108,7 @@ export function openModelService(options: ModelOptions): ModelService { } if (limits.turns > 64 || limits.attempts > 8 || limits.activeMs > 3600000 || limits.outputBytes > 32768) fail('invalid_limits'); const journal = new DurableJournal(options.path, options.installationId, options.create, 0x4a4d5135), clock = options.clock ?? defaultClock; + journal.db.exec("CREATE INDEX IF NOT EXISTS model_records_work ON records(json_extract(json,'$.workId'))"); const active = new Set(); const key = (workId: string, stepId: string) => digest('s15.model.step.v1', { workId, stepId }); const time = () => { const t = clock.now(); nat(t); return t; }; @@ -371,11 +372,19 @@ export function openModelService(options: ModelOptions): ModelService { id(stepId); const work = options.policy.work.guard(actor), record = journal.get(key(work.id, stepId)); guard(actor, record); if (record.state !== 'completed' || record.output === null) fail('result_unavailable'); consume(record.output); }, - project(owner, workId): ModelBudgetView { + observations(owner, workIds) { + options.policy.owner.current(owner); + if (!Array.isArray(workIds) || workIds.length > 32) fail('invalid_shape'); + workIds.forEach(id); + const ids = [...new Set(workIds)]; if (!ids.length) return { records: [], truncated: false }; + const rows = journal.db.query<{ json: string }, string[]>(`SELECT json_remove(json,'$.output','$.session') AS json FROM records WHERE json_extract(json,'$.workId') IN (${ids.map(() => '?').join(',')}) ORDER BY rowid DESC LIMIT 129`).all(...ids); + return { records: rows.slice(0, 128).reverse().map(row => JSON.parse(row.json) as Omit), truncated: rows.length > 128 }; + }, + project(owner, workId, includeSelections = true): ModelBudgetView { // A fresh installation has no standing policy yet; the authenticated owner still reads routes and limits (POLICY15-02). const p: { budget: import('../policy').OperatingBudget | null } = options.policy.owner.current(owner) ?? { budget: null }; if (workId !== undefined) id(workId); // Installation ceilings always show installation charges; filtering selections cannot hide siblings' spend. - const reservations = options.policy.control.reservations(), totals = summarizeReservations(reservations), records = journal.all().filter(row => workId === undefined || row.workId === workId); + const reservations = options.policy.control.reservations(), totals = summarizeReservations(reservations), records = includeSelections ? journal.all().filter(row => workId === undefined || row.workId === workId) : []; const workIds = workId ? [workId] : [...new Set(records.map(row => row.workId))]; return { contract: 's15-model-budget/v1', currency: p.budget?.currency ?? null, subscriptionLimits: options.policy.control.subscriptionLimits(), ceilings: (Object.keys(totals.charged) as (keyof typeof totals.charged)[]).map(dimension => ({ dimension, ceiling: p.budget?.ceiling[dimension] ?? null, charged: dimension === 'spendMinor' && !p.budget ? null : totals.charged[dimension], measured: totals.measured[dimension], unknown: totals.unknown.includes(dimension) })), diff --git a/src/s15/model/types.ts b/src/s15/model/types.ts index 155a9e94..63a08b49 100644 --- a/src/s15/model/types.ts +++ b/src/s15/model/types.ts @@ -137,7 +137,10 @@ export interface ModelService { * invocation or result. Unknown effect outcomes remain the responsibility/owning adapter's concern. */ reconcile(owner: import('../policy').OwnerActor, recordId: string): ModelSelectionRecord; publish(actor: WorkActor, stepId: string, consume: (text: string) => void): void; - project(owner: import('../policy').OwnerActor, workId?: string): ModelBudgetView; + project(owner: import('../policy').OwnerActor, workId?: string, includeSelections?: boolean): ModelBudgetView; + /** Read at most 128 recent steps for at most 32 owner-authorized work IDs, without output or native handles. + * The query never reconciles, renews, reserves or starts work; truncation is explicit. */ + observations(owner: import('../policy').OwnerActor, workIds: readonly string[]): { records: Omit[]; truncated: boolean }; /** Drop cached catalog evidence for one route (or all) after an observed sign-in, logout or account change; * the next step renews and lists afresh. No credential is read or written. */ forgetRouteCatalog(route?: ApprovedModelRoute['provider']): void; diff --git a/src/s16/bots/service.ts b/src/s16/bots/service.ts index 91c16cac..6c72ca98 100644 --- a/src/s16/bots/service.ts +++ b/src/s16/bots/service.ts @@ -107,7 +107,8 @@ export class BotDirectory { if (record.state !== "active") throw new AppError("bot_archived", 409); const ref = this.isMain(botId) ? this.options.main.bot : record.ref ?? this.options.configured(botId)?.ref; if (!ref) throw new AppError("bot_unavailable", 409); - const selection = record.selection && (!policySelections || policySelections.some(s => same(s, record.selection))) ? record.selection : this.options.main.selection; + if (record.selection && policySelections && !policySelections.some(s => same(s, record.selection))) throw new AppError("selection_pinned", 409); + const selection = record.selection ?? this.options.main.selection; return { bot: structuredClone(ref), selection: structuredClone(selection), excluded: [...record.excluded], record }; } /** Ingress fence: a conversation of an archived Bot accepts no new message, routine run or assignment. */ diff --git a/src/s16/bots/types.ts b/src/s16/bots/types.ts index 9ac0f71b..6e7990a8 100644 --- a/src/s16/bots/types.ts +++ b/src/s16/bots/types.ts @@ -70,7 +70,7 @@ export interface BotView { id: string; revision: number; origin: BotOrigin; main: boolean; name: string; responsibility: string; selection: Selection | null; selectionLabel: string | null; - /** True when the chosen route is no longer approved and new work uses the installation default. */ + /** True when the exact chosen route is no longer approved; new work holds until the owner changes it. */ selectionUnavailable: boolean; excluded: string[]; assignments: boolean; state: "active" | "archived"; diff --git a/src/s16/client/client.ts b/src/s16/client/client.ts index 5d222402..0c246810 100644 --- a/src/s16/client/client.ts +++ b/src/s16/client/client.ts @@ -1,3 +1,4 @@ +import type { ClientModelsView } from "./contracts"; import { clientResponseBytes, type ClientConnectionsView, type ClientConnectionCommand, type ClientConnectionReceipt, type ClientSource, type ClientBotsView, type ClientBotDetail, type ClientBot, type ClientBotProposal, type ClientBotDraft, type ClientBotExport, type ClientBotCommand, type ClientBotReceipt, type ClientNotificationDevice, type ClientNotificationSettings, type ClientNotificationSubscribeCommand, type ClientSteer, type ClientSteerReceipt, type ClientRoutineDetail, type ClientRoutineDraft, type ClientRoutineList, type ClientRoutineOptions, type ClientRoutineProposal, type ClientRoutineReceipt, type ClientArtifactDetail, type ClientArtifactInputCommand, type ClientArtifactItem, type ClientArtifactList, type ClientArtifactQuery, type ClientMemoryCommand, type ClientMemoryDetail, type ClientMemoryList, type ClientMemoryQuery, type ClientMemoryResult, type ClientBootstrap, type ClientDecision, type ClientEvents, type ClientMessage, type ClientReceipt, type ClientRequest, type ClientSnapshot } from "./contracts"; import type { FileArtifact, FileReference, FileUpload, FileUploadCommand } from "../files/types"; import type { ScreenCommand, ScreenCommandResult, ScreenView } from "../computers/screen"; @@ -14,6 +15,10 @@ const record = (value: unknown): value is Record => typeof valu const identifier = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9_-]{1,128}$/.test(value); const safeCode = (value: unknown) => typeof value === "string" && /^[a-z][a-z0-9_]{0,127}$/.test(value) ? value : "client_unavailable"; const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0; +const nullableCount = (value: unknown) => value === null || count(value); +const modelRef = (value: unknown) => record(value) && identifier(value.id) && count(value.revision) && count(value.generation); +const modelChoice = (value: unknown) => record(value) && modelRef(value.route) && modelRef(value.model) && typeof value.effort === "string"; +const quantity = (value: unknown) => nullableCount(value) || typeof value === "string" && /^[0-9]+$/.test(value); const sha256 = (value: unknown) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value); const invalid = (): never => { throw new JitClientError("client_protocol_invalid", null, "response"); }; const id = (value: string) => { if (!identifier(value)) throw new JitClientError("invalid_identity", null, "not_sent"); return value; }; @@ -43,6 +48,17 @@ export class JitClient { const { csrf: _csrf, ...projection } = data as unknown as ClientBootstrap; return projection; } + /** Reads protected route configuration and measured/unknown budgets; starts no provider work. */ + async models(signal?: AbortSignal): Promise { + const data = await this.call("/models", "GET", undefined, signal); + if (!record(data) || data.contract !== "s16-client-models/v1" || !Array.isArray(data.routes) || data.routes.length > 64 || !record(data.budget) || !Array.isArray(data.budget.ceilings)) return invalid(); + for (const route of data.routes) if (!record(route) || !modelChoice(route.selection) || !["codex", "grok"].includes(String(route.provider)) || typeof route.modelId !== "string" || typeof route.approved !== "boolean" || !modelRef(route.account) || !modelRef(route.billing) || !modelRef(route.recipient) || !["subscription", "metered"].includes(String(route.charge)) || !["available", "unavailable", "quota"].includes(String(route.availability)) || route.holdCode !== null && typeof route.holdCode !== "string") return invalid(); + for (const ceiling of data.budget.ceilings) if (!record(ceiling) || typeof ceiling.dimension !== "string" || !quantity(ceiling.charged) || !quantity(ceiling.measured) || !quantity(ceiling.ceiling) || typeof ceiling.unknown !== "boolean") return invalid(); + const limits = data.budget.subscriptionLimits; + if (limits !== null && (!record(limits) || !count(limits.concurrency) || !record(limits.perWork) || ![limits.perWork.calls, limits.perWork.steps, limits.perWork.activeMs].every(count))) return invalid(); + if (!count(data.budget.unsettled)) return invalid(); + return data as unknown as ClientModelsView; + } /** Creates one local immutable send identity; callers retain this command through response loss. */ prepareMessage(conversationId: string, text: string, files: readonly FileReference[] = []): ClientMessage { id(conversationId); @@ -62,6 +78,15 @@ export class JitClient { async snapshot(conversationId: string, signal?: AbortSignal): Promise { const data = await this.call(`/conversations/${id(conversationId)}`, "GET", undefined, signal); if (!record(data) || data.contract !== "s16-client-snapshot/v1" || !record(data.conversation) || data.conversation.contract !== "s15.owner-view/v1" || data.conversation.conversationId !== conversationId || !Number.isSafeInteger(data.conversation.cursor) || !Array.isArray(data.conversation.rows) || data.conversation.rows.length > 32 || !Array.isArray(data.conversation.needsYou)) return invalid(); + if (data.modelUsage !== undefined) { + if (!record(data.modelUsage) || !Array.isArray(data.modelUsage.records) || data.modelUsage.records.length > 128 || typeof data.modelUsage.truncated !== "boolean") return invalid(); + const ids = new Set(data.conversation.rows.map(row => record(row) ? row.requestId : null)); + for (const step of data.modelUsage.records) { + if (!record(step) || !identifier(step.id) || !ids.has(step.requestId) || typeof step.provider !== "string" || typeof step.model !== "string" || !modelChoice(step.selection) || !record(step.effort) || typeof step.effort.requested !== "string" || !record(step.usage) || !quantity(step.usage.spendMinor) || !nullableCount(step.physicalSends) || !nullableCount(step.refusedSends) || !count(step.reservedCalls) || typeof step.partial !== "boolean") return invalid(); + if (step.tokens !== null && (!record(step.tokens) || !nullableCount(step.tokens.inputTokens) || !nullableCount(step.tokens.outputTokens))) return invalid(); + if (step.effort.attempts !== undefined && (!Array.isArray(step.effort.attempts) || step.effort.attempts.some(value => value !== null && (!record(value) || value.sent !== null && typeof value.sent !== "string" || value.reported !== null && typeof value.reported !== "string")))) return invalid(); + } + } for (const row of data.conversation.rows) if (!record(row) || !identifier(row.requestId) || !Number.isSafeInteger(row.revision) || !record(row.receipt) || row.receipt.conversationId !== conversationId) return invalid(); return data as unknown as ClientSnapshot; } diff --git a/src/s16/client/contracts.ts b/src/s16/client/contracts.ts index 8853c63b..7f23b427 100644 --- a/src/s16/client/contracts.ts +++ b/src/s16/client/contracts.ts @@ -1,6 +1,7 @@ import type { ConversationCommand, ConversationDecisionCommand, ConversationEvent, ConversationReceipt, ConversationSteerCommand, ConversationSteerReceipt } from "../../s15/conversation/types"; import type { ConversationListEntry, ConversationNeedsYou, ConversationOwnerRow, ConversationOwnerView } from "../../s15/conversation/owner-view"; import type { FileArtifact, FileLimits } from "../files/types"; +import type { ApprovedModelRoute, ModelBudgetView, ModelSelectionRecord } from "../../s15/model/types"; /** Versioned client capabilities describe actual composed operations, never execution authority. */ export interface ClientCapabilities { @@ -28,6 +29,8 @@ export interface ClientCapabilities { bots?: { available: false; code: "bots_unavailable" } | { available: true; contract: "s16-client-bots/v1"; delegation: boolean }; /** CONN16-01/MCP16-01/OPEN16-01 connections (`s16-client-connections/v1`): GitHub plus HTTPS tool sources. */ connections?: { available: false; code: "connections_unavailable" } | { available: true; contract: "s16-client-connections/v1"; kinds: ("mcp" | "openapi" | "graphql")[]; github: boolean; oauth: boolean }; + /** MODEL16-01: configured routes and recorded work usage; reads never start provider work. */ + models?: { available: true; contract: "s16-client-models/v1" }; } /** Authenticated, no-store bootstrap. CSRF stays in the transport, outside persisted client state. */ export interface ClientBootstrap { @@ -45,7 +48,23 @@ export interface ClientBootstrap { policyUpdate?: boolean; } /** Currently authorized owner projection; completion cannot be reconstructed from progress events. */ -export interface ClientSnapshot { contract: "s16-client-snapshot/v1"; conversation: ConversationOwnerView; /** Additive (BOT16-01): the conversation's Bot. */ botId?: string } +export interface ClientSnapshot { contract: "s16-client-snapshot/v1"; conversation: ConversationOwnerView; /** Additive (BOT16-01): the conversation's Bot. */ botId?: string; modelUsage?: ClientModelUsage } + +/** Configuration is not proof of a successful live provider call. Every route still passes POLICY/DATA15. */ +export interface ClientModelsView { + contract: "s16-client-models/v1"; + routes: (Pick & { approved: boolean; holdCode: string | null })[]; + budget: Pick; +} +/** Observed work-step facts only; no prompt/output/native session or inferred zero measurements. */ +export interface ClientModelStep extends Pick { + requestId: string; provider: string; model: string; selection: ApprovedModelRoute["selection"]; + physicalSends: number | null; refusedSends: number | null; reservedCalls: number; + /** Known numbers are subtotals when any call/measurement in this step remains unknown. */ + partial: boolean; +} +/** At most 128 recent steps from this snapshot's already-authorized request identities. */ +export interface ClientModelUsage { records: ClientModelStep[]; truncated: boolean } /** One currently authorized request, including requests older than the bounded conversation window. */ export interface ClientRequest { contract: "s16-client-request/v1"; conversationId: string; receipt: ConversationReceipt; row: ConversationOwnerRow } /** Monotonic conversation-bound metadata, used only to invalidate and refresh owner projections. */ diff --git a/src/s16/http.ts b/src/s16/http.ts index 5c40b204..6b6cc85c 100644 --- a/src/s16/http.ts +++ b/src/s16/http.ts @@ -14,6 +14,7 @@ import type { ScreenControl } from "./computers/screen"; import type { ComputerDirectory } from "./computers/service"; import type { BotDirectory } from "./bots/service"; import type { ConnectionDirectory } from "./connections/service"; +import type { S16ModelsPort } from "./models"; import { connectionLimits } from "./connections/types"; /** @@ -24,7 +25,7 @@ import { connectionLimits } from "./connections/types"; export const artifactPreviewPolicy = "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src 'none'; form-action 'none'; base-uri 'none'; frame-ancestors 'self'"; /** Protected shared client adapter. It adds no engine, database, approval authority or automatic retry. */ -export function createS16ClientHandler(app: ConversationApplication, options: { origin: string; cookieName: string; /** AUTH16-01 banner: true while a newer default proposal awaits the owner. */ policyUpdate?: (actor: Actor) => boolean; authentication: ConversationHttpAuthentication; files?: FileStore; imageAvailable?: () => boolean; memory?: S16MemoryPort; routines?: RoutineService; wake?: () => void; notifications?: NotificationService; computers?: ComputerDirectory; /** DESK16-01 watch and take over a working computer's screen (`s16-computer-screen/v1`). */ screen?: ScreenControl; /** BOT16-01 persistent Bots (`s16-client-bots/v1`). */ bots?: BotDirectory; /** CONN16-01 connections (`s16-client-connections/v1`). */ connections?: ConnectionDirectory }): (request: Request) => Promise { +export function createS16ClientHandler(app: ConversationApplication, options: { origin: string; cookieName: string; /** AUTH16-01 banner: true while a newer default proposal awaits the owner. */ policyUpdate?: (actor: Actor) => boolean; authentication: ConversationHttpAuthentication; models?: S16ModelsPort; files?: FileStore; imageAvailable?: () => boolean; memory?: S16MemoryPort; routines?: RoutineService; wake?: () => void; notifications?: NotificationService; computers?: ComputerDirectory; /** DESK16-01 watch and take over a working computer's screen (`s16-computer-screen/v1`). */ screen?: ScreenControl; /** BOT16-01 persistent Bots (`s16-client-bots/v1`). */ bots?: BotDirectory; /** CONN16-01 connections (`s16-client-connections/v1`). */ connections?: ConnectionDirectory }): (request: Request) => Promise { const origin = new URL(options.origin); if (origin.origin !== options.origin || !/^[A-Za-z0-9_-]+$/.test(options.cookieName)) throw new AppError("invalid_configuration"); const json = (value: unknown, status = 200): Response => { @@ -48,7 +49,7 @@ export function createS16ClientHandler(app: ConversationApplication const formats = [ ...["txt", "md", "markdown", "csv", "tsv"].map(extension => ({ extension, mime: "text/plain", bytes: textBytes })), ...(binary ? [{ extension: "pdf", mime: "application/pdf", bytes: files!.limits.fileBytes }] : []), ...(images ? ["png", "jpg", "jpeg"].map(extension => ({ extension, mime: extension === "png" ? "image/png" : "image/jpeg", bytes: files!.limits.fileBytes })) : []) ]; - return { contract: "s16-client-capabilities/v1", revision: app.options.memory?.fileContract ? 2 : 1, textMessages: true, progress: "control_events", exactDecisions: !!(app.options.policy.actionSlips && app.options.policy.decideAction && app.options.policy.decidePending && app.options.policy.dispatchAction), liveSteering: true, + return { contract: "s16-client-capabilities/v1", revision: app.options.memory?.fileContract ? 2 : 1, textMessages: true, ...(options.models ? { models: { available: true as const, contract: "s16-client-models/v1" as const } } : {}), progress: "control_events", exactDecisions: !!(app.options.policy.actionSlips && app.options.policy.decideAction && app.options.policy.decidePending && app.options.policy.dispatchAction), liveSteering: true, uploads: files && app.options.files ? { available: true, limits: { ...files.limits }, extensions: formats.map(format => format.extension), formats, textBytes, memory: !!app.options.memory?.fileContract, ...(app.options.memory?.fileContract ? { memoryContract: app.options.memory.fileContract } : {}), ...(files.parser && !images ? { unavailableBinary: binary ? "images_unsupported" as const : "sanitizer_unavailable" as const } : {}), ...(binary ? { binary: { limits: { ...binaryLimits, originalBytes: Math.min(binaryLimits.originalBytes, files.limits.fileBytes) }, images } } : {}) } : { available: false, code: "upload_unavailable" }, @@ -180,6 +181,11 @@ export function createS16ClientHandler(app: ConversationApplication if (request.method === "POST" && screen[1]) { const input = await body(request, 4096); return json(await options.screen.command(currentOwner(), input)); } throw new AppError("method_rejected", 405); } + if (url.pathname === "/api/s16/client/models") { + if (request.method !== "GET" || url.search) throw new AppError("method_rejected", 405); + if (!options.models) throw new AppError("models_unavailable", 503); + return json(options.models.view(currentOwner())); + } const computer = /^\/api\/s16\/client\/computers(?:\/(commands))?$/.exec(url.pathname); if (computer) { if (!options.computers) throw new AppError("computers_unavailable", 503); @@ -237,7 +243,9 @@ export function createS16ClientHandler(app: ConversationApplication const conversationId = conversation[1]!; if (request.method === "GET" && !conversation[2]) { if (url.search) throw new AppError("invalid_body"); - return json({ contract: "s16-client-snapshot/v1", conversation: conversationOwnerView(app, authenticated.actor, conversationId), ...(options.bots ? { botId: options.bots.conversationBot(conversationId) } : {}) }); + const conversation = conversationOwnerView(app, authenticated.actor, conversationId); + const modelUsage = options.models?.usage(currentOwner(), conversation.rows.flatMap(row => row.scopeLine ? [{ requestId: row.requestId, workId: row.scopeLine.authorityId }] : [])); + return json({ contract: "s16-client-snapshot/v1", conversation, ...(modelUsage ? { modelUsage } : {}), ...(options.bots ? { botId: options.bots.conversationBot(conversationId) } : {}) }); } if (request.method === "GET" && conversation[2] === "events") { if ([...url.searchParams.keys()].some(key => key !== "after") || url.searchParams.getAll("after").length > 1 || !/^(?:0|[1-9]\d{0,15})$/.test(url.searchParams.get("after") ?? "0")) throw new AppError("cursor_invalid", 409); diff --git a/src/s16/models.ts b/src/s16/models.ts new file mode 100644 index 00000000..67b2c7c1 --- /dev/null +++ b/src/s16/models.ts @@ -0,0 +1,32 @@ +import type { OwnerActor, S15PolicyService } from "../s15/policy"; +import { canonical } from "../s15/conversation/validation"; +import type { ApprovedModelRegistry, ModelService } from "../s15/model/types"; +import type { ClientModelsView, ClientModelUsage } from "./client/contracts"; + +/** Protected read-only MODEL16 client seam. Callers supply only work IDs from an authenticated owner snapshot. */ +export interface S16ModelsPort { + view(owner: Owner): ClientModelsView; + usage(owner: Owner, requests: readonly { requestId: string; workId: string }[]): ClientModelUsage; +} + +/** Reuse MODEL's exact recorded controls/reservations, without provider discovery, reconciliation or inference. */ +export function createS16ModelsPort(models: ModelService, registry: ApprovedModelRegistry, policy: S15PolicyService): S16ModelsPort { + return { + view(owner) { + const current = policy.owner.current(owner), { currency, ceilings, subscriptionLimits, unsettled, routes } = models.project(owner, undefined, false); + return { contract: "s16-client-models/v1", routes: structuredClone(registry.list()).map(route => { + const approved = !!current?.selections.some(selection => canonical(selection) === canonical(route.selection)); + return { selection: route.selection, provider: route.provider, modelId: route.modelId, account: route.account, billing: route.billing, recipient: route.recipient, charge: route.charge, availability: route.availability, approved, + holdCode: !current ? "policy_required" : !approved ? "selection_pinned" : routes.find(row => canonical(row.selection) === canonical(route.selection))?.holdCode ?? null }; + }), budget: { currency, ceilings, subscriptionLimits, unsettled } }; + }, + usage(owner, requests) { + const ids = new Map(requests.map(row => [row.workId, row.requestId])); + const page = models.observations(owner, [...ids.keys()]); + return { truncated: page.truncated, records: page.records.map(row => ({ id: row.id, requestId: ids.get(row.workId)!, provider: row.route.provider, model: row.route.modelId, selection: row.route.selection, + state: row.state, code: row.code, createdAt: row.createdAt, tokens: row.tokens, usage: row.usage, providerRequests: row.providerRequests ?? null, effort: row.effort, reason: row.reason, controls: row.controls ?? null, + physicalSends: row.physicalDispatches?.filter(send => !send.refusal).length ?? null, refusedSends: row.physicalDispatches?.filter(send => !!send.refusal).length ?? null, reservedCalls: row.reservations.length, + partial: Object.values(row.usage).some(value => value === null) || row.tokenSamples.some(sample => !sample.usage || sample.usage.inputTokens === null || sample.usage.outputTokens === null) })) }; + }, + }; +} diff --git a/src/s16/web/BotsView.tsx b/src/s16/web/BotsView.tsx index 3f36efb1..6a7b0c08 100644 --- a/src/s16/web/BotsView.tsx +++ b/src/s16/web/BotsView.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react"; import type { Locale } from "../../i18n"; import { JitClientError, type JitClient } from "../client"; import type { ClientBot, ClientBotCommand, ClientBotDetail, ClientBotDraft, ClientBotProposal, ClientBotReceipt, ClientBotsView } from "../client/contracts"; +import { ModelsPanel } from "./ModelsPanel"; import { BotProposalCard } from "./BotProposalCard"; import type { Copy } from "./copy"; @@ -12,6 +13,7 @@ export interface BotsViewProps { client: JitClient; t: Copy; locale: Locale; /** Server capability. When false, no request is made and no control is shown. */ available: boolean; + modelsAvailable?: boolean; page: BotsPage; onNavigate(page: BotsPage): void; onStartChat(botId: string): void; @@ -34,7 +36,7 @@ export function botName(t: Copy, bot: Pick | undefin * New Bot form. Every change is one explicit command that is never retried silently; creating a Bot always goes * through the reviewed proposal card. */ -export function BotsView({ client, t, locale, available, page, onNavigate, onStartChat, onOpenConversation, onChanged, onFailure }: BotsViewProps) { +export function BotsView({ client, t, locale, available, modelsAvailable, page, onNavigate, onStartChat, onOpenConversation, onChanged, onFailure }: BotsViewProps) { const [data, setData] = useState(null), [detail, setDetail] = useState(null), [loadError, setLoadError] = useState(null); const [notice, setNotice] = useState(null), [reload, setReload] = useState(0), [proposal, setProposal] = useState(null), [confirm, setConfirm] = useState(false); const noticeRef = useRef(null), heading = useRef(null), importer = useRef(null), commands = useRef(0); @@ -122,6 +124,7 @@ export function BotsView({ client, t, locale, available, page, onNavigate, onSta {bot.state === "active" ? void send({ contract: "s16-bot-command/v1", requestId: uid(), kind: "bot.update", botId: bot.id, expectedRevision: bot.revision, name: draft.name, responsibility: draft.responsibility, selection: draft.selection, assignments: draft.assignments, excluded: draft.excluded }, () => t("s16.bots.saved"))} /> : bot.responsibility &&

{bot.responsibility}

} + {modelsAvailable && }
{bot.state === "active" && } {data.creation.available && } @@ -149,6 +152,7 @@ export function BotsView({ client, t, locale, available, page, onNavigate, onSta return

{t("s16.bots.title")}

{t("s16.bots.lead")}

+ {modelsAvailable && } {loading}{status} {data && <>
@@ -173,12 +177,14 @@ export function BotsView({ client, t, locale, available, page, onNavigate, onSta /** The exact editable Bot configuration; submitting creates a proposal (new Bot) or saves the profile (existing Bot). */ function BotForm({ t, data, initial, busy, submit, creating = false, main = false, onSubmit }: { t: Copy; data: ClientBotsView; initial: ClientBotDraft | null; busy: boolean; submit: string; creating?: boolean; main?: boolean; onSubmit(draft: ClientBotDraft): void }) { const [name, setName] = useState(initial?.name ?? ""), [responsibility, setResponsibility] = useState(initial?.responsibility ?? ""); - const [selection, setSelection] = useState(() => initial?.selection ? data.selections.findIndex(choice => same(choice.selection, initial.selection)) : -1); + const [selection, setSelection] = useState(() => initial?.selection ?? null); + const selectionKey = (value: NonNullable) => JSON.stringify([value.route.id, value.route.revision, value.route.generation, value.model.id, value.model.revision, value.model.generation, value.effort]); + const unavailable = selection !== null && !data.selections.some(choice => selectionKey(choice.selection) === selectionKey(selection)); const [excluded, setExcluded] = useState(initial?.excluded ?? []), [assignments, setAssignments] = useState(initial?.assignments ?? true), [invalid, setInvalid] = useState(false); return
{ event.preventDefault(); - if (!name.trim()) { setInvalid(true); return; } - onSubmit({ contract: "s16-bot-draft/v1", name: name.trim(), responsibility: responsibility.trim(), selection: selection >= 0 ? data.selections[selection]!.selection : null, excluded: excluded.filter(id => data.resources.some(resource => resource.id === id)).sort(), assignments }); + if (!name.trim() || unavailable) { setInvalid(true); return; } + onSubmit({ contract: "s16-bot-draft/v1", name: name.trim(), responsibility: responsibility.trim(), selection, excluded: excluded.filter(id => data.resources.some(resource => resource.id === id)).sort(), assignments }); }}> setName(event.target.value)} /> @@ -187,10 +193,16 @@ function BotForm({ t, data, initial, busy, submit, creating = false, main = fals