1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
---@meta
--- algocline Lua StdLib — LuaCats type definitions
--- This file provides type information for editor completion and static analysis.
--- It is NOT executed at runtime. Place in workspace.library for LuaLS.
---
--- Usage: Add this directory to `workspace.library` in .luarc.json:
--- { "workspace": { "library": ["types"] } }
---
--- Layer 0: Runtime Primitives (Rust-backed)
--- Layer 1: Prelude Combinators (Pure Lua)
---@class alc
alc =
-- ============================================================
-- Layer 0: Runtime Primitives
-- ============================================================
-- LLM ---
---@class AlcLlmOpts
---@field system? string System prompt
---@field max_tokens? integer Max tokens (default: 1024)
---@field grounded? boolean Request grounded response (default: false)
---@field underspecified? boolean Signal underspecified prompt (default: false)
--- Call the Host LLM. Yields the coroutine until the host responds.
---@param prompt string The prompt to send
---@param opts? AlcLlmOpts Options
---@return string response LLM response text
---@class AlcLlmBatchItem
---@field prompt string The prompt
---@field system? string System prompt
---@field max_tokens? integer Max tokens (default: 1024)
---@field grounded? boolean Request grounded response
---@field underspecified? boolean Signal underspecified prompt
--- Send multiple LLM calls as a single batch. All queries dispatched concurrently.
---@param items AlcLlmBatchItem[] Array of query tables
---@return string[] responses Responses in same order as input
---@class AlcForkResult
---@field strategy string Package name
---@field result? string Result (on success)
---@field error? string Error message (on failure)
---@class AlcForkOpts
---@field on_error? "skip"|"fail" Error handling (default: "skip")
--- Spawn N independent Lua VMs, each running one strategy with the same ctx.
---@param strategies string[] Array of package names
---@param ctx table Context passed to each strategy's run(ctx)
---@param opts? AlcForkOpts Options
---@return AlcForkResult[] results Per-strategy results
-- JSON ---
--- Serialize a Lua value to JSON string.
---@param value any Lua value to serialize
---@return string json JSON string
--- Deserialize a JSON string to a Lua value.
---@param str string JSON string
---@return any value Lua value
-- Fuzzy Matching ---
---@class AlcMatchEnumOpts
---@field threshold? number Minimum similarity for fuzzy fallback (default: 0.7)
--- Find which candidate appears in LLM output (case-insensitive substring).
--- If multiple match, returns the one whose last occurrence is latest.
--- Falls back to fuzzy matching (Jaro-Winkler) for typos.
---@param text string LLM response text
---@param candidates string[] Valid values to search for
---@param opts? AlcMatchEnumOpts Options
---@return string|nil matched Matched candidate or nil
--- Normalize yes/no-style LLM responses.
--- Scans for affirmative/negative keywords and returns the polarity of the last-occurring keyword.
---@param text string LLM response text
---@return boolean|nil result true (affirmative), false (negative), or nil (ambiguous)
-- Logging ---
--- Emit a log message via tracing.
---@param level "error"|"warn"|"info"|"debug" Log level
---@param msg string Log message
-- State ---
---@class alc.state
alc. =
--- Read a value from the persistent key-value store.
---@param key string Key to read
---@param default? any Default value if key does not exist
---@return any value Stored value or default
--- Write a value to the persistent key-value store.
---@param key string Key to write
---@param value any JSON-serializable value
--- List all keys in the current namespace.
---@return string[] keys Array of key names
--- Remove a key from the store.
---@param key string Key to delete
-- Text ---
---@class AlcChunkOpts
---@field mode? "lines"|"chars" Chunking mode (default: "lines")
---@field size? integer Chunk size (default: 50)
---@field overlap? integer Overlap between chunks (default: 0)
--- Split text into chunks by lines or characters.
---@param text string Text to split
---@param opts? AlcChunkOpts Options
---@return string[] chunks Array of text chunks
-- Metrics ---
---@class alc.stats
alc. =
--- Record a custom metric.
---@param key string Metric name
---@param value any JSON-serializable value
--- Retrieve a recorded metric.
---@param key string Metric name
---@return any|nil value Metric value or nil
-- Time ---
--- Wall-clock time in fractional seconds since Unix epoch.
---@return number seconds Sub-millisecond precision
-- Budget ---
---@class AlcBudgetRemaining
---@field llm_calls? integer Remaining LLM calls (if limit set)
---@field elapsed_ms? integer Remaining time in ms (if limit set)
--- Query raw remaining budget.
---@return AlcBudgetRemaining|nil remaining nil if no budget set
-- Progress ---
--- Report structured progress, readable via alc_status MCP tool.
---@param step integer Current step number
---@param total integer Total number of steps
---@param msg? string Optional progress message
-- ============================================================
-- Layer 1: Prelude Combinators
-- ============================================================
-- LLM Wrappers ---
---@class AlcCacheOpts : AlcLlmOpts
---@field cache_key? string Explicit cache key (overrides auto-fingerprint)
---@field cache_skip? boolean Bypass cache, always call LLM
--- Memoized LLM call. Session-scoped cache, max 256 entries.
---@param prompt string The prompt
---@param opts? AlcCacheOpts Options (same as alc.llm plus cache control)
---@return string response Cached or fresh LLM response
---@class AlcCacheInfo
---@field entries integer Current cache entries
---@field hits integer Cache hit count
---@field misses integer Cache miss count
---@field max_entries integer Maximum cache capacity
--- Return cache statistics.
---@return AlcCacheInfo info
--- Clear all cached responses and reset counters.
--- Call alc.llm, returning default on failure instead of raising.
---@param prompt string The prompt
---@param opts? AlcLlmOpts Options
---@param default string Fallback value on error
---@return string response LLM response or default
--- Convenience wrapper: calls alc.llm with grounded = true.
---@param claim string Claim to ground
---@param opts? AlcLlmOpts Options
---@return string response Grounded response
--- Convenience wrapper: calls alc.llm with underspecified = true.
---@param prompt string Underspecified prompt
---@param opts? AlcLlmOpts Options
---@return string response Resolved response
-- Collection ---
--- Apply fn(item, index) to each item.
---@generic T, R
---@param items T[] Array of items
---@param fn fun(item: T, index: integer): R Transform function
---@return R[] results Array of results
--- Fold array to single value.
---@generic T, R
---@param items T[] Array of items
---@param fn fun(acc: R, item: T, index: integer): R Reducer function
---@param init? R Initial value (default: items[1])
---@return R result Final accumulated value
--- Keep items where fn(item, index) returns truthy.
---@generic T
---@param items T[] Array of items
---@param fn fun(item: T, index: integer): any Predicate function
---@return T[] filtered Filtered array
---@class AlcParallelOpts
---@field system? string Shared system prompt
---@field max_tokens? integer Shared max_tokens
---@field post_fn? fun(response: string, item: any, index: integer): any Post-processing function
--- Batch-parallel LLM calls over an array (single round-trip).
---@param items any[] Array of items
---@param prompt_fn fun(item: any, index: integer): string|AlcLlmBatchItem Prompt builder
---@param opts? AlcParallelOpts Options
---@return string[]|any[] results Responses (or post_fn results)
-- Aggregation ---
---@class AlcVoteResult
---@field winner string Most frequent answer
---@field count integer Count of winner
---@field total integer Total answers
--- Majority vote over an array of string answers.
---@param answers string[] Array of answers
---@return AlcVoteResult result Vote result
--- Extract the first integer from a string. Clamps to 1-10.
---@param str string String containing a number
---@param default? integer Fallback value (default: 5)
---@return integer score Score in 1-10 range
--- Extract a number from LLM output.
--- If pattern is given, uses it as a Lua pattern with a capture group.
--- Otherwise extracts the first number (integer or decimal, optionally negative).
---@param text string Text to extract from
---@param pattern? string Lua pattern with capture group
---@return number|nil value Extracted number or nil
-- JSON ---
--- Extract JSON object or array from LLM output (3-stage fallback).
---@param raw string Raw LLM output
---@return table|nil data Parsed JSON or nil
-- State ---
--- Read-modify-write for state.
---@param key string Key to update
---@param fn fun(current: any): any Transform function
---@param default? any Initial value if key does not exist
---@return any updated Updated value
-- Pipeline ---
---@class AlcPipeOpts
---@field on_stage? fun(i: integer, name: string, ctx: table) Callback after each stage
--- Sequential pipeline: run multiple strategies in order.
---@param strategies (string|fun(ctx: table): table)[] Package names or inline functions
---@param ctx table Initial context
---@param opts? AlcPipeOpts Options
---@return table ctx Context with .result and .pipe_history
-- Tuning ---
---@class AlcTuningOpts
---@field prefix? string Namespace key in ctx
--- Merge tuning defaults with ctx overrides. Deep-merges dicts, shallow-replaces arrays.
---@param defaults table Default parameter table
---@param ctx table Context with potential overrides
---@param opts? AlcTuningOpts Options
---@return table merged Merged parameters
-- Utility ---
--- Normalize text and return 8-char hex hash (DJB2). For dedup, not crypto.
---@param str string Text to fingerprint
---@return string hash 8-character hex string
--- Returns true if budget has remaining capacity.
---@return boolean ok True if safe to continue