<% ' ApiContextController: task briefing assembly (spec FR-010, section 9.3, section 10, AC-05, AC-16). ' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (FTS query). ' ' POST /api/v1/context ' {"task", "namespace_ids":[], "session_id", "include":["constraints","preferences","decisions","lessons","knowledge", ' "references","working_state"], "verification_filter":"verified_only|include_unverified", ' "detail_level":"full|summary", "max_context_tokens":100..32000, "max_items":1..50, "max_references":0..20, ' "format":"structured"} ' ' Matching is hybrid (lexical fused with vector similarity, core/lib.Embeddings.asp) when configured, else lexical. ' Assembly (all filtered to active, currently valid memories in namespaces the caller can read): ' constraints every constraint memory in scope, by importance: loaded by scope, not by similarity, and required. ' If they do not fit the budget the request fails with 422 context_budget_exceeded. ' working_state latest checkpoint of session_id (404 when the session is not visible) ' preferences every preference memory in scope, by importance ' conflicts disputed memories among the above and the task matches (always reported, labelled) ' decisions / lessons / knowledge matches of the task (hybrid or lexical), by type ' references matches over current document chunks (untrusted reference content) ' unverified unverified matches, only with verification_filter include_unverified ' The budget is filled in that order; an item that does not fit is skipped and counted. Memories with identical ' content (same text, ignoring case and outer whitespace) appear once. Token counts are estimates (characters / 4) of the included text, not of ' the JSON envelope. Constraints are always returned in full, also with detail_level summary. Const CTX_CONSTRAINTS = 0 Const CTX_PREFERENCES = 1 Const CTX_CONFLICTS = 2 Const CTX_DECISIONS = 3 Const CTX_LESSONS = 4 Const CTX_KNOWLEDGE = 5 Const CTX_REFERENCES = 6 Const CTX_UNVERIFIED = 7 Const CTX_SECTION_COUNT = 8 Const CTX_MAX_POLICIES = 200 Class ApiContextController_Class Private m_errs ' candidates, in rank order within each section Private m_cSec(), m_cJson(), m_cTok(), m_cTel(), m_cN, m_spec Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok, m_strategy, m_rankWarning, m_demoted Public Property Get useLayout() useLayout = False End Property Public Property Let useLayout(v) End Property Public Property Get Title() Title = "Context API" End Property '--------------------------------------------------------------- ' POST /api/v1/context '--------------------------------------------------------------- Public Sub Assemble() Dim body, input, task, fts, budget, maxItems, maxRefs, detail, vf, fmt, requested, allowed, sessionId Dim incPrefs, incDecisions, incLessons, incKnowledge, incRefs, incState Dim rs, sql, now_, i, j, n, ids(), scores(), idList, sec, json, warnings, complete Dim stateJson, stateTok, sessNs, sessStatus, sessObjective, curRev, savedAt Dim used, requiredTok, policyCount, truncated, omittedBudget, omittedLimit, cap Dim outSec(), cnt(), out, refSeen, txt, policiesCapped, ranker, qid, t0 t0 = Timer If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) '--- validation ----------------------------------------------- m_errs = "" task = ReqString(input, "task", 2000) budget = OptInt(input, "max_context_tokens", 4000, 100, 32000) maxItems = OptInt(input, "max_items", 10, 1, 50) maxRefs = OptInt(input, "max_references", 5, 0, 20) detail = LCase("" & OptStringDefault(input, "detail_level", 20, "full")) If detail <> "full" And detail <> "summary" Then AddErr "detail_level must be full or summary." End If vf = LCase("" & OptStringDefault(input, "verification_filter", 30, "verified_only")) If vf <> "verified_only" And vf <> "include_unverified" Then AddErr "verification_filter must be verified_only or include_unverified." End If fmt = LCase("" & OptStringDefault(input, "format", 20, "structured")) If fmt <> "structured" Then AddErr "format must be structured." End If sessionId = OptStringDefault(input, "session_id", 64, "") If Len(sessionId) > 0 Then If Not Api_IsId(sessionId) Then AddErr "session_id must be a valid id." End If End If requested = IdListSql(input, "namespace_ids") incPrefs = True incDecisions = True incLessons = True incKnowledge = True incRefs = True incState = True If input.HasRaw("include") Then Dim incArr, inc incArr = JsonLite_ParseStringArray(input.Raw("include")) If IsNull(incArr) Then AddErr "include must be an array of section names." Else incPrefs = False incDecisions = False incLessons = False incKnowledge = False incRefs = False incState = False For i = 0 To UBound(incArr) inc = LCase(Trim(incArr(i))) Select Case inc Case "constraints" ' always included Case "preferences" incPrefs = True Case "decisions" incDecisions = True Case "lessons" incLessons = True Case "knowledge" incKnowledge = True Case "references" incRefs = True Case "working_state" incState = True Case Else AddErr "include contains an unknown section: " & Left(inc, 40) & "." End Select Next End If ElseIf input.Exists("include") Then If Not IsNull(input.Item("include")) Then AddErr "include must be an array of section names." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If fts = Search_FtsQuery(task) If Len(fts) = 0 Then Api_Invalid Array("task must contain at least one word.") Exit Sub End If '--- session (checked before any retrieval: an invisible session is a 404) --- stateJson = "null" stateTok = 0 If Len(sessionId) > 0 Then Set rs = DAL().Query("SELECT namespace_id, status, objective FROM sessions WHERE id = ? AND tenant_id = ?", Array(sessionId, Api_TenantId)) If rs.EOF Then rs.Close Api_Error 404, "session_not_found", "Session not found." Exit Sub End If sessNs = "" & rs(0) sessStatus = "" & rs(1) sessObjective = "" & rs(2) rs.Close If Not Api_CanAccessNamespace(sessNs, "read") Then Api_Error 404, "session_not_found", "Session not found." Exit Sub End If If incState Then curRev = 0 Set rs = DAL().Query("SELECT MAX(revision) FROM checkpoints WHERE session_id = ?", sessionId) If Not rs.EOF Then If Not IsNull(rs(0)) Then curRev = CLng(rs(0)) End If End If rs.Close txt = "null" savedAt = "null" If curRev > 0 Then Set rs = DAL().Query("SELECT state, created_at FROM checkpoints WHERE session_id = ? AND revision = ?", Array(sessionId, curRev)) If Not rs.EOF Then txt = "" & rs(0) savedAt = JsonLite_Quote("" & rs(1)) End If rs.Close End If stateTok = Tokens(sessObjective & vbLf & txt) stateJson = "{""session_id"":" & JsonLite_Quote(sessionId) & ",""status"":" & JsonLite_Quote(sessStatus) & _ ",""objective"":" & JsonLite_Quote(sessObjective) & ",""revision"":" & curRev & ",""state"":" & txt & _ ",""saved_at"":" & savedAt & ",""token_estimate"":" & stateTok & "}" End If End If allowed = Api_AllowedNamespaceIds("read") If Len(allowed) > 0 And Len(requested) > 0 Then allowed = IntersectIds(allowed, requested) End If m_cN = 0 ReDim m_cSec(31) ReDim m_cJson(31) ReDim m_cTok(31) ReDim m_cTel(31) m_spec = "" m_seen = Chr(31) m_strategy = "lexical" m_rankWarning = "" m_demoted = 0 m_dupes = 0 m_unverifiedExcluded = 0 policiesCapped = False now_ = Api_Now() If Len(allowed) > 0 Then '--- 1. policies: constraints and preferences, by scope ------------------ sql = CtxMemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _ "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _ "AND r.verification_status <> 'rejected' AND m.type IN ('constraint','preference') " & _ "ORDER BY CASE m.type WHEN 'constraint' THEN 0 ELSE 1 END, COALESCE(r.importance, 0) DESC, m.updated_at DESC LIMIT " & (CTX_MAX_POLICIES + 1) Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_)) policyCount = 0 Do While Not rs.EOF policyCount = policyCount + 1 If policyCount > CTX_MAX_POLICIES Then policiesCapped = True Exit Do End If If "" & rs(2) = "constraint" Then AddMemory rs, CTX_CONSTRAINTS, vf, "full", 0 ElseIf incPrefs Then AddMemory rs, CTX_PREFERENCES, vf, detail, 0 End If rs.MoveNext Loop rs.Close '--- 2. memory matches (lexical, fused with semantic when configured) ---------- If incDecisions Or incLessons Or incKnowledge Then Set ranker = New Ranker_Class ranker.Run "memory", fts, task, Api_TenantId, allowed NoteRanker ranker n = ranker.Count If n > 0 Then ReDim ids(n - 1) ReDim scores(n - 1) For i = 0 To n - 1 ids(i) = ranker.IdAt(i) scores(i) = -ranker.ScoreAt(i) Next End If idList = IdSqlList(ids, n) If Len(idList) > 0 Then ' Read the canonical rows (closing the result set), then add them in rank order. sql = CtxMemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _ "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _ "AND r.verification_status <> 'rejected' AND m.type NOT IN ('constraint','preference','working')" Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_)) Dim rowsTmp rowsTmp = Empty If Not rs.EOF Then rowsTmp = rs.GetRows() End If rs.Close If Not IsEmpty(rowsTmp) Then ' GetRows is (column, row); walk the ranks and pick the matching row For i = 0 To n - 1 For j = 0 To UBound(rowsTmp, 2) If "" & rowsTmp(0, j) = ids(i) Then sec = TypeSection("" & rowsTmp(2, j)) If sec = CTX_DECISIONS And Not incDecisions Then sec = -1 ElseIf sec = CTX_LESSONS And Not incLessons Then sec = -1 ElseIf sec = CTX_KNOWLEDGE And Not incKnowledge Then sec = -1 End If If sec >= 0 Then AddMemoryRow rowsTmp, j, sec, vf, detail, -CDbl(scores(i)) End If Exit For End If Next Next End If End If End If '--- 3. reference passages ------------------------------------------------ If incRefs And maxRefs > 0 Then Set ranker = New Ranker_Class ranker.Run "chunk", fts, task, Api_TenantId, allowed NoteRanker ranker n = ranker.Count If n > 0 Then ReDim ids(n - 1) ReDim scores(n - 1) For i = 0 To n - 1 ids(i) = ranker.IdAt(i) scores(i) = -ranker.ScoreAt(i) Next End If idList = IdSqlList(ids, n) If Len(idList) > 0 Then Dim chunkRows chunkRows = Empty sql = "SELECT c.id, c.document_id, c.document_revision, c.ordinal, c.content, c.heading_path, c.start_offset, c.end_offset, d.namespace_id, d.title, d.source_uri " & _ "FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") " & _ "AND c.document_revision = d.current_revision" Set rs = DAL().Query(sql, Api_TenantId) If Not rs.EOF Then chunkRows = rs.GetRows() End If rs.Close If Not IsEmpty(chunkRows) Then refSeen = Chr(31) cap = 0 For i = 0 To n - 1 If cap >= maxRefs Then Exit For End If For j = 0 To UBound(chunkRows, 2) If "" & chunkRows(0, j) = ids(i) Then txt = "" & chunkRows(4, j) If InStr(refSeen, Chr(31) & txt & Chr(31)) > 0 Then m_dupes = m_dupes + 1 Else refSeen = refSeen & txt & Chr(31) json = RefJson(chunkRows, j, detail, -CDbl(scores(i))) AddCand CTX_REFERENCES, json, m_lastTok, "chunk|" & ids(i) & "|" & CLng(chunkRows(2, j)) & "|" & JsonLite_Num(-CDbl(scores(i))) cap = cap + 1 End If Exit For End If Next Next End If End If End If End If '--- budget --------------------------------------------------------------------- requiredTok = 0 For i = 0 To m_cN - 1 If m_cSec(i) = CTX_CONSTRAINTS Then requiredTok = requiredTok + m_cTok(i) End If Next If requiredTok > budget Then Api_Audit "context.assemble", "context", "", "budget_exceeded" Api_Send 422, "{""error"":{""code"":""context_budget_exceeded"",""message"":" & _ JsonLite_Quote("The applicable constraints need about " & requiredTok & " tokens, more than max_context_tokens (" & budget & "). Raise the budget or narrow namespace_ids.") & _ ",""required_tokens"":" & requiredTok & ",""max_context_tokens"":" & budget & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" Exit Sub End If ReDim outSec(CTX_SECTION_COUNT - 1) ReDim cnt(CTX_SECTION_COUNT - 1) For i = 0 To CTX_SECTION_COUNT - 1 outSec(i) = "" cnt(i) = 0 Next used = requiredTok omittedBudget = 0 omittedLimit = 0 For i = 0 To m_cN - 1 If m_cSec(i) = CTX_CONSTRAINTS Then AppendTo outSec, cnt, CTX_CONSTRAINTS, m_cJson(i) AddTel i End If Next warnings = "" If stateTok > 0 Then If used + stateTok <= budget Then used = used + stateTok Else stateJson = "null" omittedBudget = omittedBudget + 1 AddWarning warnings, "working_state did not fit the budget and was left out; restore it with GET /sessions/{id}/state" End If End If For sec = CTX_PREFERENCES To CTX_SECTION_COUNT - 1 If sec = CTX_PREFERENCES Then cap = 50 ElseIf sec = CTX_REFERENCES Then cap = maxRefs Else cap = maxItems End If For i = 0 To m_cN - 1 If m_cSec(i) = sec Then If cnt(sec) >= cap Then omittedLimit = omittedLimit + 1 ElseIf used + m_cTok(i) > budget Then omittedBudget = omittedBudget + 1 Else used = used + m_cTok(i) AppendTo outSec, cnt, sec, m_cJson(i) AddTel i End If End If Next Next complete = True If policiesCapped Then complete = False AddWarning warnings, "more than " & CTX_MAX_POLICIES & " constraint/preference memories are in scope; only the most important were considered, so the briefing is incomplete. Narrow namespace_ids." End If truncated = (omittedBudget > 0) If omittedBudget > 0 Then AddWarning warnings, omittedBudget & " item(s) left out to fit max_context_tokens" End If If m_unverifiedExcluded > 0 Then AddWarning warnings, m_unverifiedExcluded & " unverified item(s) excluded; use verification_filter include_unverified to see them" End If If cnt(CTX_CONFLICTS) > 0 Then AddWarning warnings, cnt(CTX_CONFLICTS) & " disputed item(s) included under conflicts; do not rely on them without checking" End If If Len(allowed) = 0 Then AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty" End If If m_demoted > 0 Then AddWarning warnings, m_demoted & " matched item(s) ranked lower because of negative feedback on their current revision" End If If Len(m_rankWarning) > 0 Then AddWarning warnings, m_rankWarning End If ' Telemetry: the query id is returned so results can be rated with POST /feedback qid = Tel_NewQueryId() Tel_Record qid, "context", m_strategy, task, m_spec, t0 out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""query_id"":" & JsonLite_Quote(qid) & ",""task"":" & JsonLite_Quote(task) & _ ",""strategy"":" & JsonLite_Quote(m_strategy) & ",""format"":""structured"",""verification_filter"":" & JsonLite_Quote(vf) & ",""detail_level"":" & JsonLite_Quote(detail) & _ ",""budget"":{""max_context_tokens"":" & budget & ",""used_tokens"":" & used & ",""counting_method"":""estimate_chars_div_4""" & _ ",""complete"":" & LCase(CStr(complete)) & ",""truncated"":" & LCase(CStr(truncated)) & "}" & _ ",""omitted"":{""over_budget"":" & omittedBudget & ",""over_limit"":" & omittedLimit & ",""duplicates"":" & m_dupes & ",""unverified_excluded"":" & m_unverifiedExcluded & "}" out = out & ",""constraints"":[" & outSec(CTX_CONSTRAINTS) & "]" If incState Then out = out & ",""working_state"":" & stateJson End If If incPrefs Then out = out & ",""preferences"":[" & outSec(CTX_PREFERENCES) & "]" End If out = out & ",""conflicts"":[" & outSec(CTX_CONFLICTS) & "]" If incDecisions Then out = out & ",""decisions"":[" & outSec(CTX_DECISIONS) & "]" End If If incLessons Then out = out & ",""lessons"":[" & outSec(CTX_LESSONS) & "]" End If If incKnowledge Then out = out & ",""knowledge"":[" & outSec(CTX_KNOWLEDGE) & "]" End If If incRefs Then out = out & ",""references"":[" & outSec(CTX_REFERENCES) & "]" End If If vf = "include_unverified" Then out = out & ",""unverified"":[" & outSec(CTX_UNVERIFIED) & "]" End If out = out & ",""warnings"":[" & warnings & "]}" Api_Audit "context.assemble", "context", "", "ok" Api_Send 200, out End Sub '=============================================================== ' Helpers '=============================================================== ' Columns relied on by AddMemory / AddMemoryRow: ' 0 id, 1 namespace_id, 2 type, 3 revision, 4 title, 5 summary, 6 content, 7 tags, 8 confidence, 9 importance, ' 10 verification_status, 11 content_hash, 12 creator, 13 updated_at, 14 valid_until ' Strategy/warning of the last ranking (hybrid unless semantic retrieval was unavailable for any section) Private Sub NoteRanker(r) m_demoted = m_demoted + r.Demoted If Len(r.Warning) > 0 Then m_rankWarning = r.Warning m_strategy = "lexical" ElseIf Len(m_rankWarning) = 0 Then m_strategy = r.Strategy End If End Sub Private Function CtxMemorySelect() CtxMemorySelect = "SELECT m.id, m.namespace_id, m.type, r.revision, r.title, r.summary, r.content, r.tags, r.confidence, r.importance, " & _ "r.verification_status, r.content_hash, m.creator_principal_id, m.updated_at, m.valid_until " & _ "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision" End Function Private Function TypeSection(t) Select Case t Case "decision" TypeSection = CTX_DECISIONS Case "lesson" TypeSection = CTX_LESSONS Case Else TypeSection = CTX_KNOWLEDGE End Select End Function ' Copies one result-set row into an array and hands it to AddMemoryRow (single code path for both sources). Private Sub AddMemory(rs, sec, vf, detail, score) Dim row(14, 0), k For k = 0 To 14 row(k, 0) = rs(k) Next AddMemoryRow row, 0, sec, vf, detail, score End Sub ' rows is GetRows-shaped (column, row). Sorts the memory into its section by verification state and dedupes by content. Private Sub AddMemoryRow(rows, j, sec, vf, detail, score) Dim st, key, json, target st = "" & rows(10, j) target = sec If st = "disputed" Then target = CTX_CONFLICTS ElseIf st <> "verified" Then If vf = "include_unverified" Then target = CTX_UNVERIFIED Else m_unverifiedExcluded = m_unverifiedExcluded + 1 Exit Sub End If End If ' The stored content_hash also covers namespace, type and title, so the same text in two namespaces has two ' hashes. Dedupe on the normalized content instead. key = LCase(Trim("" & rows(6, j))) If InStr(m_seen, Chr(31) & key & Chr(31)) > 0 Then m_dupes = m_dupes + 1 Exit Sub End If m_seen = m_seen & key & Chr(31) json = MemJson(rows, j, detail, score, st, (sec = CTX_CONSTRAINTS)) AddCand target, json, m_lastTok, "memory|" & rows(0, j) & "|" & CLng(rows(3, j)) & "|" & TelScore(score) End Sub Private Function MemJson(rows, j, detail, score, st, isPolicy) Dim s, bodyText, trust If detail = "summary" Then If IsNull(rows(5, j)) Then bodyText = "" & rows(6, j) If Len(bodyText) > 240 Then bodyText = Left(bodyText, 240) & "..." End If Else bodyText = "" & rows(5, j) End If Else bodyText = "" & rows(6, j) End If m_lastTok = Tokens("" & rows(4, j) & vbLf & bodyText) Select Case st Case "verified" trust = "verified_memory" Case "disputed" trust = "disputed_memory" Case Else trust = "unverified_memory" End Select s = "{""id"":" & JsonLite_Quote("" & rows(0, j)) & ",""revision"":" & CLng(rows(3, j)) & ",""type"":" & JsonLite_Quote("" & rows(2, j)) & _ ",""namespace_id"":" & JsonLite_Quote("" & rows(1, j)) & ",""title"":" & JsonLite_Quote("" & rows(4, j)) If detail = "summary" Then s = s & ",""summary"":" & JsonLite_Quote(bodyText) Else s = s & ",""content"":" & JsonLite_Quote(bodyText) End If s = s & ",""verification_status"":" & JsonLite_Quote(st) & ",""content_trust"":" & JsonLite_Quote(trust) If isPolicy Then If st = "verified" Then s = s & ",""authority"":""policy""" End If End If s = s & ",""tags"":" & JRaw(rows(7, j), "[]") & ",""confidence"":" & JNum(rows(8, j)) & ",""importance"":" & JNum(rows(9, j)) If score <> 0 Then s = s & ",""relevance_score"":" & JsonLite_Num(score) End If s = s & ",""valid_until"":" & JStr(rows(14, j)) & ",""provenance"":{""created_by"":" & JsonLite_Quote("" & rows(12, j)) & _ ",""updated_at"":" & JsonLite_Quote("" & rows(13, j)) & "},""token_estimate"":" & m_lastTok & "}" MemJson = s End Function ' Chunk row columns: 0 id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end, ' 8 namespace id, 9 title, 10 source uri Private Function RefJson(rows, j, detail, score) Dim txt, s txt = "" & rows(4, j) If detail = "summary" Then If Len(txt) > 240 Then txt = Left(txt, 240) & "..." End If End If m_lastTok = Tokens(txt) s = "{""chunk_id"":" & JsonLite_Quote("" & rows(0, j)) & ",""document_id"":" & JsonLite_Quote("" & rows(1, j)) & _ ",""document_title"":" & JsonLite_Quote("" & rows(9, j)) & ",""source_uri"":" & JStr(rows(10, j)) & _ ",""document_revision"":" & CLng(rows(2, j)) & ",""ordinal"":" & CLng(rows(3, j)) & ",""heading_path"":" & JStr(rows(5, j)) & _ ",""locator"":{""start"":" & CLng(rows(6, j)) & ",""end"":" & CLng(rows(7, j)) & "},""namespace_id"":" & JsonLite_Quote("" & rows(8, j)) & _ ",""relevance_score"":" & JsonLite_Num(score) & ",""content"":" & JsonLite_Quote(txt) & _ ",""content_trust"":""untrusted_reference"",""token_estimate"":" & m_lastTok & "}" RefJson = s End Function ' tel: "kind|id|revision|score" of the item, recorded for feedback if the item makes it into the briefing Private Sub AddCand(sec, json, tok, tel) If m_cN > UBound(m_cSec) Then ReDim Preserve m_cSec(m_cN * 2) ReDim Preserve m_cJson(m_cN * 2) ReDim Preserve m_cTok(m_cN * 2) ReDim Preserve m_cTel(m_cN * 2) End If m_cSec(m_cN) = sec m_cJson(m_cN) = json m_cTok(m_cN) = tok m_cTel(m_cN) = tel m_cN = m_cN + 1 End Sub Private Sub AddTel(i) If Len(m_spec) > 0 Then m_spec = m_spec & Chr(30) End If m_spec = m_spec & m_cTel(i) End Sub ' Constraints and preferences are loaded by scope and have no similarity score Private Function TelScore(score) TelScore = "0" If IsNumeric(score) Then If Not IsEmpty(score) Then TelScore = JsonLite_Num(score) End If End If End Function Private Sub AppendTo(outSec, cnt, sec, json) If cnt(sec) > 0 Then outSec(sec) = outSec(sec) & "," End If outSec(sec) = outSec(sec) & json cnt(sec) = cnt(sec) + 1 End Sub Private Sub AddWarning(warnings, text) If Len(warnings) > 0 Then warnings = warnings & "," End If warnings = warnings & JsonLite_Quote(text) End Sub ' Token estimate for included text: characters / 4, rounded up (declared as estimate_chars_div_4) Private Function Tokens(text) Tokens = Int((Len(text) + 3) / 4) End Function ' 'id1','id2' for the first n valid ids Private Function IdSqlList(ids, n) Dim i, out out = "" For i = 0 To n - 1 If Api_IsId(ids(i)) Then If Len(out) > 0 Then out = out & "," End If out = out & "'" & ids(i) & "'" End If Next IdSqlList = out End Function Private Function JStr(v) If IsNull(v) Then JStr = "null" Else JStr = JsonLite_Quote("" & v) End If End Function Private Function JNum(v) If IsNull(v) Then JNum = "null" ElseIf Len("" & v) = 0 Then JNum = "null" Else JNum = JsonLite_Num(v) End If End Function Private Function JRaw(v, dflt) If IsNull(v) Then JRaw = dflt ElseIf Len("" & v) = 0 Then JRaw = dflt Else JRaw = "" & v End If End Function Private Sub AddErr(msg) If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30) End If m_errs = m_errs & msg End Sub Private Function ReqString(input, name, maxLen) Dim v ReqString = "" If Not input.Exists(name) Then AddErr name & " is required." Exit Function End If v = input.Item(name) If IsNull(v) Then AddErr name & " is required." Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If v = Trim(v) If Len(v) = 0 Then AddErr name & " must not be empty." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If ReqString = v End Function ' Optional string with a default when absent or null Private Function OptStringDefault(input, name, maxLen, dflt) Dim v OptStringDefault = dflt If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If OptStringDefault = v End Function ' Optional whole number in lo..hi with a default when absent or null Private Function OptInt(input, name, dflt, lo, hi) Dim v OptInt = dflt If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbDouble Then AddErr name & " must be a number." Exit Function End If If v <> Int(v) Or v < lo Or v > hi Then AddErr name & " must be a whole number between " & lo & " and " & hi & "." Exit Function End If OptInt = CLng(v) End Function Private Function IdListSql(input, name) Dim arr, i, out IdListSql = "" If Not input.HasRaw(name) Then If input.Exists(name) Then If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids." End If End If Exit Function End If arr = JsonLite_ParseStringArray(input.Raw(name)) If IsNull(arr) Then AddErr name & " must be an array of ids." Exit Function End If out = "" For i = 0 To UBound(arr) If Not Api_IsId(arr(i)) Then AddErr name & " must contain valid ids." Exit Function End If If Len(out) > 0 Then out = out & "," End If out = out & "'" & arr(i) & "'" Next If Len(out) = 0 Then AddErr name & " must not be empty when given." End If IdListSql = out End Function Private Function IntersectIds(allowed, requested) Dim a, i, out a = Split(allowed, ",") out = "" For i = 0 To UBound(a) If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then If Len(out) > 0 Then out = out & "," End If out = out & a(i) End If Next IntersectIds = out End Function ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) Public Sub Invoke(actionName, args) Select Case LCase(actionName) Case "assemble" : Assemble Case Else Err.Raise 438, "ApiContextController_Class", "Action '" & actionName & "' not found" End Select End Sub End Class Dim ApiContextController_Class__Singleton Function ApiContextController() If IsEmpty(ApiContextController_Class__Singleton) Then Set ApiContextController_Class__Singleton = New ApiContextController_Class End If Set ApiContextController = ApiContextController_Class__Singleton End Function ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) Sub ApiContextController_Invoke(actionName, args) ApiContextController().Invoke actionName, args End Sub %>