text
stringlengths
3
8.33k
repo
stringclasses
52 values
path
stringlengths
6
141
language
stringclasses
35 values
sha
stringlengths
64
64
chunk_index
int32
0
273
n_tokens
int32
1
896
3.5-turbo", "name": "Gpt 3.5 Turbo", "provider": "openai", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdocs%2Fai-gateway%2Flogos%2Fopenai.png&w=64&q=75", "description": "" }...
hacknation
www/lib/ai/models.ts
TypeScript
024e0f0f335074fb9395d832ef85f3a877c3bd366e81051ec7ae17fe954ccaad
19
896
w=64&q=75", "description": "" }, { "id": "arcee-ai/trinity-mini", "name": "Trinity Mini", "provider": "arcee-ai", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdoc...
hacknation
www/lib/ai/models.ts
TypeScript
461cf0cb4d4a0a0d3987631c56d2494b49504d0f418571ad9105b023e62cccce
20
896
%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdocs%2Fai-gateway%2Flogos%2Fzai.png&w=64&q=75", "description": "" }, { "id": "alibaba/qwen-3-30b", "name": "Qwen 3 30b", "provider": "alibaba", "image": "https://vercel.com/vc-ap-vercel-marketing/...
hacknation
www/lib/ai/models.ts
TypeScript
8f4da5a095f8c728759f723bf7ecbc6b0bd50efbd290c99051fb7111197f70af
21
896
ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdocs%2Fai-gateway%2Flogos%2Famazon%20bedrock.png&w=64&q=75", "description": "" }, { "id": "nvidia/nemotron-3-nano-30b-a3b", "name": "Nemotron 3 Nano 30b A3b", ...
hacknation
www/lib/ai/models.ts
TypeScript
c6b374484b66121424c98b6c90f92432ee0a15602777c54ba653e84f78fd36d6
22
896
Qwen3 Max Thinking", "provider": "alibaba", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdocs%2Fai-gateway%2Flogos%2Falibaba%20cloud.png&w=64&q=75", "description": "" }, { ...
hacknation
www/lib/ai/models.ts
TypeScript
ca56483dbf10bf1f96ec80a096d0ec145ee2d36def519254ff04023e2f1f73be
23
896
75", "description": "" }, { "id": "mistral/magistral-medium", "name": "Magistral Medium", "provider": "mistral", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdocs...
hacknation
www/lib/ai/models.ts
TypeScript
9d7ce49c21560e859ed9abb1130469dfdada004c69fa0f0908022386ff48f078
24
896
%2Fai-gateway%2Flogos%2Falibaba%20cloud.png&w=64&q=75", "description": "" }, { "id": "mistral/mixtral-8x22b-instruct", "name": "Mixtral 8x22b Instruct", "provider": "mistral", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4z...
hacknation
www/lib/ai/models.ts
TypeScript
3594b5ec75f96869747339d469adfe1ba15c093f47c08a9eb3ff5564df980986
25
896
-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdocs%2Fai-gateway%2Flogos%2Fblackforestlabs.png&w=64&q=75", "description": "" }, { "id": "openai/gpt-3.5-turbo-instruct", "name": "Gpt 3.5 Turbo Instruct", "provider"...
hacknation
www/lib/ai/models.ts
TypeScript
c6c59adaa4f55432b222af81185365480ae0a3027ca30cbd3a22d82a0311908c
26
896
Mercury Coder Small", "provider": "inception", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fstatic%2Fdocs%2Fai-gateway%2Flogos%2Finception.png&w=64&q=75", "description": "" }, { "...
hacknation
www/lib/ai/models.ts
TypeScript
39ca1dff2adf1c7cb9842b14a4b53028a690587a4552277d182a0224d7f093aa
27
896
=64&q=75", "description": "" }, { "id": "perplexity/sonar-reasoning", "name": "Sonar Reasoning", "provider": "perplexity", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public.blob.vercel-storage.com%2Fdocs-assets%2Fsta...
hacknation
www/lib/ai/models.ts
TypeScript
46c06b63a40adb4af255689e54715f719c5e87504a6c8f3d75bfcde026cfd6fa
28
896
Fstatic%2Fdocs%2Fai-gateway%2Flogos%2Fvoyage.png&w=64&q=75", "description": "" }, { "id": "voyage/voyage-finance-2", "name": "Voyage Finance 2", "provider": "voyage", "image": "https://vercel.com/vc-ap-vercel-marketing/_next/image?url=https%3A%2F%2F7nyt0uhk7sse4zvn.public...
hacknation
www/lib/ai/models.ts
TypeScript
c0deb63c5159c0ab8ba09e45bf70271f7808a66920ff12607d116966dceff172
29
545
import type { Geo } from "@vercel/functions"; import type { ArtifactKind } from "@/components/artifact"; export const artifactsPrompt = ` ## Artifacts (Right Panel) The right panel displays both interactive visualizations AND text documents. **Use it aggressively — both for visual artifacts AND written reports.** ##...
hacknation
www/lib/ai/prompts.ts
TypeScript
13b60467c8bee9ef4f7eb13176091ce5c4df54babbf883b1eab0e58d8be6cae8
0
896
`You are a friendly assistant! Keep your responses concise and helpful. When asked to write, create, or help with something, just do it directly. Don't ask clarifying questions unless absolutely necessary - make reasonable assumptions and proceed with the task.`; export type RequestHints = { latitude: Geo["latitude...
hacknation
www/lib/ai/prompts.ts
TypeScript
c0bab984837139bc30a7741a7be6058fb80d3f0d375beaa8be7528a4de79c773
1
698
import { devToolsMiddleware } from "@ai-sdk/devtools"; import { gateway } from "@ai-sdk/gateway"; import { wrapLanguageModel } from "ai"; import { chatModels } from "./models"; const isDevMode = process.env.NODE_ENV === "development"; /** * Fallback model used for titles, artifacts, and when no model is specified. ...
hacknation
www/lib/ai/providers.ts
TypeScript
10a02206376301ac55fab9c524b4a251ee2f496cda414036e401a8c475a80d8a
0
470
import { stepCountIs, ToolLoopAgent } from "ai"; import { getLanguageModel } from "../providers"; import { getDemographics } from "../tools/getDemographics"; import { getFacility } from "../tools/getFacility"; import { getSchema } from "../tools/getSchema"; import { queryDatabase } from "../tools/queryDatabase"; import...
hacknation
www/lib/ai/agents/database-agent.ts
TypeScript
34efe3bfae790a362421e4d3a590fd90fb5423a97ea94df79cc3ccc02f74908e
0
418
import { stepCountIs, ToolLoopAgent } from "ai"; import { getLanguageModel } from "../providers"; import { compareRegions } from "../tools/compareRegions"; import { findMedicalDeserts } from "../tools/findMedicalDeserts"; import { findNearby } from "../tools/findNearby"; import { planMission } from "../tools/planMissio...
hacknation
www/lib/ai/agents/geospatial-agent.ts
TypeScript
50d8cfeb56f83d181732341742c12cbb866258e804aad6a8dcb8037c8c002815
0
371
import { stepCountIs, ToolLoopAgent } from "ai"; import { getLanguageModel } from "../providers"; import { askClarifyingQuestion } from "../tools/ask-clarifying-question"; import { getProviderProfile } from "../tools/get-provider-profile"; import { searchProviders } from "../tools/search-providers"; import { firecrawlE...
hacknation
www/lib/ai/agents/health-search-agent.ts
TypeScript
8542ff8c27626e9eeb4c10b5667ad9775893dc9f4b6bb6a1438c2969549c4173
0
590
export { databaseAgent } from "./database-agent"; export { geospatialAgent } from "./geospatial-agent"; export { healthSearchAgent } from "./health-search-agent"; export { medicalReasoningAgent } from "./medical-reasoning-agent"; export { missionPlannerAgent } from "./mission-planner-agent"; export { createOrchestrator...
hacknation
www/lib/ai/agents/index.ts
TypeScript
b3a684e43b3a88aafd7d81245f0c8b6960134e7ef5268884322ef3241a55e076
0
97
import { stepCountIs, ToolLoopAgent } from "ai"; import { getLanguageModel } from "../providers"; import { assessFacilityCredibility } from "../tools/assessFacilityCredibility"; import { detectAnomalies } from "../tools/detectAnomalies"; import { analyzeTextEvidence } from "../tools/medical/analyzeTextEvidence"; import...
hacknation
www/lib/ai/agents/medical-reasoning-agent.ts
TypeScript
c32b8641f71babe679c3ce91e62f6a4a900fafe4c458a69167b1809b6ce7db5a
0
398
/** * Mission Planner Agent — autonomous volunteer deployment workflow. * * Uses the evaluator-optimizer pattern: runs gap analysis, finds candidate * facilities, evaluates plan quality, and iterates until the recommendation * meets quality thresholds. * * Phases (controlled by prepareStep): * Phase 1 (0-2): ...
hacknation
www/lib/ai/agents/mission-planner-agent.ts
TypeScript
ce8913d5f733e092717334c02c6e91b7bee9611f871a8c0a730cd995ea15a074
0
440
/** * Orchestrator Agent — the main coordinator for Meridian AI. * * Delegates to specialized sub-agents, manages working memory, * and streams artifact results to the client. * * Key capabilities (AI SDK v6): * - prepareStep: Phased execution with context management * - parallelInvestigate: Run 2-4 sub-age...
hacknation
www/lib/ai/agents/orchestrator.ts
TypeScript
878c60c3b3ea9146e6fe8b4e7a5a9d44aa3fa50068f990f120544dd3d258f59c
0
896
* so the user sees results from fast agents immediately * - Synthetic error messages: failed agents produce visible error * messages instead of silently returning empty arrays * - Promise.allSettled: partial failures don't block other agents */ function createParallelInvestigateTool() { // Map of agen...
hacknation
www/lib/ai/agents/orchestrator.ts
TypeScript
6ded02a47f0d8024474fd70536ea3ad15897c427a70315a4ae5913e7497441b4
1
896
; const duration = Date.now() - startTime; console.log( `[parallelInvestigate] ${tasks.length} agents completed in ${duration}ms` ); }, toModelOutput: ({ output }) => { // Summarize the combined subagent outputs for the orchestrator's context if (!output?.parts) { ...
hacknation
www/lib/ai/agents/orchestrator.ts
TypeScript
27b994fb97309c37c682575f9933b012037eb7b1968837f948f5096a29c9ecea
2
896
, session }), { ttl: 30 * 60 * 1000, }), // --- Visualization artifact tools --- getHeatmap: getHeatmapArtifact({ dataStream, session }), getRegionChoropleth: getRegionChoroplethArtifact({ dataStream, session }), getDataQualityMap: getDataQualityMapArtifact({ dataStream, session }...
hacknation
www/lib/ai/agents/orchestrator.ts
TypeScript
23e1705a9bdbc3e9a3b9c97a80d282e039f6199ff65945d25193ad56cc771ff1
3
896
return { success: true }; } catch (e) { console.error("[Memory] Failed to update:", e); return { success: false, reason: "Storage error" }; } }, }), }, stopWhen: stepCountIs(15), // --- Phased execution control --- prepareStep: ({ stepNumber, me...
hacknation
www/lib/ai/agents/orchestrator.ts
TypeScript
1d0d2f7a822e264b12a0918f27e463127a8e917476530e5764524e915fd72536
4
565
/** * Agent-specific prompts, split from the monolithic system prompt. * Each agent gets focused instructions for its domain. */ export const orchestratorPrompt = ` You are Meridian AI — a global healthcare analyst for the Virtue Foundation. You analyze healthcare facilities worldwide for planners, volunteer doctor...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
082a0734512060904597f1ccec1e3365a075bf99796a79f66603c59763e9feb1
0
896
" / "within X km" → findNearby (produces a map the user can see) - For "gaps" / "deserts" / "coverage" → findMedicalDeserts (produces a map) - For "compare" / "distribution" / "stats" → getStats (produces a dashboard) - For "volunteer" / "where should I go" / "mission planning" → planVolunteerMission (comprehensive aut...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
ec88d4679445f1876e2e4525b1e21d8ea758f93e64790636fc0e3ad32a88079b
1
896
lack equipment", "temporary equipment", "corroborated by sources" | medicalReasoning (crossValidateClaims, classifyServices) | | 4.x Anomaly Detection | "suspicious", "mismatch", "unrealistic", "shouldn't move together" | parallelInvestigate: medicalReasoning + investigateData | | 5.x Service Classification | "permanen...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
213dd3cc982eb9202863182d26f8ccd9db0ce48c361ee621df7ddbbc26441987
2
896
phrases ("Great question!", "I'd be happy to help", "Let me look into that") - Never start with "Based on the data" or "According to our database" - NEVER output transitional phrases between tool calls. Forbidden examples: - "Let me now...", "I'll analyze...", "Now let me get...", "Let me refine..." - "I need to us...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
47b6ed5ef00f63252631e3486144f494a1ac48c4bd494db68c10d7566f5e9398
3
896
quality: many facilities have null address_region, num_doctors, and capacity. Always account for NULLs. ## Example SQL Queries -- Count facilities by region: SELECT address_region, COUNT(*) AS cnt FROM facilities GROUP BY address_region ORDER BY cnt DESC; -- Find tertiary hospitals: SELECT name, address_region FROM f...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
e22f1a0c6c9846c70a7fa2a6ae4f0a973437cae0758db69b09a44a65e8b50dcb
4
896
is null. Instead: - Add \`WHERE capacity IS NOT NULL\` before ordering - If zero results, report "No bed capacity data available for this region" — do NOT return null rows as if they are results 3. **Fall back to free-text search** when structured columns are null: - Beds: \`SELECT name, description FROM faci...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
a0547eb1d35e8b9b853c5d4cd6eb31f3f50f43ac7969b47a35a52467890c9814
5
896
km for specialized care in rural or underserved areas. When getTravelTime is available, prefer road travel time over Haversine distance for access analysis. In your final response, include a clear summary that the orchestrator can relay to the user. `; export const medicalReasoningAgentPrompt = ` You are a medical dat...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
75dc829ed0659a921d7e27ac9a84981de0b01a3c889b40c3974ae16702bcbb00
6
896
for research/scraping data) When external agents propose metadata changes or corrections: 1. Use validateEnrichment to check proposed changes against existing data 2. Every change MUST include a source URL or citation 3. Changes that contradict existing data are flagged, not auto-applied 4. Numeric values are range-che...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
7a6a323a0057add344886ee56b15d1cd169e87b7bd5d07ef22df33056cdd943c
7
896
-8) Use evaluatePlan to: - Score the plan on gap coverage, facility readiness, and practical feasibility - If the score is below 7/10, identify what's missing and use findNearby or getFacility to fill gaps - Iterate until the plan meets quality thresholds or you've exhausted options ## Phase 4: Final Synthesis (Steps ...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
afbfa1e172a4b9e850b63d24dc7c51b6ade95d7215ff71dd2b2d6c5a7c87877a
8
896
When presenting results: - Lead with a brief summary of what you found and why these providers match - The searchProviders tool results will render as rich provider cards automatically - Add commentary about each provider — why they're a good match for this specific user - Note any limitations (e.g., "couldn't verify i...
hacknation
www/lib/ai/agents/prompts.ts
TypeScript
ad390b8784b88f54872a18f8638679ae60263a18ade1906b66a3f7c0447b6448
9
244
import { stepCountIs, ToolLoopAgent } from "ai"; import { getLanguageModel } from "../providers"; import { corroborateClaims } from "../tools/web/corroborateClaims"; import { firecrawlExtract } from "../tools/web/firecrawl-extract"; import { firecrawlScrape } from "../tools/web/firecrawl-scrape"; import { firecrawlSear...
hacknation
www/lib/ai/agents/web-research-agent.ts
TypeScript
95f6f39bae91819fec72e811f30906f21c01cdd02d4141ddbd6c90f0bd648ca4
0
424
/** * Artifact-enhanced tool wrappers. * * These thin wrappers call the raw geospatial / stats tools AND stream * document-style artifacts to the client via the UIMessageStreamWriter so the * frontend can render them in the unified artifact panel. */ import { tool, type UIMessageStreamWriter } from "ai"; import ...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
b7388cdf455fd96c1f24371aa3124f8c5f86665da1df559c87228bb2b2b7a46b
0
896
f.beds as number) ?? null, })), stage: "complete", progress: 1, }); dataStream.write({ type: "data-facilityMapDelta", data: payload, transient: true } as never); if (session?.user?.id) { await saveDocument({ id, title, content: payload, kind: "facility-map", userId: s...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
631a6643fb4bb3a9a0a3dd06198b8fa7b3f969150f25e4e813dff58e9a26e355
1
896
, 120] ); if (iso.error || !iso.features) return null; return { providerName: p.name, lat: p.lat, lng: p.lng, isochrones: iso.features.map((f) => ({ rangeMinutes: Math.round(f.properties.value / 60), ...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
b093ae433d3aacdb839d8406f9640b63986fd2271e6d3ebd0c1711df7e2d5472
2
896
-disable-next-line @typescript-eslint/no-explicit-any const result = rawResult as any; if (result.error) { emitDocumentFinish(dataStream); return result; } const payload = JSON.stringify({ title: `Mission plan: ${params.specialty}`, volunteerProfile: result.volu...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
245acf6835f1035438b209caad78786bbf638b71268ba80f128ad73918093937
3
896
; // ── getRegionChoropleth → region-choropleth ───────────────────────── export const getRegionChoroplethArtifact = ({ dataStream, session, }: ArtifactToolDeps) => tool({ description: 'Generate a regional choropleth map showing health metrics by region. Use for "compare regions visually", "show facil...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
6d131010066e0ce9ad9883af710c2e5167f338ea34664c4ce8ed29e14ae6bd07
4
896
getAccessibilityMapArtifact = ({ dataStream, session, }: ArtifactToolDeps) => tool({ description: 'Generate a travel time accessibility map showing isochrone polygons (real road-network zones) around a facility or location. Use for "how far can patients travel", "show travel time coverage from X", "acce...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
580f6772836ca1b9fa0fabeb3a1357b3a00e8904871a162ea434074e4a585cbc
5
896
= nearbyRows .filter((r) => r.lat && r.lng) .map((r) => { const distKm = haversineKm(center.lat, center.lng, r.lat as number, r.lng as number); const estimatedMinutes = Math.round((distKm / 50) * 60); const sortedRanges = [...rangesMinutes].sort((a, b) => a - b); ...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
5876ffd186906fb4023028429fbd8bc64d85f467c5b0306d9b1e533724bd0b28
6
896
lng, city: facilities.addressCity, region: facilities.addressRegion, hasSpecialties: sql<boolean>`specialties is not null and array_length(specialties, 1) > 0`, hasProcedures: sql<boolean>`procedures is not null and array_length(procedures, 1) > 0`, hasEquipme...
hacknation
www/lib/ai/tools/artifact-tools.ts
TypeScript
d1ec6c15d6969a269e53ccf538b56b95e18c39cbe9b2d0eb6842acd7b4c8d1eb
7
788
import { tool } from "ai"; import { z } from "zod"; /** * A pass-through tool that lets the agent ask the user a structured * clarifying question with predefined options. The UI renders this as * an interactive card with clickable buttons. * * The agent calls this tool, the result is the same structured data, * ...
hacknation
www/lib/ai/tools/ask-clarifying-question.ts
TypeScript
34af70d40ba7c213e86f3b5f83f86431ef4881e76fef66332c96ec35a66f0848
0
358
import { tool } from "ai"; import { and, eq, ilike, isNotNull } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { computeAnomalyConfidence, type AnomalyConfidence, } from "./computeAnomalyConfidence"; import { createToolLogg...
hacknation
www/lib/ai/tools/assessFacilityCredibility.ts
TypeScript
00102579ed2300396a6aa36a7b0ef4ae928dee3752cfc36487f9f921686a01ed
0
896
}, assessments: assessments.slice(0, 20), summary: redCount > 0 ? `${redCount} facilit${redCount === 1 ? "y" : "ies"} flagged with critical misrepresentation signals. ${yellowCount} require${yellowCount === 1 ? "s" : ""} further review.` : yellowCount > 0 ...
hacknation
www/lib/ai/tools/assessFacilityCredibility.ts
TypeScript
0069cacc70d4b8be4b9814ef1bbc84c8fa0f0a51a5c575297e8e441c5238fc8b
1
248
import { tool } from "ai"; import { and, ilike, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { createToolLogger } from "./debug"; import { DB_QUERY_TIMEOUT_MS, withTimeout } from "./safeguards"; export const compareReg...
hacknation
www/lib/ai/tools/compareRegions.ts
TypeScript
4b2e80b1e096294034d91de65576b95252f5dd0eb1e76734d938ea643163975e
0
896
(filterResult.count); } comparison.push(entry); } // Identify gaps const gaps: string[] = []; const maxFacilities = Math.max( ...comparison.map((c) => c.totalFacilities) ); const minFacilities = Math.min( ...comparison.map((c) => c.totalFacilities) ...
hacknation
www/lib/ai/tools/compareRegions.ts
TypeScript
736751152fa2d70b3dc4d83683560a93a95bb6ff91f90d5bd5a12abea01855f5
1
355
import { MEDICAL_KNOWLEDGE } from "../../medical-knowledge"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export type AnomalyFlag = { checkId: string; severity: "critical" | "high" | "medium" ...
hacknation
www/lib/ai/tools/computeAnomalyConfidence.ts
TypeScript
eee729de82d836304fb1ffe16047888bae3af3fc3ed784bfd0394a24e071d816
0
896
bed${beds === 1 ? "" : "s"} (minimum 5 expected for any surgical facility).`, }); } return flags; } function checkSpecialtyInfrastructureGap(f: FacilityInput): AnomalyFlag[] { const flags: AnomalyFlag[] = []; const specText = (f.specialtiesRaw ?? "").toLowerCase(); const procText = (f.proceduresRaw ?? "...
hacknation
www/lib/ai/tools/computeAnomalyConfidence.ts
TypeScript
3920fe963f0e134d5d97fddbbfe5b17b16eaefc2042298ebbcfbd91103dd2c43
1
896
< 5) { flags.push({ checkId: "unlikely_capacity", severity: "critical", explanation: `Reports ${beds} beds but only ${doctors} doctor${doctors === 1 ? "" : "s"}, which is implausible for any operational facility.`, }); } return flags; } function checkMissingCriticalData(f: FacilityInput)...
hacknation
www/lib/ai/tools/computeAnomalyConfidence.ts
TypeScript
828fc52aca98139f0a9a20ac375fbb005211d5a64be17b0ad9c4bb92dd5aefe2
2
896
): AnomalyConfidence { const flags: AnomalyFlag[] = [ ...checkInfrastructureMismatch(facility), ...checkSpecialtyInfrastructureGap(facility), ...checkProcedureEquipmentMismatch(facility), ...checkCapacityStaffingRatio(facility), ...checkMissingCriticalData(facility), ...checkProcedureBreadth(f...
hacknation
www/lib/ai/tools/computeAnomalyConfidence.ts
TypeScript
d625a9807a591a34efc301bf2977113e74666e0f304c0abf5eaa918e1197db12
3
421
import { tool, type UIMessageStreamWriter } from "ai"; import type { Session } from "next-auth"; import { z } from "zod"; import { artifactKinds, documentHandlersByArtifactKind, } from "@/lib/artifacts/server"; import type { ChatMessage } from "@/lib/types"; import { generateUUID } from "@/lib/utils"; type CreateD...
hacknation
www/lib/ai/tools/create-document.ts
TypeScript
6558989bbf25a4583f1c402b535a19db946aefae69dbcd449474d45547256612
0
412
const TOOL_LOG_PREFIX = "[VFTool]"; function truncate(value: unknown, maxLen = 500): string { const str = typeof value === "string" ? value : JSON.stringify(value, null, 0); if (str && str.length > maxLen) { return `${str.slice(0, maxLen)}... (${str.length} chars)`; } return str ?? "undefined"; } func...
hacknation
www/lib/ai/tools/debug.ts
TypeScript
8d2aceb59a672a6b64f596444395c1eaf020a193f6d08f3910983c778567e4d7
0
896
Error ? err.stack : undefined; console.error(`${tag} ERROR | ${message}`); if (stack) { console.error(`${tag} ERROR | Stack: ${stack}`); } console.error( `${tag} ERROR | Duration: ${durationMs}ms | Args: ${truncate(args, 400)}` ); }, }; }
hacknation
www/lib/ai/tools/debug.ts
TypeScript
27aed837b63b00ce97d53aa315c10fed93634b10a27430e96f274d42469416a3
1
90
import { tool } from "ai"; import { and, gt, ilike, isNotNull, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { MEDICAL_KNOWLEDGE } from "../../medical-knowledge"; import { createToolLogger } from "./debug"; import { DB_Q...
hacknation
www/lib/ai/tools/detectAnomalies.ts
TypeScript
7fda75a4e0106f1c669e86152ffa96819cd28a687a9742b0a61098a4410f9e3c
0
896
.select({ id: facilities.id, name: facilities.name, beds: facilities.capacity, doctors: facilities.numDoctors, type: facilities.facilityType, }) .from(facilities) .where( and( ...baseC...
hacknation
www/lib/ai/tools/detectAnomalies.ts
TypeScript
e7db02b7d9ef122c673546e00aca435231a2f74f00a99629c9dbc47d8b90efc2
1
896
) || procText.includes(specialty.toLowerCase()) ) { const issues: string[] = []; if (beds > 0 && beds < thresholds.minBeds) { issues.push(`${beds} beds (min ${thresholds.minBeds})`); } if (doctors > 0 && doctors < thresho...
hacknation
www/lib/ai/tools/detectAnomalies.ts
TypeScript
08c826c5032271c238ca6db8078f282fec3f5fc67fc528e80a0022d58b3e1865
2
896
procCount, equipmentLength: equipLen, issues: issues.join("; "), }); } } if (breadthAnomalies.length > 0) { anomalies.push({ type: "Procedure Breadth vs Infrastructure Mismatch", description: "Facilities c...
hacknation
www/lib/ai/tools/detectAnomalies.ts
TypeScript
fc0042d29c24e7055300042713a7025a1f4bbbc5fa58651946549f1a7ad7dc92
3
678
/** * Evaluate Plan Tool — scores mission plans using structured evaluation. * * Uses generateObject to produce typed quality metrics for a volunteer * mission plan, enabling the evaluator-optimizer pattern in the * mission planner agent. */ import { generateObject, tool } from "ai"; import { z } from "zod"; imp...
hacknation
www/lib/ai/tools/evaluate-plan.ts
TypeScript
b7ba75e04eea6079a387c79f72672562c2e307f6535e1fbf9a778d52487336f6
0
894
import { tool } from "ai"; import { and, ilike, isNotNull, or } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { CITY_COORDS } from "../../ghana"; import { createToolLogger } from "./debug"; import { clampNumber, DB_QUERY_TIMEO...
hacknation
www/lib/ai/tools/findMedicalDeserts.ts
TypeScript
38cb422bc2c54dc2e779a3f3917b3ba2acd8001792ce0d797a9a77b964ec88f1
0
896
`), ilike(facilities.specialtiesRaw, `%${word}%`) ) ) ) .limit(1000), DB_QUERY_TIMEOUT_MS, abortSignal ); if (broadMatches.length > 0) { suggestedAlternatives.push({ te...
hacknation
www/lib/ai/tools/findMedicalDeserts.ts
TypeScript
7f115ff9c94f3f1ffb7f85948542223c9256f6459c95ce63e9a3a7e4c27fb1ad
1
556
import { tool } from "ai"; import { and, ilike, isNotNull, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { isGeoError, resolveLocation } from "../../geocode"; import { createToolLogger } from "./debug"; import { clampN...
hacknation
www/lib/ai/tools/findNearby.ts
TypeScript
5faeec7355ea9412b0ce0ca6f576fb001369b5197705b375e2b32878f0d6696c
0
896
: facilities.id, name: facilities.name, type: facilities.facilityType, city: facilities.addressCity, lat: facilities.lat, lng: facilities.lng, distanceKm: distanceSql, doctors: facilities.numDoctors, beds: facilities.capacit...
hacknation
www/lib/ai/tools/findNearby.ts
TypeScript
5a8a5ad5fbb4608cda1a2f29d858359660fa21dd10c6a99c7252eaedbe1fa9bb
1
702
import FirecrawlApp from "@mendable/firecrawl-js"; import { tool } from "ai"; import { z } from "zod"; import { getProviderById } from "@/lib/db/queries"; function getFirecrawlClient() { const apiKey = process.env.FIRECRAWL_API_KEY; if (!apiKey) { throw new Error("FIRECRAWL_API_KEY environment variable is not ...
hacknation
www/lib/ai/tools/get-provider-profile.ts
TypeScript
18fe25f5e7faa0870ec5e6fea4b3385d62a4237817018bf4fdd0d6e37b85b8d9
0
795
import { tool } from "ai"; import { and, eq, gte, ilike, lte, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { demographicsBenchmarks, demographicsCountries, demographicsRegions, } from "../../db/schema.demographics"; import { createToolLogger } from "./debug"; // ------...
hacknation
www/lib/ai/tools/getDemographics.ts
TypeScript
749268d32be8758bbe056d57859c49e6e2894d8327db21a9db45717b5cac5df4
0
896
?: number; max?: number }, populationRange?: { min?: number; max?: number } ): Promise<RegionRow[]> { const conditions = [eq(demographicsRegions.countryCode, code)]; if (gdpRange?.min !== undefined) { conditions.push(gte(demographicsRegions.gdpPerCapitaUsd, gdpRange.min)); } if (gdpRange?.max !== undefin...
hacknation
www/lib/ai/tools/getDemographics.ts
TypeScript
a9c88fea032165b01f2c07e5cfff6e6e72dc9d5733e106322d8f2ced3d0aeacc
1
896
); if (!country) { const result = { error: `Country "${countryCode}" not found in demographics database.`, }; log.error(result, { countryCode }, Date.now() - start); return result; } // Fetch filtered regions const filteredRegions = await fetchRegions( ...
hacknation
www/lib/ai/tools/getDemographics.ts
TypeScript
a67f3cc24919df1fb58c708c634d219a6e59f184778f49953e98d8b68f0a6748
2
896
?? 0; const o65 = r.ageOver65Pct ?? 0; return { region: r.region, population: pop, under15: u15, under15Population: Math.round((pop * u15) / 100), working, over65: o65, over65Popul...
hacknation
www/lib/ai/tools/getDemographics.ts
TypeScript
bdea0d000c6fd93b1c1c5f64c2a8c1b2b208f2d880019f6d3807fc9d642a0895
3
896
r.region, urbanPercent: r.urbanPercent, doctorsPer1000: r.doctorsPer1000, })), ruralRegions: ruralRegions.map((r) => ({ region: r.region, ruralPercent: r.ruralPercent, doctorsPer1000: r.doctorsPer1000, })), ...
hacknation
www/lib/ai/tools/getDemographics.ts
TypeScript
cdac15f19d7b0b17c5f1150271a09798feec046968b089d4f37da13d15a0f84e
4
545
import { tool } from "ai"; import { eq, ilike } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { computeAnomalyConfidence } from "./computeAnomalyConfidence"; import { createToolLogger } from "./debug"; import { DB_QUERY_TIMEOU...
hacknation
www/lib/ai/tools/getFacility.ts
TypeScript
1c04acd0d6086a417b351ea576c6106cfdc7f40e9ab3c5cc3b7eba50dc004eae
0
896
(error: unknown) { const message = error instanceof Error ? error.message : "Unknown lookup error"; log.error(error, { id, name }, Date.now() - start); return { error: `Lookup failed: ${message}` }; } }, });
hacknation
www/lib/ai/tools/getFacility.ts
TypeScript
f143d1c587ea3bee67b844395ffdaef9237fb772f23090325f5843ffbd1db4b2
1
65
import { tool } from "ai"; import { z } from "zod"; import type { ColumnDef } from "./schema-map"; import { DEMOGRAPHICS_BENCHMARKS_SCHEMA, DEMOGRAPHICS_COUNTRIES_SCHEMA, DEMOGRAPHICS_REGIONS_SCHEMA, FACILITIES_SCHEMA, } from "./schema-map"; const TABLE_SCHEMAS: Record<string, ColumnDef[]> = { facilities: FA...
hacknation
www/lib/ai/tools/getSchema.ts
TypeScript
fbe343b3d812a9465a4afc64e856fc47ac0d45054c36f4754d57dd921aa56d2e
0
561
import { tool } from "ai"; import { and, isNotNull, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { createToolLogger } from "./debug"; import { clampNumber, DB_QUERY_TIMEOUT_MS, withTimeout } from "./safeguards"; export...
hacknation
www/lib/ai/tools/getStats.ts
TypeScript
121ebef31c95307fff4a8ba6fe98258ad219c85f7389229ef7d04cc67b6ef4d9
0
896
NULL GROUP BY specialty ORDER BY count DESC LIMIT ${limit}` ), DB_QUERY_TIMEOUT_MS, abortSignal ); const rows = Array.isArray(stats) ? stats : []; log.step("Specialty stats returned", rows.length); const output...
hacknation
www/lib/ai/tools/getStats.ts
TypeScript
3fbc331a7d8c1cf98ab671224138ed5025050be13671d1786ceacc7e9c7da757
1
428
// Database tools // Artifact-enhanced geospatial tools (stream visualizations to canvas) export { findMedicalDesertsArtifact, findNearbyArtifact, getAccessibilityMapArtifact, getDataQualityMapArtifact, getHeatmapArtifact, getRegionChoroplethArtifact, getStatsArtifact, planMissionArtifact, } from "./ar...
hacknation
www/lib/ai/tools/index.ts
TypeScript
b9c817357ffc6d2a866e456911635487706016ed3fc453f87b5cdd5306711d5d
0
360
import { tool } from "ai"; import { and, ilike, isNotNull, or, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { CITY_COORDS } from "../../ghana"; import { createToolLogger } from "./debug"; import { DB_QUERY_TIMEOUT_MS, w...
hacknation
www/lib/ai/tools/planMission.ts
TypeScript
f652711bc459d0e93410e1162c847e323f76bbd61835a84e3079beee92c421bd
0
896
number }; }> = []; if (providers.length === 0) { // NATIONAL_GAP: No facilities offer this specialty at all log.step("National gap detected for specialty", specialty); // Find the largest hospitals as potential hosts const largestHospitals = await withTimeout( db ...
hacknation
www/lib/ai/tools/planMission.ts
TypeScript
d839f95d63a75c19685701e4c420faa4cddd771f54b9be5aa876ebccfb48cd85
1
896
(3), DB_QUERY_TIMEOUT_MS, abortSignal ); log.step("Potential host facilities found", potentialHosts.length); if (potentialHosts.length > 0) { const host = potentialHosts[0]; recommendations.push({ priority: "High - Critical Ga...
hacknation
www/lib/ai/tools/planMission.ts
TypeScript
ca4fd165648c0e4e20622bd57b84e961e56112ead5a8919ecd631fe8d2e46b69
2
896
.name, city: hostRow.city, region: hostRow.region, facilityType: hostRow.facilityType, beds: hostRow.beds, doctors: hostRow.doctors, equipment: hostRow.equipment, procedures: hostRow.procedures, distanceKm: t...
hacknation
www/lib/ai/tools/planMission.ts
TypeScript
c56d3650f96934c99bc078ce78d6d599114307d150b5547e6fc93f8d0e27324b
3
278
import { tool } from "ai"; import { sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { createToolLogger } from "./debug"; import { DB_QUERY_TIMEOUT_MS, MAX_RESULT_ROWS, truncateResults, validateReadOnlySQL, withTimeout, } from "./safeguards"; import { FACILITIES_COLUMN_...
hacknation
www/lib/ai/tools/queryDatabase.ts
TypeScript
b98987f82715b47bb0eabbed7c10cb52bb8e21d44391982f3733c7632344b511
0
866
/** * Shared safeguard utilities for AI tool executions. * Provides timeout management, result truncation, input validation, and SQL safety. */ // --------------------------------------------------------------------------- // Timeout wrapper // -----------------------------------------------------------------------...
hacknation
www/lib/ai/tools/safeguards.ts
TypeScript
796552d0cc74e6053bd65d8e1af84c7b2133cb86339bbfe9cd9d5e6826bcbfb4
0
896
------------------------------------------------------------------------- // SQL validation (enhanced) // --------------------------------------------------------------------------- const DESTRUCTIVE_KEYWORDS = [ "DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "CREATE", "REPLACE", "GRANT",...
hacknation
www/lib/ai/tools/safeguards.ts
TypeScript
492b29cbccf9fdc4319f4addc5e351079f4988a1d512b9dafecf30f1932f2c90
1
896
--- // Input validation helpers // --------------------------------------------------------------------------- /** * Clamps a numeric value to a min/max range with a default fallback. */ export function clampNumber( value: unknown, min: number, max: number, defaultValue: number ): number { const num = ...
hacknation
www/lib/ai/tools/safeguards.ts
TypeScript
ce15a92209ba9a30e50f5bfb52c0fc0902dc87ee43e995e0a08889bd42a7a310
2
554
/** * Facilities table schema map — the single source of truth for column name * mappings between Drizzle ORM camelCase and PostgreSQL snake_case. * * Used by: * - queryDatabase: auto-corrects camelCase → snake_case in raw SQL * - getSchema: returns column metadata to the LLM * - error messages: provides column ...
hacknation
www/lib/ai/tools/schema-map.ts
TypeScript
70d81f1f69ad219fdb22c18d5b0c059e848c6c981ebd4374221f0292f4eaf716
0
896
", type: "text", description: "Organization classification", }, // Location { column: "address_line1", type: "text", description: "Street address" }, { column: "address_city", type: "text", description: "City name" }, { column: "address_region", type: "text", description: "Administrative ...
hacknation
www/lib/ai/tools/schema-map.ts
TypeScript
6a6876b62898eb67a129b73dabaafda5d3a1e3813f9843ee9cbaf612b9f831c1
1
896
"Whether the facility accepts volunteers", }, { column: "created_at", type: "timestamp", description: "Record creation timestamp", }, ]; // --------------------------------------------------------------------------- // Compact column hint for error messages // ----------------------------------------...
hacknation
www/lib/ai/tools/schema-map.ts
TypeScript
2373b247cdae34c7ffcd1f2e167358d9b618b83fe5567372b16df72e4da9355a
2
896
export const DEMOGRAPHICS_REGIONS_SCHEMA: ColumnDef[] = [ { column: "id", type: "serial", description: "Primary key (auto-increment)" }, { column: "country_code", type: "varchar(3)", description: "ISO country code (FK to demographics_countries)", }, { column: "region", type: "text", description: "Re...
hacknation
www/lib/ai/tools/schema-map.ts
TypeScript
33308d8436f8e52992b9d5d6077b58d7b70b2cd38d02c24ce8fd1cb42ccc0ed2
3
896
{ column: "operating_rooms_per_100k", type: "double precision", description: "Operating rooms per 100,000 people", }, { column: "data_source", type: "text", description: "Data source" }, { column: "updated_at", type: "timestamp", description: "Last update timestamp", }, ]; /** All demog...
hacknation
www/lib/ai/tools/schema-map.ts
TypeScript
9806797e67c5c56f70771c9552f2f7505de71015b9e849c6b9ac96b712fd7c38
4
107
import FirecrawlApp from "@mendable/firecrawl-js"; import { tool } from "ai"; import { z } from "zod"; import { searchCachedProviders, upsertProviders, } from "@/lib/db/queries"; function getFirecrawlClient() { const apiKey = process.env.FIRECRAWL_API_KEY; if (!apiKey) { throw new Error("FIRECRAWL_API_KEY ...
hacknation
www/lib/ai/tools/search-providers.ts
TypeScript
9410a4efc7fca16028f77cdde4c3bbfe3fdb6158b6ff8bfbad87212c754e1546
0
896
client = getFirecrawlClient(); const searchQuery = `${query} ${specialty ?? ""} ${location} doctor hospital clinic contact address phone rating`.trim(); console.log(`[searchProviders] Web search: "${searchQuery}"`); const searchData = await client.search(searchQuery, { limit: Math.min(limit ...
hacknation
www/lib/ai/tools/search-providers.ts
TypeScript
7cae8a36e60565a0c904b0bdd2743cb0a5b3d4fd6d3a91da900179b5e6deba50
1
896
structured results const providers = extractedProviders.slice(0, limit).map((p, idx) => ({ id: `web-${idx}`, name: p.name, type: p.type, specialty: p.specialty ?? null, address: p.address ?? null, city: p.city ?? location, region: p.region ?? null, c...
hacknation
www/lib/ai/tools/search-providers.ts
TypeScript
7c8f36fb47d784d079a96429e63d03baa72e05bcf02dc6fa57b6ff1be3047ec7
2
329
import { tool } from "ai"; import { and, cosineDistance, desc, ilike, isNotNull, sql } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../db"; import { facilities } from "../../db/schema.facilities"; import { embed } from "../../embed"; import { computeAnomalyConfidence } from "./computeAnomalyConfi...
hacknation
www/lib/ai/tools/searchFacilities.ts
TypeScript
704aae55e92dff7f4018a57f0568388ff617b7c6bcd3b2a2a49c243c790d8f22
0
896
type, lat: row.lat, lng: row.lng, similarity: row.similarity, procedures: row.procedures, equipment: row.equipment, confidence: { level: confidence.level, score: confidence.score, flagCount: confidence.flags.length, ...
hacknation
www/lib/ai/tools/searchFacilities.ts
TypeScript
e3de87d5ac4efc9c270edd7b6d5aa6cc7511cd8584ac158af558424ab008b375
1
167
import { tool } from "ai"; import { and, cosineDistance, desc, eq, ilike, isNotNull, sql, } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../../db"; import { facilities } from "../../../db/schema.facilities"; import { embed } from "../../../embed"; import { createToolLogger } from "....
hacknation
www/lib/ai/tools/medical/analyzeTextEvidence.ts
TypeScript
c36581991793382b0b543576a789705676e338e8989a23dd610239c140f474e6
0
896
classification */ subCategories: { legacy: [ "analog", "film-based", "manual", "outdated", "old model", "refurbished", "second-hand", "secondhand", "donated equipment", "reconditioned", "legacy", ], modern: [ ...
hacknation
www/lib/ai/tools/medical/analyzeTextEvidence.ts
TypeScript
108c937406044d280a1d00cefcad4cac88f4883957594670b87e1ec25acc93f8
1
896
string | null; equipment: string | null; capabilities: string | null; description: string | null; specialties: string | null; region: string | null; }>; if (facilityId) { // Direct lookup rows = await withTimeout( db .select({ ...
hacknation
www/lib/ai/tools/medical/analyzeTextEvidence.ts
TypeScript
95dbaee50e7938df7ef07e240ffaca3122f7c9edc97d1a726916b90a442e4128
2
896
> 0) { evidence.equipmentAgeClass = "modern"; } else { evidence.equipmentAgeClass = "unknown"; } } allEvidence.push(evidence); } } } // Build summary by category const categorySummary: Record<string...
hacknation
www/lib/ai/tools/medical/analyzeTextEvidence.ts
TypeScript
a9eddeef9731bf16702f0d7deb10b80571a5394e6b977ec2d964dee32f55216c
3
207
import { tool } from "ai"; import { and, eq, ilike, isNotNull } from "drizzle-orm"; import { z } from "zod"; import { db } from "../../../db"; import { facilities } from "../../../db/schema.facilities"; import { createToolLogger } from "../debug"; import { DB_QUERY_TIMEOUT_MS, withTimeout } from "../safeguards"; /** ...
hacknation
www/lib/ai/tools/medical/classifyServices.ts
TypeScript
f6e4783092988d8f7c64367d820d17f531a026dc242733fedd5377df3a84b752
0
896