diff --git a/.agents/skills/typesafe-ai/LICENSE b/.agents/skills/typesafe-ai/LICENSE new file mode 100644 index 000000000..8c73b41b8 --- /dev/null +++ b/.agents/skills/typesafe-ai/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 TypeSafe AI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.agents/skills/typesafe-ai/SKILL.md b/.agents/skills/typesafe-ai/SKILL.md new file mode 100644 index 000000000..0109513f9 --- /dev/null +++ b/.agents/skills/typesafe-ai/SKILL.md @@ -0,0 +1,149 @@ +--- +name: typesafe-ai +license: MIT +description: > + Build AI-powered software with TypeSafe: small units of AI intelligence you + can use like programming primitives. Its System One models, including Jev, + turn natural language and application state into typed judgments and + probabilities that code can combine. Use when a feature needs programmable + common sense, when brainstorming what AI could make possible in an app, or + when an LLM prompt-and-parse step could become a structured decision. + Applications include routing, ranking, extraction, verification, and + interactive experiences; these are starting points, not the limits. + Read live docs and cookbooks to find useful patterns and discover new combinations. +--- + +# Build with TypeSafe + +TypeSafe makes units of AI intelligence usable like programming primitives: small +judgments you can compose into larger capabilities. Its **System One models** return +fast, focused judgments that software can consume directly. **Jev** is TypeSafe's +flagship and first System One model. It understands natural language and returns +typed answers and probabilities rather +than generating text or reasoning explanations. Code owns the workflow; the model +supplies programmable common sense where ordinary code needs semantic understanding. + +## Read the live docs + +**The live TypeSafe docs are the source of truth. Read them as part of the task.** +This skill gives direction; the docs carry current concepts, prompting guidance, +API contracts, SDK usage, models, limits, and worked examples. + +- Start with the [documentation index](https://docs.typesafe.ai/llms.txt) to discover + relevant pages and cookbooks. Use targeted reads rather than loading the entire site. +- Mintlify serves Markdown by appending `.md` to a page path, for example + [how to build with TypeSafe](https://docs.typesafe.ai/concepts/how-to-build-with-system-one.md). + Follow links from the index; convert extensionless documentation page links to + `.md` when useful. Resolve relative links against `https://docs.typesafe.ai`. +- Before writing an integration, read the current API or chosen SDK page and the + question guidance relevant to the design. For a new workflow, also inspect the + closest cookbook: it often shows a better decomposition than a generic classifier. +- If the index is unavailable, use the direct links below or the site's navigation. + If Markdown fetching fails, try the normal page. If live access is unavailable, + use available local docs or installed SDK types, state that limitation, and avoid + inventing version-dependent details. + +| Task | Start here; follow the relevant details | +| --- | --- | +| Understand the programming model | [System One](https://docs.typesafe.ai/concepts/system-one.md), [building guide](https://docs.typesafe.ai/concepts/how-to-build-with-system-one.md) | +| Explore what to build | [Use-case map](https://docs.typesafe.ai/concepts/use-case-map.md), then relevant cookbooks from the index | +| Prepare inputs and questions | [State](https://docs.typesafe.ai/concepts/state.md), [primitives](https://docs.typesafe.ai/primitives.md), then the chosen primitive's page | +| Decide how to handle uncertainty | [Confidence](https://docs.typesafe.ai/confidence.md) | +| Write API code | [HTTP API](https://docs.typesafe.ai/api.md), [Python SDK](https://docs.typesafe.ai/sdk/python.md), or [JavaScript SDK](https://docs.typesafe.ai/sdk/javascript.md) | +| Update an older integration | [Migration guide](https://docs.typesafe.ai/migrating-to-v1.md) and the installed SDK's current reference | + +## Find the useful shape + +Start from the behavior the user wants: what will the application show, select, +change, or hand off? Work backward to the judgments it needs. Keep known rules, +calculations, exact lookups, and execution in code. Preserve the user's chosen stack +and scope; add TypeSafe where semantic understanding helps. + +When brainstorming or choosing an architecture, consider more than classification. +The patterns below are starting points: combine primitives around the user's goal, +including ideas that do not fit an established recipe. + +- **Route and fill known arguments.** A request can select a handler and its typed + parameters. Ask useful branch-specific questions up front and consume only the + relevant answers. Explore [function calling](https://docs.typesafe.ai/cookbooks/function_calling.md) + and [speculative fan-out](https://docs.typesafe.ai/patterns/fan-out.md). +- **Select instead of generate.** Find candidate values or source spans in code, + use a judgment to select the intended one, then copy or normalize it. Code can + also assemble source text into a formatted document or reading guide. Explore + [value extraction](https://docs.typesafe.ai/cookbooks/pre_parsed_value_extraction_cookbook.md) + and [structure recovery](https://docs.typesafe.ai/cookbooks/autoformat.md). +- **Find and judge evidence.** Retrieve candidates, compare their relevance to a + query, and select useful context. Explore [reranking](https://docs.typesafe.ai/cookbooks/rerank_typesafe.md) + and [hierarchical classification](https://docs.typesafe.ai/cookbooks/hierarchical_classification.md). +- **Turn judgments into reusable data.** Score dimensions once, then let code or + user controls change weights, thresholds, rankings, and views. With labeled + outcomes, those signals can become classical ML features. Explore + [composite scoring](https://docs.typesafe.ai/patterns/composite-scoring.md) and + [feature discovery](https://docs.typesafe.ai/cookbooks/autoresearch_feature_discovery.md). +- **Verify and escalate.** Check specific claims or fields against their evidence; + send uncertain or failing cases to a person or reasoning model. Explore + [citation checks](https://docs.typesafe.ai/cookbooks/citation_check.md) and + [extraction cascades](https://docs.typesafe.ai/cookbooks/sde_cascade.md). +- **Respond to changing state.** Code can retain goals and observations while fresh + judgments guide the next bounded step. Keep inferred state distinct from observed + facts, and check freshness before applying a result to a changed situation. + +For open-ended requests, offer the few directions that best serve the user's goal +and recommend a starting point. For a concrete request, choose the relevant pattern +and build; a brainstorm is not a mandatory detour. + +## Design the judgments + +Choose by what the answer means, then read the relevant primitive page: + +| Need | Primitive | Important distinction | +| --- | --- | --- | +| One of a defined set | [Choice](https://docs.typesafe.ai/primitives/choice.md) | Picks one option; its distribution compares competing options | +| Whether a condition holds | [Noul](https://docs.typesafe.ai/primitives/noul.md) | Probability of yes; no separate confidence; use one per label when several may apply | +| Degree along a described dimension | [Score](https://docs.typesafe.ai/primitives/score.md) | Probability-weighted position on ordered levels; use comparable per-item Scores for graded ranking | + +Give each question enough relevant **state** to answer: source text, identities, +relationships, policies, and current facts. Prefer named JSON fields when context +has several parts. Put the judgment in **instructions** and define its possible +answers in **criteria**. Question IDs are for code and are not sent to the model; +include complete meaning in the question. Reference nested state with backticked +paths such as `ticket.messages[0].text`. + +Ask one narrow, coherent judgment per question. Split independently useful dimensions, +without destroying the relationship being judged. A bounded action selection or +contextual interpretation is valid; atomic does not mean literal fact extraction +or a one-sentence limit. Strings work for simple questions. Use structured objects +or arrays when definitions, contrasts, exclusions, or examples clarify instructions +or criteria. Score levels must describe concrete situations and stand on their own. + +Keep the needed answers available. Include a no-match outcome when nothing may fit; +use a separate presence judgment when it is independently useful. For source-value +selection, check candidate coverage: the model cannot choose an omitted value. + +## Compose and verify + +**Ask independent questions over the same state together**, including useful +speculative questions. They run in parallel and cannot see one another's answers. +State each speculative premise explicitly; code consumes the applicable answers. +A second request is warranted when an earlier answer is needed to fetch evidence, +construct new state, or determine the next options. Extra questions still use tokens; +measure actual request budgets, cost, and end-to-end latency. + +Use probabilities and confidence to guide behavior, with thresholds evaluated on +the user's data and consequences. Choice/Score confidence summarizes distribution +concentration, not overall workflow correctness or permission to act. A Noul near +0.5 means similar probability for yes and no, not medium intensity. Several +acceptable alternatives can also spread probability; low confidence need not +invalidate a harmless preference choice. Ignore uncertainty on unused branches. + +Keep policy explicit and raw judgments reusable. Weighted scores suit compensating +preferences; an “any serious violation” rule needs separate conditions. Changing a +weight or display filter need not rerun inference when evidence and question meanings +are unchanged. Typed output guarantees the interface, not truth. System One models +are trained for calibrated decisions; validate their performance in the target domain. + +Test representative cases and the resulting application behavior. For failures, +inspect the exact state, questions, candidates, answers, composition, and observed +outcome. Separate missing evidence, model errors, code errors, and service failures. +Treat cookbook thresholds and demo results as examples to evaluate, not universal +rules or permanent model limitations. Keep API credentials server-side in web apps. diff --git a/.claude/skills/typesafe-ai/LICENSE b/.claude/skills/typesafe-ai/LICENSE new file mode 100644 index 000000000..8c73b41b8 --- /dev/null +++ b/.claude/skills/typesafe-ai/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 TypeSafe AI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.claude/skills/typesafe-ai/SKILL.md b/.claude/skills/typesafe-ai/SKILL.md new file mode 100644 index 000000000..0109513f9 --- /dev/null +++ b/.claude/skills/typesafe-ai/SKILL.md @@ -0,0 +1,149 @@ +--- +name: typesafe-ai +license: MIT +description: > + Build AI-powered software with TypeSafe: small units of AI intelligence you + can use like programming primitives. Its System One models, including Jev, + turn natural language and application state into typed judgments and + probabilities that code can combine. Use when a feature needs programmable + common sense, when brainstorming what AI could make possible in an app, or + when an LLM prompt-and-parse step could become a structured decision. + Applications include routing, ranking, extraction, verification, and + interactive experiences; these are starting points, not the limits. + Read live docs and cookbooks to find useful patterns and discover new combinations. +--- + +# Build with TypeSafe + +TypeSafe makes units of AI intelligence usable like programming primitives: small +judgments you can compose into larger capabilities. Its **System One models** return +fast, focused judgments that software can consume directly. **Jev** is TypeSafe's +flagship and first System One model. It understands natural language and returns +typed answers and probabilities rather +than generating text or reasoning explanations. Code owns the workflow; the model +supplies programmable common sense where ordinary code needs semantic understanding. + +## Read the live docs + +**The live TypeSafe docs are the source of truth. Read them as part of the task.** +This skill gives direction; the docs carry current concepts, prompting guidance, +API contracts, SDK usage, models, limits, and worked examples. + +- Start with the [documentation index](https://docs.typesafe.ai/llms.txt) to discover + relevant pages and cookbooks. Use targeted reads rather than loading the entire site. +- Mintlify serves Markdown by appending `.md` to a page path, for example + [how to build with TypeSafe](https://docs.typesafe.ai/concepts/how-to-build-with-system-one.md). + Follow links from the index; convert extensionless documentation page links to + `.md` when useful. Resolve relative links against `https://docs.typesafe.ai`. +- Before writing an integration, read the current API or chosen SDK page and the + question guidance relevant to the design. For a new workflow, also inspect the + closest cookbook: it often shows a better decomposition than a generic classifier. +- If the index is unavailable, use the direct links below or the site's navigation. + If Markdown fetching fails, try the normal page. If live access is unavailable, + use available local docs or installed SDK types, state that limitation, and avoid + inventing version-dependent details. + +| Task | Start here; follow the relevant details | +| --- | --- | +| Understand the programming model | [System One](https://docs.typesafe.ai/concepts/system-one.md), [building guide](https://docs.typesafe.ai/concepts/how-to-build-with-system-one.md) | +| Explore what to build | [Use-case map](https://docs.typesafe.ai/concepts/use-case-map.md), then relevant cookbooks from the index | +| Prepare inputs and questions | [State](https://docs.typesafe.ai/concepts/state.md), [primitives](https://docs.typesafe.ai/primitives.md), then the chosen primitive's page | +| Decide how to handle uncertainty | [Confidence](https://docs.typesafe.ai/confidence.md) | +| Write API code | [HTTP API](https://docs.typesafe.ai/api.md), [Python SDK](https://docs.typesafe.ai/sdk/python.md), or [JavaScript SDK](https://docs.typesafe.ai/sdk/javascript.md) | +| Update an older integration | [Migration guide](https://docs.typesafe.ai/migrating-to-v1.md) and the installed SDK's current reference | + +## Find the useful shape + +Start from the behavior the user wants: what will the application show, select, +change, or hand off? Work backward to the judgments it needs. Keep known rules, +calculations, exact lookups, and execution in code. Preserve the user's chosen stack +and scope; add TypeSafe where semantic understanding helps. + +When brainstorming or choosing an architecture, consider more than classification. +The patterns below are starting points: combine primitives around the user's goal, +including ideas that do not fit an established recipe. + +- **Route and fill known arguments.** A request can select a handler and its typed + parameters. Ask useful branch-specific questions up front and consume only the + relevant answers. Explore [function calling](https://docs.typesafe.ai/cookbooks/function_calling.md) + and [speculative fan-out](https://docs.typesafe.ai/patterns/fan-out.md). +- **Select instead of generate.** Find candidate values or source spans in code, + use a judgment to select the intended one, then copy or normalize it. Code can + also assemble source text into a formatted document or reading guide. Explore + [value extraction](https://docs.typesafe.ai/cookbooks/pre_parsed_value_extraction_cookbook.md) + and [structure recovery](https://docs.typesafe.ai/cookbooks/autoformat.md). +- **Find and judge evidence.** Retrieve candidates, compare their relevance to a + query, and select useful context. Explore [reranking](https://docs.typesafe.ai/cookbooks/rerank_typesafe.md) + and [hierarchical classification](https://docs.typesafe.ai/cookbooks/hierarchical_classification.md). +- **Turn judgments into reusable data.** Score dimensions once, then let code or + user controls change weights, thresholds, rankings, and views. With labeled + outcomes, those signals can become classical ML features. Explore + [composite scoring](https://docs.typesafe.ai/patterns/composite-scoring.md) and + [feature discovery](https://docs.typesafe.ai/cookbooks/autoresearch_feature_discovery.md). +- **Verify and escalate.** Check specific claims or fields against their evidence; + send uncertain or failing cases to a person or reasoning model. Explore + [citation checks](https://docs.typesafe.ai/cookbooks/citation_check.md) and + [extraction cascades](https://docs.typesafe.ai/cookbooks/sde_cascade.md). +- **Respond to changing state.** Code can retain goals and observations while fresh + judgments guide the next bounded step. Keep inferred state distinct from observed + facts, and check freshness before applying a result to a changed situation. + +For open-ended requests, offer the few directions that best serve the user's goal +and recommend a starting point. For a concrete request, choose the relevant pattern +and build; a brainstorm is not a mandatory detour. + +## Design the judgments + +Choose by what the answer means, then read the relevant primitive page: + +| Need | Primitive | Important distinction | +| --- | --- | --- | +| One of a defined set | [Choice](https://docs.typesafe.ai/primitives/choice.md) | Picks one option; its distribution compares competing options | +| Whether a condition holds | [Noul](https://docs.typesafe.ai/primitives/noul.md) | Probability of yes; no separate confidence; use one per label when several may apply | +| Degree along a described dimension | [Score](https://docs.typesafe.ai/primitives/score.md) | Probability-weighted position on ordered levels; use comparable per-item Scores for graded ranking | + +Give each question enough relevant **state** to answer: source text, identities, +relationships, policies, and current facts. Prefer named JSON fields when context +has several parts. Put the judgment in **instructions** and define its possible +answers in **criteria**. Question IDs are for code and are not sent to the model; +include complete meaning in the question. Reference nested state with backticked +paths such as `ticket.messages[0].text`. + +Ask one narrow, coherent judgment per question. Split independently useful dimensions, +without destroying the relationship being judged. A bounded action selection or +contextual interpretation is valid; atomic does not mean literal fact extraction +or a one-sentence limit. Strings work for simple questions. Use structured objects +or arrays when definitions, contrasts, exclusions, or examples clarify instructions +or criteria. Score levels must describe concrete situations and stand on their own. + +Keep the needed answers available. Include a no-match outcome when nothing may fit; +use a separate presence judgment when it is independently useful. For source-value +selection, check candidate coverage: the model cannot choose an omitted value. + +## Compose and verify + +**Ask independent questions over the same state together**, including useful +speculative questions. They run in parallel and cannot see one another's answers. +State each speculative premise explicitly; code consumes the applicable answers. +A second request is warranted when an earlier answer is needed to fetch evidence, +construct new state, or determine the next options. Extra questions still use tokens; +measure actual request budgets, cost, and end-to-end latency. + +Use probabilities and confidence to guide behavior, with thresholds evaluated on +the user's data and consequences. Choice/Score confidence summarizes distribution +concentration, not overall workflow correctness or permission to act. A Noul near +0.5 means similar probability for yes and no, not medium intensity. Several +acceptable alternatives can also spread probability; low confidence need not +invalidate a harmless preference choice. Ignore uncertainty on unused branches. + +Keep policy explicit and raw judgments reusable. Weighted scores suit compensating +preferences; an “any serious violation” rule needs separate conditions. Changing a +weight or display filter need not rerun inference when evidence and question meanings +are unchanged. Typed output guarantees the interface, not truth. System One models +are trained for calibrated decisions; validate their performance in the target domain. + +Test representative cases and the resulting application behavior. For failures, +inspect the exact state, questions, candidates, answers, composition, and observed +outcome. Separate missing evidence, model errors, code errors, and service failures. +Treat cookbook thresholds and demo results as examples to evaluate, not universal +rules or permanent model limitations. Keep API credentials server-side in web apps. diff --git a/AGENTS.md b/AGENTS.md index d6846fb78..49e0ca392 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,6 +91,9 @@ Drivers are hot-editable and ship without a compilation step. See - Treat code, types, tests and driver metadata as the detailed documentation. - Add prose only for architecture, safety invariants or operator steps the code cannot explain. +- When a feature needs semantic judgment rather than generated text, use + [`.agents/skills/typesafe-ai`](.agents/skills/typesafe-ai/SKILL.md). Keep + Core validation and dispatch in code. ## Working alongside other people @@ -283,6 +286,7 @@ SDM630 as site meter. Its dashboard is `http://127.0.0.1:8762`; FTW is | Planner contract/fallback | [`go/internal/mpc`](go/internal/mpc) | | Optional optimizer | [`optimizer`](optimizer) | | Driver catalog | `DRIVER` blocks in `drivers/*.lua` | +| Semantic judgments (proposed Jev / TypeSafe) | [`.agents/skills/typesafe-ai`](.agents/skills/typesafe-ai/SKILL.md), [`go/internal/typesafe`](go/internal/typesafe), [`go/internal/assistant/judgments.go`](go/internal/assistant/judgments.go) | When behavior looks wrong, inspect the source and its tests before adding a new document. Keep [docs/](docs/) small and current. diff --git a/VISION.md b/VISION.md index eb93aa7ca..4333c8c55 100644 --- a/VISION.md +++ b/VISION.md @@ -163,6 +163,16 @@ authorized cloud agent is an endpoint that can read the data the user grants it; do not describe that access as blind. The box keeps operating when the agent, MCP service or network is unavailable. +Proposed, not shipped: TypeSafe's Jev model can turn a household sentence +and current site facts into typed judgments — what they want, which existing +Core operation that maps to, and how sure the judgment is. Code would then +call the schedule, Charge now, vehicle-SoC and Ask why paths Core already +has. Jev must not dispatch, set planner output on hardware, or replace +admission. The box stays in charge when the judgment service is gone. The +first intended use is Ask why routing (which tools, whether this is a +control request, whether to draft an issue), then household intents once +external write authority is defined. + This document adds no new protocol operation, credential or access grant. New shared names belong in the contract registry and must ship with their validation and matching clients. diff --git a/docs/architecture.md b/docs/architecture.md index d6046aa21..0d4b02f16 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -55,6 +55,13 @@ what its grant allows, and its access must be revocable. Protocol extensions require registry changes and paired implementation tests; this section does not introduce wire names or bypass existing admission rules. +Proposed, not shipped: a System One model (Jev) may classify a household +sentence and fill arguments for operations Core already admits. It is an +optional cloud judgment service, not a fourth module. When it is missing, +Ask why and the typed APIs keep working. Judgments never dispatch, never +apply planner output to hardware, and never bypass admission or freshness +checks. See [`go/internal/assistant/judgments.go`](../go/internal/assistant/judgments.go). + ## Power convention Above the driver boundary, positive power flows into the site and negative diff --git a/docs/roadmap.md b/docs/roadmap.md index d56f937a6..a98b78f5d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -121,7 +121,7 @@ change does not prove the currently pinned recovery bundle passes. | Daily charging | [The webapp panel](https://github.com/srcfl/ftw-webapp/blob/ff7af033fa3fcdeb38882e3ff365e8d6d7aba75a/src/views/EvPanel.svelte) already saves SoC on slider release, changes schedules without a Save button and supports Charge now. | [Now](https://github.com/srcfl/ftw-webapp/blob/ff7af033fa3fcdeb38882e3ff365e8d6d7aba75a/src/views/Now.svelte) normally opens that panel after a charger tap or notification link. Bring the relevant SoC action directly into the post-plug-in entry experience. Complete the goal → plan → delivered-energy flow on real chargers, including offline cars and restarts. | | Notifications | Core and the webapp implement subscription, charging connection/completion/interruption events and device alerts. See the [shared push catalogue](../contract/push-catalogue.yaml) and [rule defaults](../go/internal/notifications/service.go). | There is no dedicated predicted-missed-departure event in that catalogue. Add an actionable goal-risk notification and make activation clear during charging setup, with user consent. Verify delivery while the app is closed; an interrupted-session alert alone does not cover a future shortfall. | | Live trust and expert access | Flow exists. [LivePanel](https://github.com/srcfl/ftw-webapp/blob/ff7af033fa3fcdeb38882e3ff365e8d6d7aba75a/src/views/LivePanel.svelte) already puts a recent one-second trace behind each energy bubble and freezes it on silence. Core stores [structured v2 command results](../go/internal/state/driver_command_results.go), plan diagnostics and issued forecasts. | Join request, accepted intent, command response and measured effect in the normal experience and a structured analysis API, including legacy drivers and different sample cadences. Current result records and live watts are useful parts, not a complete proof of causality. Measure response time on a target box. | -| External control and agents | [Protocol command IDs and authorization leases](../go/internal/appproto/command.go), scoped operations, [bounded battery holds](../go/internal/api/api_battery_manual.go), schedule APIs and encrypted sessions exist. [HASS callbacks](../go/cmd/ftw/main.go) persist modes and grid targets. The built-in [Ask why tools](../go/internal/api/api_assistant_tools.go) are read-only. | Define renewable external control separately from durable goals. Losing HASS does not currently expire its saved mode. Existing authorization leases do not supply that policy. Build structured agent reads first, then permitted schedule/plan writes and a cloud MCP endpoint using the same Core checks. | +| External control and agents | [Protocol command IDs and authorization leases](../go/internal/appproto/command.go), scoped operations, [bounded battery holds](../go/internal/api/api_battery_manual.go), schedule APIs and encrypted sessions exist. [HASS callbacks](../go/cmd/ftw/main.go) persist modes and grid targets. The built-in [Ask why tools](../go/internal/api/api_assistant_tools.go) are read-only. | Define renewable external control separately from durable goals. Losing HASS does not currently expire its saved mode. Existing authorization leases do not supply that policy. Build structured agent reads first, then permitted schedule/plan writes and a cloud MCP endpoint using the same Core checks. Proposed: Jev as a judgment layer in front of Ask why, then mapping sentences onto those same Core operations — not a new control path. See [`go/internal/assistant/judgments.go`](../go/internal/assistant/judgments.go). | | Savings | [The API](../go/internal/api/api_savings.go) explicitly reports `site_total` against `no_pv_no_battery_vehicle_energy_at_daily_average`. Actual import cost and export revenue are available. | Make the scope clear on each surface that says “saved”. Then add and validate the same-hardware self-consumption counterfactual, including EV behaviour and stored-energy accounting. Do not relabel the current figure as FTW's incremental benefit. | | Heat and settings | Thermal contracts and an [explicitly opted-in solar feed](../go/cmd/ftw/solar_feed_send.go) already exist. The on-box [planner settings](../web/settings/tabs/planner.js) and webapp use different levels of technical language; the on-box minimum SoC still says “House reserve”. | Keep existing opt-ins explicit while phase one uses heat data for planning. Align basic controls around user goals and distinguish operating limits from forecast caution. Audit stored settings before removing or hiding them. Active tank/hot-water optimization remains a later bounded outcome. | diff --git a/go/internal/assistant/household.go b/go/internal/assistant/household.go new file mode 100644 index 000000000..6143900f3 --- /dev/null +++ b/go/internal/assistant/household.go @@ -0,0 +1,335 @@ +package assistant + +import ( + "fmt" + "regexp" + "strconv" + "strings" + + "github.com/srcfl/ftw/go/internal/appproto" + "github.com/srcfl/ftw/go/internal/typesafe" +) + +// Household mapping is proposed: Jev fills arguments for operations Core +// already admits. This file does not call those APIs and does not +// dispatch. Unavailable TypeSafe means the existing UI and typed routes +// keep working. + +const ( + houseActionConfidenceMin = 0.75 + houseUnsafeNoulMin = 0.6 + houseArgNoulMin = 0.55 + + houseActionExplain = "explain" + houseActionChargeNow = "charge_now" + houseActionSchedule = "set_schedule" + houseActionVehicleSoC = "set_vehicle_soc" + houseActionUnsupported = "unsupported" + + houseDaysWeekdays = "weekdays" + houseDaysEveryday = "everyday" + houseDaysWeekend = "weekend" + houseDaysUnstated = "not_stated" + houseUnstated = "not_stated" + + houseQAction = "action" + houseQUnsafe = "asks_to_bypass_safety" + houseQDurable = "is_standing_goal" + houseQSoC = "soc_pct" + houseQSoCStated = "soc_stated" + houseQDeadline = "deadline_local" + houseQDeadStat = "deadline_stated" + houseQDays = "days" + houseQLoadpoint = "loadpoint" +) + +// DaysWeekdays is ISO bits 0..4 (Mon–Fri), matching loadpoint.Schedule. +const DaysWeekdays uint8 = 0b0011111 + +// DaysWeekend is Saturday and Sunday (bits 5 and 6). +const DaysWeekend uint8 = 0b1100000 + +var ( + percentRe = regexp.MustCompile(`\b(\d{1,3})\s*%`) + clockRe = regexp.MustCompile(`\b([01]?\d|2[0-3])[:.]([0-5]\d)\b`) +) + +// HouseholdOutcome is what code should do with a composed intent. +type HouseholdOutcome string + +const ( + // HouseholdPropose is a typed intent Core can admit or reject. + HouseholdPropose HouseholdOutcome = "propose" + // HouseholdClarify is missing a closed-set argument the operation needs. + HouseholdClarify HouseholdOutcome = "clarify" + // HouseholdExplain should go to Ask why, not a write. + HouseholdExplain HouseholdOutcome = "explain" + // HouseholdRefuse is unsafe or unsupported. Do not call Core writes. + HouseholdRefuse HouseholdOutcome = "refuse" +) + +// HouseholdIntent is a proposed Core operation plus closed-set arguments. +// CoreOp is an existing protocol or HTTP name; empty means do not call Core. +type HouseholdIntent struct { + Outcome HouseholdOutcome + Action string + ActionConfidence float64 + CoreOp string + LoadpointID string + SoCPct *float64 + DeadlineLocal string + Recurring bool + Days uint8 + DaysKnown bool + Durable bool + Unsafe bool + UnsupportedReason string +} + +// HouseholdState adds pre-parsed percent and clock candidates so Jev +// selects a value that appeared in the utterance (or not_stated). +func HouseholdState(site SiteContext) map[string]any { + state := AskState(site) + state["percent_candidates"] = ExtractPercents(site.Utterance) + state["clock_candidates"] = ExtractClocks(site.Utterance) + return state +} + +// HouseholdQuestions fans out the function-calling pattern: pick one +// existing operation and fill only closed-set arguments. Numbers FTW +// cannot list (arbitrary watts) stay out of Jev and keep their Core defaults. +func HouseholdQuestions(site SiteContext) map[string]typesafe.Question { + socOpts := map[string]string{ + houseUnstated: "The utterance does not name a battery percentage.", + "50": "About half full.", + "60": "Sixty percent.", + "70": "Seventy percent.", + "80": "Eighty percent. The usual weekday ready-by target.", + "90": "Ninety percent.", + "100": "Full.", + } + for _, p := range ExtractPercents(site.Utterance) { + socOpts[strconv.Itoa(p)] = fmt.Sprintf("The utterance names %d percent.", p) + } + + deadOpts := map[string]string{ + houseUnstated: "No ready-by clock time is named.", + "06:00": "Six in the morning.", + "07:00": "Seven in the morning. The usual weekday example.", + "08:00": "Eight in the morning.", + "09:00": "Nine in the morning.", + "17:00": "Five in the afternoon.", + "18:00": "Six in the evening.", + } + for _, c := range ExtractClocks(site.Utterance) { + deadOpts[c] = "The utterance names " + c + " as a clock time." + } + + lpOpts := map[string]string{ + houseUnstated: "No specific charger is named, or the site has none.", + } + for _, lp := range site.Loadpoints { + id := strings.TrimSpace(lp.ID) + if id == "" || id == houseUnstated { + continue + } + label := strings.TrimSpace(lp.Name) + if label == "" { + label = id + } + lpOpts[id] = "The charger " + label + " (id " + id + ")." + } + + return map[string]typesafe.Question{ + houseQAction: typesafe.Choice( + "Which existing FTW operation does this household request map to?", + map[string]string{ + houseActionExplain: "They want to understand the site. Route to Ask why. Do not change goals.", + houseActionChargeNow: "Start charging the plugged-in car now. One-shot; Core already has Charge now (loadpoint.hold with a release SoC).", + houseActionSchedule: "A standing ready-by goal: be at a SoC by a local time on selected days. This is a durable schedule, not a control lease.", + houseActionVehicleSoC: "Correct the estimated car battery level. Not a command to charge.", + houseActionUnsupported: "Something FTW must not do from a sentence: power off an inverter, disable the site-meter watchdog, apply a planner slot directly to hardware, or otherwise bypass Core.", + }, + ), + houseQUnsafe: typesafe.Noul( + "Does the request ask to bypass FTW safety or to command hardware that Core does not expose as a household goal?", + "Disable the site-meter watchdog, send planner output to devices, turn off an inverter, ignore fuse limits, or similar.", + "A normal household goal or an explanation request.", + ), + houseQDurable: typesafe.Noul( + "Is this a standing household goal that should persist after the caller disconnects?", + "Every weekday, every morning, keep this until I change it.", + "One-shot: charge now, this trip, or a one-time correction.", + ), + houseQSoCStated: typesafe.Noul( + "Does the utterance name a battery percentage?", + "A percent is stated, including words like 80% or eighty percent.", + "No percentage is named.", + ), + houseQSoC: typesafe.Choice("Which battery percentage in `percent_candidates` or the usual targets did they mean?", socOpts), + houseQDeadStat: typesafe.Noul( + "Does the utterance name a ready-by clock time?", + "A time of day such as 07:00, 7:00, klockan 7.", + "No clock time is named.", + ), + houseQDeadline: typesafe.Choice("Which local clock time is the ready-by deadline?", deadOpts), + houseQDays: typesafe.Choice( + "Which days should a standing charging goal apply to?", + map[string]string{ + houseDaysWeekdays: "Monday to Friday for this household, not UTC.", + houseDaysEveryday: "Every day, including the weekend.", + houseDaysWeekend: "Saturday and Sunday only.", + houseDaysUnstated: "Days are not mentioned. Code may apply the weekday default only for a standing schedule.", + }, + ), + houseQLoadpoint: typesafe.Choice("Which configured charger in `loadpoints` is this about?", lpOpts), + } +} + +// ComposeHouseholdIntent reads speculative answers and keeps only the +// branch that won. It never returns a Core write for an unsafe request. +func ComposeHouseholdIntent(site SiteContext, res *typesafe.Result) HouseholdIntent { + out := HouseholdIntent{Outcome: HouseholdExplain, Action: houseActionExplain, CoreOp: ""} + if res == nil { + out.Outcome = HouseholdExplain + return out + } + if v, ok := res.NoulOf(houseQUnsafe); ok && v >= houseUnsafeNoulMin { + out.Unsafe = true + out.Action = houseActionUnsupported + out.Outcome = HouseholdRefuse + out.UnsupportedReason = "the request asks to bypass safety or command hardware FTW does not expose as a household goal" + return out + } + act, ok := res.ChoiceOf(houseQAction) + if !ok || act.Confidence < houseActionConfidenceMin { + out.Outcome = HouseholdExplain + out.fillArgs(site, res) + return out + } + out.Action = act.Choice + out.ActionConfidence = act.Confidence + if v, ok := res.NoulOf(houseQDurable); ok { + out.Durable = v >= houseArgNoulMin + out.Recurring = out.Durable + } + out.fillArgs(site, res) + + switch out.Action { + case houseActionUnsupported: + out.Outcome = HouseholdRefuse + out.UnsupportedReason = "no existing household operation matches this request" + return out + case houseActionExplain: + out.Outcome = HouseholdExplain + return out + case houseActionChargeNow: + out.CoreOp = appproto.OpLoadpointHold + if out.LoadpointID == "" { + out.Outcome = HouseholdClarify + return out + } + out.Outcome = HouseholdPropose + out.Recurring = false + out.Durable = false + return out + case houseActionVehicleSoC: + out.CoreOp = appproto.OpLoadpointSoCSet + if out.LoadpointID == "" || out.SoCPct == nil { + out.Outcome = HouseholdClarify + return out + } + out.Outcome = HouseholdPropose + out.Recurring = false + return out + case houseActionSchedule: + out.CoreOp = "loadpoint.schedule" + if out.LoadpointID == "" || out.SoCPct == nil || out.DeadlineLocal == "" { + out.Outcome = HouseholdClarify + return out + } + out.Recurring = true + out.Durable = true + if !out.DaysKnown { + // Unstated days on a standing goal follow the product example: + // 80% by 07:00 every weekday. A stated "every day" keeps Days==0. + out.Days = DaysWeekdays + } + out.Outcome = HouseholdPropose + return out + default: + out.Outcome = HouseholdExplain + return out + } +} + +func (out *HouseholdIntent) fillArgs(site SiteContext, res *typesafe.Result) { + if len(site.Loadpoints) == 1 { + out.LoadpointID = site.Loadpoints[0].ID + } else if lp, ok := res.ChoiceOf(houseQLoadpoint); ok && lp.Choice != "" && lp.Choice != houseUnstated { + out.LoadpointID = lp.Choice + } + if stated, ok := res.NoulOf(houseQSoCStated); ok && stated >= houseArgNoulMin { + if soc, ok := res.ChoiceOf(houseQSoC); ok && soc.Choice != houseUnstated { + if n, err := strconv.ParseFloat(soc.Choice, 64); err == nil && n >= 0 && n <= 100 { + out.SoCPct = &n + } + } + } + if stated, ok := res.NoulOf(houseQDeadStat); ok && stated >= houseArgNoulMin { + if d, ok := res.ChoiceOf(houseQDeadline); ok && d.Choice != houseUnstated { + out.DeadlineLocal = d.Choice + } + } + if days, ok := res.ChoiceOf(houseQDays); ok { + switch days.Choice { + case houseDaysWeekdays: + out.Days = DaysWeekdays + out.DaysKnown = true + case houseDaysEveryday: + out.Days = 0 + out.DaysKnown = true + case houseDaysWeekend: + out.Days = DaysWeekend + out.DaysKnown = true + } + } +} + +// ExtractPercents finds 0–100 percentages named in the utterance. +func ExtractPercents(utterance string) []int { + seen := map[int]bool{} + var out []int + for _, m := range percentRe.FindAllStringSubmatch(utterance, -1) { + n, err := strconv.Atoi(m[1]) + if err != nil || n > 100 { + continue + } + if seen[n] { + continue + } + seen[n] = true + out = append(out, n) + } + return out +} + +// ExtractClocks finds HH:MM / H.MM local times named in the utterance. +func ExtractClocks(utterance string) []string { + seen := map[string]bool{} + var out []string + for _, m := range clockRe.FindAllStringSubmatch(utterance, -1) { + h, _ := strconv.Atoi(m[1]) + min, _ := strconv.Atoi(m[2]) + if h > 23 || min > 59 { + continue + } + s := fmt.Sprintf("%02d:%02d", h, min) + if seen[s] { + continue + } + seen[s] = true + out = append(out, s) + } + return out +} diff --git a/go/internal/assistant/household_test.go b/go/internal/assistant/household_test.go new file mode 100644 index 000000000..05192f4e2 --- /dev/null +++ b/go/internal/assistant/household_test.go @@ -0,0 +1,194 @@ +package assistant + +import ( + "os" + "testing" + + "github.com/srcfl/ftw/go/internal/appproto" + "github.com/srcfl/ftw/go/internal/typesafe" +) + +func TestExtractPercentsAndClocks(t *testing.T) { + if got := ExtractPercents("Ladda till 80% sen 90%"); len(got) != 2 || got[0] != 80 || got[1] != 90 { + t.Fatalf("percents = %v", got) + } + if got := ExtractPercents("no percent here"); len(got) != 0 { + t.Fatalf("percents = %v", got) + } + if got := ExtractClocks("klar till 7:00 och sen 18.30"); len(got) != 2 || got[0] != "07:00" || got[1] != "18:30" { + t.Fatalf("clocks = %v", got) + } +} + +func TestHouseholdQuestionsIncludeExtractedCandidates(t *testing.T) { + qs := HouseholdQuestions(SiteContext{ + Utterance: "80% by 07:15 on the garage charger", + Loadpoints: []LoadpointRef{{ID: "garage", Name: "Garage"}}, + }) + soc := qs[houseQSoC].Criteria.(map[string]string) + if _, ok := soc["80"]; !ok { + t.Fatal("extracted 80% must be a Choice option") + } + dead := qs[houseQDeadline].Criteria.(map[string]string) + if _, ok := dead["07:15"]; !ok { + t.Fatal("extracted 07:15 must be a Choice option") + } + lp := qs[houseQLoadpoint].Criteria.(map[string]string) + if _, ok := lp["garage"]; !ok { + t.Fatal("configured loadpoint must be a Choice option") + } +} + +func TestComposeHouseholdChargeNowUsesExistingHold(t *testing.T) { + site := SiteContext{Loadpoints: []LoadpointRef{{ID: "garage", Name: "Garage"}}} + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + houseQAction: choice(houseActionChargeNow, 0.93), + houseQUnsafe: noul(0.04), + houseQDurable: noul(0.08), + houseQSoCStated: noul(0.9), + houseQSoC: choice("80", 0.88), + houseQDeadStat: noul(0.05), + houseQDeadline: choice(houseUnstated, 0.9), + houseQDays: choice(houseDaysUnstated, 0.8), + houseQLoadpoint: choice("garage", 0.7), + }} + got := ComposeHouseholdIntent(site, res) + if got.Outcome != HouseholdPropose || got.CoreOp != appproto.OpLoadpointHold { + t.Fatalf("got %+v", got) + } + if got.LoadpointID != "garage" || got.SoCPct == nil || *got.SoCPct != 80 || got.Recurring { + t.Fatalf("args %+v", got) + } +} + +func TestComposeHouseholdWeekdaySchedule(t *testing.T) { + site := SiteContext{Loadpoints: []LoadpointRef{{ID: "garage"}}} + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + houseQAction: choice(houseActionSchedule, 0.91), + houseQUnsafe: noul(0.03), + houseQDurable: noul(0.94), + houseQSoCStated: noul(0.96), + houseQSoC: choice("80", 0.9), + houseQDeadStat: noul(0.97), + houseQDeadline: choice("07:00", 0.92), + houseQDays: choice(houseDaysWeekdays, 0.9), + houseQLoadpoint: choice("garage", 0.8), + }} + got := ComposeHouseholdIntent(site, res) + if got.Outcome != HouseholdPropose || got.CoreOp != "loadpoint.schedule" { + t.Fatalf("got %+v", got) + } + if got.DeadlineLocal != "07:00" || got.Days != DaysWeekdays || !got.Durable || !got.Recurring { + t.Fatalf("schedule %+v", got) + } +} + +func TestComposeHouseholdEverydayDoesNotBecomeWeekdays(t *testing.T) { + site := SiteContext{Loadpoints: []LoadpointRef{{ID: "garage"}}} + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + houseQAction: choice(houseActionSchedule, 0.9), + houseQUnsafe: noul(0.02), + houseQDurable: noul(0.9), + houseQSoCStated: noul(0.9), + houseQSoC: choice("80", 0.9), + houseQDeadStat: noul(0.9), + houseQDeadline: choice("07:00", 0.9), + houseQDays: choice(houseDaysEveryday, 0.85), + houseQLoadpoint: choice("garage", 0.8), + }} + got := ComposeHouseholdIntent(site, res) + if !got.DaysKnown || got.Days != 0 { + t.Fatalf("everyday must stay a zero mask, got %+v", got) + } +} + +func TestComposeHouseholdUnstatedDaysDefaultWeekdays(t *testing.T) { + site := SiteContext{Loadpoints: []LoadpointRef{{ID: "garage"}}} + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + houseQAction: choice(houseActionSchedule, 0.9), + houseQUnsafe: noul(0.02), + houseQDurable: noul(0.9), + houseQSoCStated: noul(0.9), + houseQSoC: choice("80", 0.9), + houseQDeadStat: noul(0.9), + houseQDeadline: choice("07:00", 0.9), + houseQDays: choice(houseDaysUnstated, 0.8), + houseQLoadpoint: choice("garage", 0.8), + }} + got := ComposeHouseholdIntent(site, res) + if got.DaysKnown || got.Days != DaysWeekdays { + t.Fatalf("unstated standing goal should default to weekdays, got %+v", got) + } +} + +func TestComposeHouseholdRefusesSafetyBypass(t *testing.T) { + site := SiteContext{Loadpoints: []LoadpointRef{{ID: "garage"}}} + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + houseQAction: choice(houseActionChargeNow, 0.99), + houseQUnsafe: noul(0.88), + houseQDurable: noul(0.1), + houseQSoCStated: noul(0.1), + houseQSoC: choice(houseUnstated, 0.9), + houseQDeadStat: noul(0.1), + houseQDeadline: choice(houseUnstated, 0.9), + houseQDays: choice(houseDaysUnstated, 0.9), + houseQLoadpoint: choice("garage", 0.9), + }} + got := ComposeHouseholdIntent(site, res) + if got.Outcome != HouseholdRefuse || got.CoreOp != "" || !got.Unsafe { + t.Fatalf("unsafe must not propose a Core write: %+v", got) + } +} + +func TestComposeHouseholdClarifiesScheduleMissingDeadline(t *testing.T) { + site := SiteContext{Loadpoints: []LoadpointRef{{ID: "garage"}}} + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + houseQAction: choice(houseActionSchedule, 0.9), + houseQUnsafe: noul(0.02), + houseQDurable: noul(0.9), + houseQSoCStated: noul(0.9), + houseQSoC: choice("80", 0.9), + houseQDeadStat: noul(0.1), + houseQDeadline: choice(houseUnstated, 0.8), + houseQDays: choice(houseDaysWeekdays, 0.8), + houseQLoadpoint: choice("garage", 0.8), + }} + got := ComposeHouseholdIntent(site, res) + if got.Outcome != HouseholdClarify { + t.Fatalf("got %+v", got) + } +} + +func TestComposeHouseholdLowConfidenceExplains(t *testing.T) { + got := ComposeHouseholdIntent(SiteContext{}, &typesafe.Result{Answers: map[string]typesafe.Answer{ + houseQAction: choice(houseActionChargeNow, 0.4), + houseQUnsafe: noul(0.1), + }}) + if got.Outcome != HouseholdExplain || got.CoreOp != "" { + t.Fatalf("got %+v", got) + } +} + +func TestLiveJevHouseholdPhrases(t *testing.T) { + key := os.Getenv("TYPESAFE_API_KEY") + if key == "" || os.Getenv("TYPESAFE_LIVE") != "1" { + t.Skip("set TYPESAFE_API_KEY and TYPESAFE_LIVE=1 to call Jev") + } + site := SiteContext{ + Utterance: "Ladda bilen till 80% till klockan 7 varje vardag", + Drivers: []string{"sungrow", "sdm630"}, + Loadpoints: []LoadpointRef{{ID: "garage", Name: "Garage"}}, + Snapshot: "mode=automatic sungrow=ok garage plugged in estimated SoC 41%", + } + cli := &typesafe.Client{APIKey: key} + res, err := cli.Evaluate(t.Context(), HouseholdState(site), HouseholdQuestions(site)) + if err != nil { + t.Fatal(err) + } + got := ComposeHouseholdIntent(site, res) + t.Logf("live household: action=%s outcome=%s op=%s soc=%v deadline=%s days=%d conf=%.2f", + got.Action, got.Outcome, got.CoreOp, got.SoCPct, got.DeadlineLocal, got.Days, got.ActionConfidence) + if got.Unsafe { + t.Fatal("weekday ready-by must not be classified as a safety bypass") + } +} diff --git a/go/internal/assistant/judgments.go b/go/internal/assistant/judgments.go new file mode 100644 index 000000000..eb8d28036 --- /dev/null +++ b/go/internal/assistant/judgments.go @@ -0,0 +1,249 @@ +package assistant + +import ( + "strings" + + "github.com/srcfl/ftw/go/internal/typesafe" +) + +// Thresholds are starting points to evaluate on real Ask why questions. +// They are not TypeSafe cookbook defaults and they are not permission +// to act on hardware. +const ( + askChoiceConfidenceMin = 0.5 + askToolNoulMin = 0.55 + askControlNoulMin = 0.7 + askBugNoulMin = 0.8 +) + +// AskHandler is the code path Ask why should take after Jev answers. +// None of these dispatch; Ask why stays read-only. +type AskHandler string + +const ( + // AskFullLLM is today's path: snapshot plus every tool, then the + // OpenRouter writer. + AskFullLLM AskHandler = "full_llm" + // AskToolsLLM calls only the tools Jev judged relevant, then the writer. + AskToolsLLM AskHandler = "tools_llm" + // AskRefuseControl tells the operator Ask why cannot change the site. + // A later household-intent mapper may propose an existing Core operation. + AskRefuseControl AskHandler = "refuse_control" + // AskSkipLLM is greeting or off-topic; no investigation. + AskSkipLLM AskHandler = "skip_llm" +) + +const ( + askTopicExplainPlan = "explain_plan" + askTopicCharging = "charging" + askTopicDriver = "driver" + askTopicSavings = "savings" + askTopicHowTo = "how_to" + askTopicReportBug = "report_bug" + askTopicChat = "conversation" + askTopicControl = "change_control" + askTopicOther = "other" + + askQTopic = "topic" + askQPlan = "needs_plan_now" + askQHealth = "needs_driver_health" + askQLogs = "needs_recent_logs" + askQReport = "needs_support_report" + askQControl = "is_control_request" + askQBug = "looks_like_ftw_bug" + askQUrgency = "urgency" + askQDriver = "implicated_driver" +) + +// SiteContext is named state for Jev: the utterance plus facts the box +// already knows. Drivers and loadpoints must be the live configured set; +// Jev cannot choose an omitted identity. +type SiteContext struct { + Utterance string `json:"utterance"` + Trigger string `json:"trigger,omitempty"` + Drivers []string `json:"drivers"` + Loadpoints []LoadpointRef `json:"loadpoints"` + Snapshot string `json:"snapshot,omitempty"` +} + +// LoadpointRef is a charger the household can name. +type LoadpointRef struct { + ID string `json:"id"` + Name string `json:"name,omitempty"` +} + +// AskRoute is the composed Ask why decision. Tools is a subset of the +// read-only allow-list. FileIssue is a hint for the writer, not a post. +type AskRoute struct { + Handler AskHandler + Topic string + TopicConfidence float64 + Tools []string + FileIssue bool + ControlRequest bool + Urgency float64 + Uncertain bool + Driver string +} + +// AskState is the JSON object sent as TypeSafe state. +func AskState(site SiteContext) map[string]any { + drivers := site.Drivers + if drivers == nil { + drivers = []string{} + } + lps := site.Loadpoints + if lps == nil { + lps = []LoadpointRef{} + } + return map[string]any{ + "utterance": strings.TrimSpace(site.Utterance), + "trigger": strings.TrimSpace(site.Trigger), + "drivers": drivers, + "loadpoints": lps, + "snapshot": strings.TrimSpace(site.Snapshot), + "policy": map[string]string{ + "ask_why": "read-only helper; it cannot command hardware or change config", + "dispatch": "only Core may dispatch, and only after admission and freshness checks", + }, + } +} + +// AskQuestions is one speculative fan-out: topic, tool needs, control +// vs explanation, and whether this looks like an FTW bug. Independent +// questions share the same state; code consumes only the relevant answers. +func AskQuestions(site SiteContext) map[string]typesafe.Question { + driverOpts := map[string]string{ + "none": "No specific configured driver is implicated, or the utterance is not about a device fault.", + } + for _, name := range site.Drivers { + name = strings.TrimSpace(name) + if name == "" || name == "none" { + continue + } + driverOpts[name] = "The utterance is about the configured driver named " + name + "." + } + return map[string]typesafe.Question{ + askQTopic: typesafe.Choice( + "What is the person trying to do with this FTW home energy box?", + map[string]string{ + askTopicExplainPlan: "Understand the current energy plan, battery charge/discharge, or why the box is idle or importing.", + askTopicCharging: "Car charging: plugged in, SoC, ready-by time, Charge now, or whether the car will be ready.", + askTopicDriver: "A device, inverter, meter or charger looks broken, offline, stale or in fault.", + askTopicSavings: "Cost, prices, export, or whether FTW is saving money.", + askTopicHowTo: "How to use a setting, the UI, or a feature. Not a live diagnosis.", + askTopicReportBug: "They want to file a bug or they claim FTW itself is wrong.", + askTopicChat: "Greeting, thanks, or something unrelated to this house's energy system.", + askTopicControl: "They want the box to change power, mode, charging or hardware right now, not merely explain it.", + askTopicOther: "None of the other options fit.", + }, + ), + askQPlan: typesafe.Noul( + "Does answering require the current plan slot and the hours-ahead battery intent?", + "The question is about what the planner is doing now or later today.", + "The question can be answered without the plan.", + ), + askQHealth: typesafe.Noul( + "Does answering require driver health (online/offline, last success, faults)?", + "A device, poll or fault is in question.", + "Driver health would not change the answer.", + ), + askQLogs: typesafe.Noul( + "Does answering require recent warning or error logs?", + "They are diagnosing a failure or unexpected behaviour.", + "Logs are not needed.", + ), + askQReport: typesafe.Noul( + "Is the compact snapshot in `snapshot` insufficient, so the full local help report is needed?", + "The snapshot is missing the evidence this question needs.", + "The snapshot, or a single targeted tool, is enough.", + ), + askQControl: typesafe.Noul( + "Is the person asking FTW to change equipment behaviour, not just explain it?", + "Charge now, stop charging, set a schedule or SoC, change mode, turn equipment off, or otherwise command the site.", + "They want an explanation, a diagnosis, or how-to help.", + ), + askQBug: typesafe.Noul( + "Does this look like a defect in FTW or a bundled driver, rather than expected control or a site/config issue?", + "FTW or a driver is misbehaving relative to the evidence.", + "Expected control, operator misunderstanding, or a site/config problem. Leave issue fields empty.", + ), + askQUrgency: typesafe.Score( + "How time-sensitive is this for the household?", + []string{ + "Routine curiosity, a past event, or no deadline.", + "Something is wrong or at risk later today: a charging deadline, an offline device, a plan that will miss a goal.", + "Immediate physical or safety language: fuse, fire, overheating, stuck dispatch, flooding power.", + }, + ), + askQDriver: typesafe.Choice( + "Which configured driver is implicated in `drivers`, if any?", + driverOpts, + ), + } +} + +// ComposeAskRoute turns Jev's answers into an Ask why code path. +// Missing or low-confidence topic falls back to today's full LLM path. +func ComposeAskRoute(res *typesafe.Result) AskRoute { + out := AskRoute{Handler: AskFullLLM, Uncertain: true} + if res == nil { + return out + } + if topic, ok := res.ChoiceOf(askQTopic); ok { + out.Topic = topic.Choice + out.TopicConfidence = topic.Confidence + out.Uncertain = topic.Confidence < askChoiceConfidenceMin || topic.Choice == "" + } + if v, ok := res.NoulOf(askQControl); ok { + out.ControlRequest = v >= askControlNoulMin + } + if v, ok := res.NoulOf(askQBug); ok { + // Expected plan questions must not become GitHub issues just + // because the operator is surprised by cheap-hour idle. + out.FileIssue = v >= askBugNoulMin && out.Topic != askTopicExplainPlan + } + if urg, ok := res.ScoreOf(askQUrgency); ok { + out.Urgency = urg.Score + } + if drv, ok := res.ChoiceOf(askQDriver); ok && drv.Choice != "" && drv.Choice != "none" { + out.Driver = drv.Choice + } + + if out.ControlRequest { + out.Handler = AskRefuseControl + return out + } + if out.Uncertain { + out.Handler = AskFullLLM + out.Tools = allAskTools() + return out + } + if out.Topic == askTopicChat { + out.Handler = AskSkipLLM + return out + } + + out.Tools = selectAskTools(res) + out.Handler = AskToolsLLM + return out +} + +func selectAskTools(res *typesafe.Result) []string { + var tools []string + add := func(noulID, tool string) { + v, ok := res.NoulOf(noulID) + if ok && v >= askToolNoulMin { + tools = append(tools, tool) + } + } + add(askQReport, ToolSupportReport) + add(askQHealth, ToolDriverHealth) + add(askQLogs, ToolRecentLogs) + add(askQPlan, ToolPlanNow) + return tools +} + +func allAskTools() []string { + return []string{ToolSupportReport, ToolDriverHealth, ToolRecentLogs, ToolPlanNow, ToolVersion} +} diff --git a/go/internal/assistant/judgments_test.go b/go/internal/assistant/judgments_test.go new file mode 100644 index 000000000..1a7a24714 --- /dev/null +++ b/go/internal/assistant/judgments_test.go @@ -0,0 +1,153 @@ +package assistant + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/srcfl/ftw/go/internal/typesafe" +) + +func TestAskQuestionsCoverFanOut(t *testing.T) { + qs := AskQuestions(SiteContext{Drivers: []string{"sungrow", "sdm630"}}) + for _, id := range []string{askQTopic, askQPlan, askQHealth, askQLogs, askQReport, askQControl, askQBug, askQUrgency, askQDriver} { + if _, ok := qs[id]; !ok { + t.Fatalf("missing question %s", id) + } + } + drv, ok := qs[askQDriver].Criteria.(map[string]string) + if !ok { + t.Fatalf("driver criteria type %T", qs[askQDriver].Criteria) + } + if _, ok := drv["sungrow"]; !ok { + t.Fatal("configured driver must be a Choice option") + } + if _, ok := drv["none"]; !ok { + t.Fatal("Choice needs a no-match option") + } +} + +func TestAskQuestionsJSONForAPI(t *testing.T) { + qs := AskQuestions(SiteContext{Drivers: []string{"sungrow"}}) + raw, err := json.Marshal(qs) + if err != nil { + t.Fatal(err) + } + s := string(raw) + if !strings.Contains(s, `"type":"choice"`) || !strings.Contains(s, `"type":"noul"`) || !strings.Contains(s, `"type":"score"`) { + t.Fatalf("questions JSON missing primitive types: %s", s) + } +} + +func TestAskStateKeepsNamedFields(t *testing.T) { + raw, err := json.Marshal(AskState(SiteContext{ + Utterance: "why is the battery idle?", + Trigger: "the operator is asking why the current plan looks like this", + Drivers: []string{"sungrow"}, + })) + if err != nil { + t.Fatal(err) + } + s := string(raw) + for _, want := range []string{`"utterance"`, `"drivers"`, `"policy"`, `"ask_why"`} { + if !strings.Contains(s, want) { + t.Fatalf("state missing %s: %s", want, s) + } + } +} + +func TestComposeAskRouteSelectsToolsAndSkipsIssueOnPlan(t *testing.T) { + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + askQTopic: choice("explain_plan", 0.92), + askQPlan: noul(0.88), + askQHealth: noul(0.1), + askQLogs: noul(0.2), + askQReport: noul(0.12), + askQControl: noul(0.05), + askQBug: noul(0.91), + askQUrgency: score(0.2), + askQDriver: choice("none", 0.8), + }} + got := ComposeAskRoute(res) + if got.Handler != AskToolsLLM { + t.Fatalf("handler = %s", got.Handler) + } + if got.FileIssue { + t.Fatal("expected-plan questions must not file an issue from a high bug noul") + } + if strings.Join(got.Tools, ",") != ToolPlanNow { + t.Fatalf("tools = %v", got.Tools) + } +} + +func TestComposeAskRouteRefusesControlWithoutDispatch(t *testing.T) { + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + askQTopic: choice("change_control", 0.9), + askQControl: noul(0.95), + askQPlan: noul(0.8), + askQHealth: noul(0.1), + askQLogs: noul(0.1), + askQReport: noul(0.1), + askQBug: noul(0.1), + askQUrgency: score(1.1), + askQDriver: choice("none", 0.7), + }} + got := ComposeAskRoute(res) + if got.Handler != AskRefuseControl || !got.ControlRequest { + t.Fatalf("got %+v", got) + } + if len(got.Tools) != 0 { + t.Fatalf("refuse path should not fetch tools: %v", got.Tools) + } +} + +func TestComposeAskRouteFallsBackWhenUncertain(t *testing.T) { + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + askQTopic: choice("other", 0.31), + askQControl: noul(0.2), + askQPlan: noul(0.9), + askQHealth: noul(0.9), + askQLogs: noul(0.9), + askQReport: noul(0.9), + askQBug: noul(0.2), + askQUrgency: score(0.4), + askQDriver: choice("none", 0.4), + }} + got := ComposeAskRoute(res) + if got.Handler != AskFullLLM || !got.Uncertain { + t.Fatalf("got %+v", got) + } + if len(got.Tools) != 5 { + t.Fatalf("uncertain path keeps every tool, got %v", got.Tools) + } +} + +func TestComposeAskRouteSkipsLLMForChat(t *testing.T) { + res := &typesafe.Result{Answers: map[string]typesafe.Answer{ + askQTopic: choice("conversation", 0.88), + askQControl: noul(0.02), + askQPlan: noul(0.01), + askQHealth: noul(0.01), + askQLogs: noul(0.01), + askQReport: noul(0.01), + askQBug: noul(0.01), + askQUrgency: score(0), + askQDriver: choice("none", 0.9), + }} + got := ComposeAskRoute(res) + if got.Handler != AskSkipLLM { + t.Fatalf("handler = %s", got.Handler) + } +} + +func noul(v float64) typesafe.Answer { + return typesafe.Answer{Type: "noul", Noul: v} +} + +func choice(c string, conf float64) typesafe.Answer { + return typesafe.Answer{Type: "choice", Choice: c, Confidence: conf} +} + +func score(v float64) typesafe.Answer { + return typesafe.Answer{Type: "score", Score: v, Confidence: 0.7} +} diff --git a/go/internal/typesafe/client.go b/go/internal/typesafe/client.go new file mode 100644 index 000000000..eeacaac58 --- /dev/null +++ b/go/internal/typesafe/client.go @@ -0,0 +1,248 @@ +// Package typesafe calls TypeSafe's System One HTTP API. +// +// Jev returns typed judgments and probabilities. Callers own workflow, +// safety and dispatch. This package does not talk to hardware. +package typesafe + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +const ( + DefaultBaseURL = "https://api.typesafe.ai" + DefaultModel = "jev-latest" + // Timeout covers a slow or retried System One call. Typical answers + // are far faster; this is a ceiling, not a target. + Timeout = 15 * time.Second + maxBody = 1 << 20 + maxAttempts = 3 +) + +// Client posts state and questions to POST /v1/systemone. +type Client struct { + APIKey string + Model string + BaseURL string + HTTP *http.Client +} + +// Request is one System One evaluation. +type Request struct { + State any `json:"state"` + Model string `json:"model"` + Questions map[string]Question `json:"questions"` +} + +// Question is one Choice, Noul or Score. Instructions and criteria may +// be strings or JSON structure; the live TypeSafe docs are the contract. +type Question struct { + Type string `json:"type"` + Instructions any `json:"instructions"` + Criteria any `json:"criteria,omitempty"` +} + +// Result is the typed answers for one request, keyed by the same ids. +type Result struct { + Model string `json:"model"` + Answers map[string]Answer `json:"answers"` + Usage Usage `json:"usage"` +} + +// Answer is one Noul, Choice or Score. Noul has no separate confidence; +// a value near 0.5 means similar probability for yes and no. +type Answer struct { + Type string `json:"type"` + Noul float64 `json:"noul"` + Choice string `json:"choice"` + Score float64 `json:"score"` + Confidence float64 `json:"confidence"` + Probabilities map[string]float64 `json:"probabilities"` + Legend map[string]string `json:"legend"` +} + +// Usage is token accounting from the API. Output tokens are free on Jev. +type Usage struct { + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` +} + +// APIError is an outbound failure the caller can map to a status code. +type APIError struct { + Status int + Msg string +} + +func (e *APIError) Error() string { return e.Msg } + +// Noul builds a yes/no question. Empty true/false descriptions omit criteria. +func Noul(instructions string, yes, no string) Question { + q := Question{Type: "noul", Instructions: instructions} + if strings.TrimSpace(yes) != "" || strings.TrimSpace(no) != "" { + q.Criteria = map[string]string{"true": yes, "false": no} + } + return q +} + +// Choice builds a one-of-a-set question. Option keys are the values code +// will receive; descriptions are the rubric, not display copy. +func Choice(instructions string, options map[string]string) Question { + return Question{Type: "choice", Instructions: instructions, Criteria: options} +} + +// Score builds an ordered rubric. Levels must stand on their own; the +// weighted score can land between them. +func Score(instructions string, levels []string) Question { + return Question{Type: "score", Instructions: instructions, Criteria: levels} +} + +// Evaluate asks every question over the same state in one call. +func (c *Client) Evaluate(ctx context.Context, state any, questions map[string]Question) (*Result, error) { + if c == nil || strings.TrimSpace(c.APIKey) == "" { + return nil, &APIError{Status: http.StatusConflict, Msg: "TypeSafe API key is missing"} + } + if len(questions) == 0 { + return nil, &APIError{Status: http.StatusBadRequest, Msg: "TypeSafe request has no questions"} + } + model := strings.TrimSpace(c.Model) + if model == "" { + model = DefaultModel + } + endpoint, err := c.endpoint() + if err != nil { + return nil, err + } + body, err := json.Marshal(Request{State: state, Model: model, Questions: questions}) + if err != nil { + return nil, &APIError{Status: http.StatusBadRequest, Msg: "TypeSafe request is not JSON"} + } + httpClient := c.HTTP + if httpClient == nil { + httpClient = &http.Client{Timeout: Timeout} + } + + var last error + for attempt := 1; attempt <= maxAttempts; attempt++ { + result, retry, err := c.post(ctx, httpClient, endpoint, body) + if err == nil { + return result, nil + } + last = err + if !retry || attempt == maxAttempts { + return nil, err + } + delay := time.Duration(1<= 500: + return nil, true, &APIError{Status: http.StatusBadGateway, Msg: "TypeSafe is unavailable"} + case resp.StatusCode >= 400: + return nil, false, &APIError{Status: http.StatusBadGateway, Msg: "TypeSafe request failed"} + } + + var out Result + if err := json.Unmarshal(raw, &out); err != nil { + return nil, false, &APIError{Status: http.StatusBadGateway, Msg: "TypeSafe returned unreadable JSON"} + } + if out.Answers == nil { + out.Answers = map[string]Answer{} + } + return &out, false, nil +} + +// NoulOf returns the yes-probability for id. +func (r *Result) NoulOf(id string) (float64, bool) { + if r == nil { + return 0, false + } + a, ok := r.Answers[id] + if !ok || a.Type != "noul" { + return 0, false + } + return a.Noul, true +} + +// ChoiceOf returns the winning option for id. +func (r *Result) ChoiceOf(id string) (Answer, bool) { + if r == nil { + return Answer{}, false + } + a, ok := r.Answers[id] + if !ok || a.Type != "choice" { + return Answer{}, false + } + return a, true +} + +// ScoreOf returns the weighted score for id. +func (r *Result) ScoreOf(id string) (Answer, bool) { + if r == nil { + return Answer{}, false + } + a, ok := r.Answers[id] + if !ok || a.Type != "score" { + return Answer{}, false + } + return a, true +} + +// Missing reports question ids that have no matching answer. +func (r *Result) Missing(ids ...string) []string { + var out []string + if r == nil { + return append([]string{}, ids...) + } + for _, id := range ids { + if _, ok := r.Answers[id]; !ok { + out = append(out, id) + } + } + return out +} diff --git a/go/internal/typesafe/client_test.go b/go/internal/typesafe/client_test.go new file mode 100644 index 000000000..311f655c0 --- /dev/null +++ b/go/internal/typesafe/client_test.go @@ -0,0 +1,134 @@ +package typesafe + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +func TestEvaluatePostsStateAndQuestions(t *testing.T) { + var gotAuth, gotPath, gotBody string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotAuth = r.Header.Get("Authorization") + raw, _ := io.ReadAll(r.Body) + gotBody = string(raw) + _ = json.NewEncoder(w).Encode(map[string]any{ + "model": "jev-1.13.0", + "answers": map[string]any{ + "is_urgent": map[string]any{"type": "noul", "noul": 0.91}, + "topic": map[string]any{ + "type": "choice", + "choice": "charging", + "confidence": 0.84, + "probabilities": map[string]any{"charging": 0.84, "plan": 0.16}, + }, + }, + "usage": map[string]any{"input_tokens": 120, "output_tokens": 8}, + }) + })) + defer srv.Close() + + cli := &Client{APIKey: "ts-test", BaseURL: srv.URL, HTTP: srv.Client()} + got, err := cli.Evaluate(context.Background(), map[string]any{ + "utterance": "charge the car to 80%", + }, map[string]Question{ + "is_urgent": Noul("Does this convey urgency?", "Time-sensitive for the household today", "No deadline or outage"), + "topic": Choice("What is this about?", map[string]string{ + "charging": "Car charging", + "plan": "The energy plan", + }), + }) + if err != nil { + t.Fatal(err) + } + if gotPath != "/v1/systemone" { + t.Fatalf("path = %s", gotPath) + } + if gotAuth != "Bearer ts-test" { + t.Fatalf("Authorization = %q", gotAuth) + } + if !strings.Contains(gotBody, `"jev-latest"`) { + t.Fatalf("default model missing: %s", gotBody) + } + if !strings.Contains(gotBody, `"charge the car to 80%"`) || !strings.Contains(gotBody, `"is_urgent"`) { + t.Fatalf("state or questions missing: %s", gotBody) + } + noul, ok := got.NoulOf("is_urgent") + if !ok || noul != 0.91 { + t.Fatalf("noul = %v ok=%v", noul, ok) + } + ch, ok := got.ChoiceOf("topic") + if !ok || ch.Choice != "charging" || ch.Confidence != 0.84 { + t.Fatalf("choice = %+v ok=%v", ch, ok) + } + if got.Model != "jev-1.13.0" { + t.Fatalf("resolved model = %q", got.Model) + } +} + +func TestEvaluateRetriesOverloadedThenSucceeds(t *testing.T) { + var n atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if n.Add(1) < 3 { + w.WriteHeader(529) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "model": "jev-1.13.0", + "answers": map[string]any{"ok": map[string]any{"type": "noul", "noul": 1}}, + }) + })) + defer srv.Close() + + cli := &Client{APIKey: "ts-test", BaseURL: srv.URL, HTTP: srv.Client()} + got, err := cli.Evaluate(context.Background(), "ping", map[string]Question{ + "ok": Noul("Is this a ping?", "", ""), + }) + if err != nil { + t.Fatal(err) + } + if n.Load() != 3 { + t.Fatalf("attempts = %d", n.Load()) + } + if v, ok := got.NoulOf("ok"); !ok || v != 1 { + t.Fatalf("noul = %v ok=%v", v, ok) + } +} + +func TestEvaluateRejectsMissingKey(t *testing.T) { + _, err := (*Client)(nil).Evaluate(context.Background(), "x", map[string]Question{"a": Noul("y", "", "")}) + if err == nil { + t.Fatal("expected error") + } + apiErr, ok := err.(*APIError) + if !ok || apiErr.Status != http.StatusConflict { + t.Fatalf("err = %v", err) + } +} + +func TestEvaluateMapsUnauthorized(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + })) + defer srv.Close() + cli := &Client{APIKey: "bad", BaseURL: srv.URL, HTTP: srv.Client()} + _, err := cli.Evaluate(context.Background(), "x", map[string]Question{"a": Noul("y", "", "")}) + apiErr, ok := err.(*APIError) + if !ok || apiErr.Status != http.StatusUnauthorized { + t.Fatalf("err = %v", err) + } +} + +func TestMissingListsAbsentIds(t *testing.T) { + r := &Result{Answers: map[string]Answer{"a": {Type: "noul", Noul: 0.2}}} + got := r.Missing("a", "b", "c") + if strings.Join(got, ",") != "b,c" { + t.Fatalf("missing = %v", got) + } +} diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 000000000..734aa12e2 --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,11 @@ +{ + "version": 1, + "skills": { + "typesafe-ai": { + "source": "typesafe-ai/skills", + "sourceType": "github", + "skillPath": "skills/typesafe-ai/SKILL.md", + "computedHash": "9cd84c5e535dec8dec59917c110f9c00b4a61faadb86b432ec7e41051170af12" + } + } +}