Skip to main content

harn_stdlib/
lib.rs

1//! Canonical embedded Harn standard library source catalog.
2//!
3//! This crate intentionally contains only static source strings so runtime and
4//! static tooling crates can share the same stdlib modules without depending on
5//! each other.
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct StdlibSource {
9    pub module: &'static str,
10    pub source: &'static str,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct StdlibPromptAsset {
15    pub path: &'static str,
16    pub source: &'static str,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct StdlibPublicFunction {
21    pub name: String,
22    pub signature: String,
23    pub required_params: usize,
24    pub total_params: usize,
25    pub variadic: bool,
26    pub doc: Option<String>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct StdlibEntrypointModule {
31    pub import_path: String,
32    pub category: String,
33}
34
35pub const STDLIB_SOURCES: &[StdlibSource] = &[
36    StdlibSource {
37        module: "text",
38        source: include_str!("stdlib/stdlib_text.harn"),
39    },
40    StdlibSource {
41        module: "collections",
42        source: include_str!("stdlib/stdlib_collections.harn"),
43    },
44    StdlibSource {
45        module: "math",
46        source: include_str!("stdlib/stdlib_math.harn"),
47    },
48    StdlibSource {
49        module: "path",
50        source: include_str!("stdlib/stdlib_path.harn"),
51    },
52    StdlibSource {
53        module: "json",
54        source: include_str!("stdlib/stdlib_json.harn"),
55    },
56    StdlibSource {
57        module: "cache",
58        source: include_str!("stdlib/stdlib_cache.harn"),
59    },
60    StdlibSource {
61        module: "tools",
62        source: include_str!("stdlib/stdlib_tools.harn"),
63    },
64    StdlibSource {
65        module: "graphql",
66        source: include_str!("stdlib/stdlib_graphql.harn"),
67    },
68    StdlibSource {
69        module: "schema",
70        source: include_str!("stdlib/stdlib_schema.harn"),
71    },
72    StdlibSource {
73        module: "testing",
74        source: include_str!("stdlib/stdlib_testing.harn"),
75    },
76    StdlibSource {
77        module: "files",
78        source: include_str!("stdlib/stdlib_files.harn"),
79    },
80    StdlibSource {
81        module: "vision",
82        source: include_str!("stdlib/stdlib_vision.harn"),
83    },
84    StdlibSource {
85        module: "context",
86        source: include_str!("stdlib/stdlib_context.harn"),
87    },
88    StdlibSource {
89        module: "runtime",
90        source: include_str!("stdlib/stdlib_runtime.harn"),
91    },
92    StdlibSource {
93        module: "command",
94        source: include_str!("stdlib/stdlib_command.harn"),
95    },
96    StdlibSource {
97        module: "review",
98        source: include_str!("stdlib/stdlib_review.harn"),
99    },
100    StdlibSource {
101        module: "experiments",
102        source: include_str!("stdlib/stdlib_experiments.harn"),
103    },
104    StdlibSource {
105        module: "project",
106        source: include_str!("stdlib/stdlib_project.harn"),
107    },
108    StdlibSource {
109        module: "prompt_library",
110        source: include_str!("stdlib/stdlib_prompt_library.harn"),
111    },
112    StdlibSource {
113        module: "async",
114        source: include_str!("stdlib/stdlib_async.harn"),
115    },
116    StdlibSource {
117        module: "poll",
118        source: include_str!("stdlib/stdlib_poll.harn"),
119    },
120    StdlibSource {
121        module: "coerce",
122        source: include_str!("stdlib/stdlib_coerce.harn"),
123    },
124    StdlibSource {
125        module: "settled",
126        source: include_str!("stdlib/stdlib_settled.harn"),
127    },
128    StdlibSource {
129        module: "cli",
130        source: include_str!("stdlib/stdlib_cli.harn"),
131    },
132    StdlibSource {
133        module: "jsonl",
134        source: include_str!("stdlib/stdlib_jsonl.harn"),
135    },
136    StdlibSource {
137        module: "config",
138        source: include_str!("stdlib/stdlib_config.harn"),
139    },
140    StdlibSource {
141        module: "agents",
142        source: include_str!("stdlib/stdlib_agents.harn"),
143    },
144    StdlibSource {
145        module: "agent/prompts",
146        source: include_str!("stdlib/agent/prompts.harn"),
147    },
148    StdlibSource {
149        module: "llm/media",
150        source: include_str!("stdlib/llm/media.harn"),
151    },
152    StdlibSource {
153        module: "llm/catalog",
154        source: include_str!("stdlib/llm/catalog.harn"),
155    },
156    StdlibSource {
157        module: "llm/safe",
158        source: include_str!("stdlib/llm/safe.harn"),
159    },
160    StdlibSource {
161        module: "llm/budget",
162        source: include_str!("stdlib/llm/budget.harn"),
163    },
164    StdlibSource {
165        module: "llm/prompts",
166        source: include_str!("stdlib/llm/prompts.harn"),
167    },
168    StdlibSource {
169        module: "llm/defaults",
170        source: include_str!("stdlib/llm/defaults.harn"),
171    },
172    StdlibSource {
173        module: "llm/handlers",
174        source: include_str!("stdlib/llm/handlers.harn"),
175    },
176    StdlibSource {
177        module: "llm/tool_middleware",
178        source: include_str!("stdlib/llm/tool_middleware.harn"),
179    },
180    StdlibSource {
181        module: "llm/refine",
182        source: include_str!("stdlib/llm/refine.harn"),
183    },
184    StdlibSource {
185        module: "llm/ensemble",
186        source: include_str!("stdlib/llm/ensemble.harn"),
187    },
188    StdlibSource {
189        module: "llm/rerank",
190        source: include_str!("stdlib/llm/rerank.harn"),
191    },
192    StdlibSource {
193        module: "agent/reasoning",
194        source: include_str!("stdlib/agent/reasoning.harn"),
195    },
196    StdlibSource {
197        module: "agent/options",
198        source: include_str!("stdlib/agent/options.harn"),
199    },
200    StdlibSource {
201        module: "llm/judge",
202        source: include_str!("stdlib/llm/judge.harn"),
203    },
204    StdlibSource {
205        module: "llm/optimize",
206        source: include_str!("stdlib/llm/optimize.harn"),
207    },
208    StdlibSource {
209        module: "agent/events",
210        source: include_str!("stdlib/agent/events.harn"),
211    },
212    StdlibSource {
213        module: "agent/primitives",
214        source: include_str!("stdlib/agent/primitives.harn"),
215    },
216    StdlibSource {
217        module: "agent/loop",
218        source: include_str!("stdlib/agent/loop.harn"),
219    },
220    StdlibSource {
221        module: "agent/user",
222        source: include_str!("stdlib/agent/user.harn"),
223    },
224    StdlibSource {
225        module: "agent/tool_search",
226        source: include_str!("stdlib/agent/tool_search.harn"),
227    },
228    StdlibSource {
229        module: "agent/turn",
230        source: include_str!("stdlib/agent/turn.harn"),
231    },
232    StdlibSource {
233        module: "agent/workers",
234        source: include_str!("stdlib/agent/workers.harn"),
235    },
236    StdlibSource {
237        module: "agent/state",
238        source: include_str!("stdlib/agent/state.harn"),
239    },
240    StdlibSource {
241        module: "agent/skills",
242        source: include_str!("stdlib/agent/skills.harn"),
243    },
244    StdlibSource {
245        module: "agent/autocompact",
246        source: include_str!("stdlib/agent/autocompact.harn"),
247    },
248    StdlibSource {
249        module: "agent/mcp",
250        source: include_str!("stdlib/agent/mcp.harn"),
251    },
252    StdlibSource {
253        module: "agent/host_tools",
254        source: include_str!("stdlib/agent/host_tools.harn"),
255    },
256    StdlibSource {
257        module: "agent/budget",
258        source: include_str!("stdlib/agent/budget.harn"),
259    },
260    StdlibSource {
261        module: "agent/daemon",
262        source: include_str!("stdlib/agent/daemon.harn"),
263    },
264    StdlibSource {
265        module: "agent/preflight",
266        source: include_str!("stdlib/agent/preflight.harn"),
267    },
268    StdlibSource {
269        module: "agent/postturn",
270        source: include_str!("stdlib/agent/postturn.harn"),
271    },
272    StdlibSource {
273        module: "agent/judge",
274        source: include_str!("stdlib/agent/judge.harn"),
275    },
276    StdlibSource {
277        module: "agent/presets",
278        source: include_str!("stdlib/agent/presets.harn"),
279    },
280    StdlibSource {
281        module: "agent_state",
282        source: include_str!("stdlib/stdlib_agent_state.harn"),
283    },
284    StdlibSource {
285        module: "memory",
286        source: include_str!("stdlib/stdlib_memory.harn"),
287    },
288    StdlibSource {
289        module: "postgres",
290        source: include_str!("stdlib/stdlib_postgres.harn"),
291    },
292    StdlibSource {
293        module: "checkpoint",
294        source: include_str!("stdlib/stdlib_checkpoint.harn"),
295    },
296    StdlibSource {
297        module: "host",
298        source: include_str!("stdlib/stdlib_host.harn"),
299    },
300    StdlibSource {
301        module: "git",
302        source: include_str!("stdlib/stdlib_git.harn"),
303    },
304    StdlibSource {
305        module: "hitl",
306        source: include_str!("stdlib/stdlib_hitl.harn"),
307    },
308    StdlibSource {
309        module: "trust",
310        source: include_str!("stdlib/stdlib_trust.harn"),
311    },
312    StdlibSource {
313        module: "corrections",
314        source: include_str!("stdlib/stdlib_corrections.harn"),
315    },
316    StdlibSource {
317        module: "plan",
318        source: include_str!("stdlib/stdlib_plan.harn"),
319    },
320    StdlibSource {
321        module: "waitpoints",
322        source: include_str!("stdlib/stdlib_waitpoints.harn"),
323    },
324    StdlibSource {
325        module: "waitpoint",
326        source: include_str!("stdlib/stdlib_waitpoint.harn"),
327    },
328    StdlibSource {
329        module: "monitors",
330        source: include_str!("stdlib/stdlib_monitors.harn"),
331    },
332    StdlibSource {
333        module: "worktree",
334        source: include_str!("stdlib/stdlib_worktree.harn"),
335    },
336    StdlibSource {
337        module: "acp",
338        source: include_str!("stdlib/stdlib_acp.harn"),
339    },
340    StdlibSource {
341        module: "triggers",
342        source: include_str!("stdlib/stdlib_triggers.harn"),
343    },
344    StdlibSource {
345        module: "handoffs",
346        source: include_str!("stdlib/stdlib_handoffs.harn"),
347    },
348    StdlibSource {
349        module: "personas/prelude",
350        source: include_str!("stdlib/stdlib_personas_prelude.harn"),
351    },
352    StdlibSource {
353        module: "connectors/shared",
354        source: include_str!("stdlib/stdlib_connectors_shared.harn"),
355    },
356    StdlibSource {
357        module: "connectors/github",
358        source: include_str!("stdlib/stdlib_connectors_github.harn"),
359    },
360    StdlibSource {
361        module: "connectors/linear",
362        source: include_str!("stdlib/stdlib_connectors_linear.harn"),
363    },
364    StdlibSource {
365        module: "connectors/notion",
366        source: include_str!("stdlib/stdlib_connectors_notion.harn"),
367    },
368    StdlibSource {
369        module: "connectors/slack",
370        source: include_str!("stdlib/stdlib_connectors_slack.harn"),
371    },
372    StdlibSource {
373        module: "workflow/prompts",
374        source: include_str!("stdlib/workflow/prompts.harn"),
375    },
376    StdlibSource {
377        module: "workflow/context",
378        source: include_str!("stdlib/workflow/context.harn"),
379    },
380    StdlibSource {
381        module: "workflow/options",
382        source: include_str!("stdlib/workflow/options.harn"),
383    },
384    StdlibSource {
385        module: "workflow/checkpoints",
386        source: include_str!("stdlib/workflow/checkpoints.harn"),
387    },
388    StdlibSource {
389        module: "workflow/stage",
390        source: include_str!("stdlib/workflow/stage.harn"),
391    },
392    StdlibSource {
393        module: "workflow/map",
394        source: include_str!("stdlib/workflow/map.harn"),
395    },
396    StdlibSource {
397        module: "workflow/schedule",
398        source: include_str!("stdlib/workflow/schedule.harn"),
399    },
400    StdlibSource {
401        module: "workflow/execute",
402        source: include_str!("stdlib/workflow/execute.harn"),
403    },
404];
405
406pub const STDLIB_PROMPT_ASSETS: &[StdlibPromptAsset] = &[
407    StdlibPromptAsset {
408        path: "agent/prompts/tool_contract_text.harn.prompt",
409        source: include_str!("stdlib/agent/prompts/tool_contract_text.harn.prompt"),
410    },
411    StdlibPromptAsset {
412        path: "agent/prompts/tool_contract_native.harn.prompt",
413        source: include_str!("stdlib/agent/prompts/tool_contract_native.harn.prompt"),
414    },
415    StdlibPromptAsset {
416        path: "agent/prompts/tool_contract_text_response_protocol.harn.prompt",
417        source: include_str!(
418            "stdlib/agent/prompts/tool_contract_text_response_protocol.harn.prompt"
419        ),
420    },
421    StdlibPromptAsset {
422        path: "agent/prompts/tool_contract_action_native.harn.prompt",
423        source: include_str!("stdlib/agent/prompts/tool_contract_action_native.harn.prompt"),
424    },
425    StdlibPromptAsset {
426        path: "agent/prompts/tool_contract_action_text.harn.prompt",
427        source: include_str!("stdlib/agent/prompts/tool_contract_action_text.harn.prompt"),
428    },
429    StdlibPromptAsset {
430        path: "agent/prompts/tool_contract_task_ledger.harn.prompt",
431        source: include_str!("stdlib/agent/prompts/tool_contract_task_ledger.harn.prompt"),
432    },
433    StdlibPromptAsset {
434        path: "agent/prompts/tool_contract_deferred_tools.harn.prompt",
435        source: include_str!("stdlib/agent/prompts/tool_contract_deferred_tools.harn.prompt"),
436    },
437    StdlibPromptAsset {
438        path: "agent/prompts/deferred_tool_listing.harn.prompt",
439        source: include_str!("stdlib/agent/prompts/deferred_tool_listing.harn.prompt"),
440    },
441    StdlibPromptAsset {
442        path: "agent/prompts/action_turn_nudge.harn.prompt",
443        source: include_str!("stdlib/agent/prompts/action_turn_nudge.harn.prompt"),
444    },
445    StdlibPromptAsset {
446        path: "agent/prompts/agent_turn_preamble.harn.prompt",
447        source: include_str!("stdlib/agent/prompts/agent_turn_preamble.harn.prompt"),
448    },
449    StdlibPromptAsset {
450        path: "agent/prompts/default_nudge.harn.prompt",
451        source: include_str!("stdlib/agent/prompts/default_nudge.harn.prompt"),
452    },
453    StdlibPromptAsset {
454        path: "agent/prompts/agentic_user_system.harn.prompt",
455        source: include_str!("stdlib/agent/prompts/agentic_user_system.harn.prompt"),
456    },
457    StdlibPromptAsset {
458        path: "agent/prompts/agentic_user_user.harn.prompt",
459        source: include_str!("stdlib/agent/prompts/agentic_user_user.harn.prompt"),
460    },
461    StdlibPromptAsset {
462        path: "agent/prompts/loop_until_done_system.harn.prompt",
463        source: include_str!("stdlib/agent/prompts/loop_until_done_system.harn.prompt"),
464    },
465    StdlibPromptAsset {
466        path: "agent/prompts/completion_judge_default.harn.prompt",
467        source: include_str!("stdlib/agent/prompts/completion_judge_default.harn.prompt"),
468    },
469    StdlibPromptAsset {
470        path: "agent/prompts/completion_judge_feedback_fallback.harn.prompt",
471        source: include_str!("stdlib/agent/prompts/completion_judge_feedback_fallback.harn.prompt"),
472    },
473    StdlibPromptAsset {
474        path: "agent/prompts/completion_judge_user.harn.prompt",
475        source: include_str!("stdlib/agent/prompts/completion_judge_user.harn.prompt"),
476    },
477    StdlibPromptAsset {
478        path: "agent/prompts/parse_guidance.harn.prompt",
479        source: include_str!("stdlib/agent/prompts/parse_guidance.harn.prompt"),
480    },
481    StdlibPromptAsset {
482        path: "agent/prompts/protocol_violation_feedback.harn.prompt",
483        source: include_str!("stdlib/agent/prompts/protocol_violation_feedback.harn.prompt"),
484    },
485    StdlibPromptAsset {
486        path: "agent/prompts/native_tool_contract_feedback.harn.prompt",
487        source: include_str!("stdlib/agent/prompts/native_tool_contract_feedback.harn.prompt"),
488    },
489    StdlibPromptAsset {
490        path: "agent/prompts/verification_gate_feedback.harn.prompt",
491        source: include_str!("stdlib/agent/prompts/verification_gate_feedback.harn.prompt"),
492    },
493    StdlibPromptAsset {
494        path: "agent/prompts/action_required_feedback.harn.prompt",
495        source: include_str!("stdlib/agent/prompts/action_required_feedback.harn.prompt"),
496    },
497    StdlibPromptAsset {
498        path: "agent/prompts/daemon_watch_feedback.harn.prompt",
499        source: include_str!("stdlib/agent/prompts/daemon_watch_feedback.harn.prompt"),
500    },
501    StdlibPromptAsset {
502        path: "agent/prompts/daemon_timer_feedback.harn.prompt",
503        source: include_str!("stdlib/agent/prompts/daemon_timer_feedback.harn.prompt"),
504    },
505    StdlibPromptAsset {
506        path: "llm/prompts/completion_fallback_system.harn.prompt",
507        source: include_str!("stdlib/llm/prompts/completion_fallback_system.harn.prompt"),
508    },
509    StdlibPromptAsset {
510        path: "llm/prompts/completion_fallback_user.harn.prompt",
511        source: include_str!("stdlib/llm/prompts/completion_fallback_user.harn.prompt"),
512    },
513    StdlibPromptAsset {
514        path: "llm/prompts/transcript_summarize_user.harn.prompt",
515        source: include_str!("stdlib/llm/prompts/transcript_summarize_user.harn.prompt"),
516    },
517    StdlibPromptAsset {
518        path: "llm/prompts/structural_chain_of_draft.harn.prompt",
519        source: include_str!("stdlib/llm/prompts/structural_chain_of_draft.harn.prompt"),
520    },
521    StdlibPromptAsset {
522        path: "llm/prompts/schema_recover_repair.harn.prompt",
523        source: include_str!("stdlib/llm/prompts/schema_recover_repair.harn.prompt"),
524    },
525    StdlibPromptAsset {
526        path: "llm/prompts/structured_envelope_schema_contract.harn.prompt",
527        source: include_str!("stdlib/llm/prompts/structured_envelope_schema_contract.harn.prompt"),
528    },
529    StdlibPromptAsset {
530        path: "llm/prompts/structured_envelope_repair.harn.prompt",
531        source: include_str!("stdlib/llm/prompts/structured_envelope_repair.harn.prompt"),
532    },
533    StdlibPromptAsset {
534        path: "llm/prompts/pairwise_rerank_user.harn.prompt",
535        source: include_str!("stdlib/llm/prompts/pairwise_rerank_user.harn.prompt"),
536    },
537    StdlibPromptAsset {
538        path: "workflow/prompts/stage.harn.prompt",
539        source: include_str!("stdlib/workflow/prompts/stage.harn.prompt"),
540    },
541    StdlibPromptAsset {
542        path: "workflow/prompts/verification_context_intro.harn.prompt",
543        source: include_str!("stdlib/workflow/prompts/verification_context_intro.harn.prompt"),
544    },
545    StdlibPromptAsset {
546        path: "orchestration/prompts/compaction_summary.harn.prompt",
547        source: include_str!("stdlib/orchestration/prompts/compaction_summary.harn.prompt"),
548    },
549];
550
551pub fn get_stdlib_source(module: &str) -> Option<&'static str> {
552    STDLIB_SOURCES
553        .iter()
554        .find_map(|entry| (entry.module == module).then_some(entry.source))
555}
556
557pub fn get_stdlib_prompt_asset(path: &str) -> Option<&'static str> {
558    let path = path.strip_prefix("std/").unwrap_or(path);
559    STDLIB_PROMPT_ASSETS
560        .iter()
561        .find_map(|entry| (entry.path == path).then_some(entry.source))
562}
563
564pub fn public_functions_for_module(module: &str) -> Vec<StdlibPublicFunction> {
565    let Some(source) = get_stdlib_source(module) else {
566        return Vec::new();
567    };
568    public_functions_from_source(source)
569}
570
571pub fn entrypoint_modules() -> Vec<StdlibEntrypointModule> {
572    STDLIB_SOURCES
573        .iter()
574        .filter_map(|entry| {
575            entrypoint_category_from_source(entry.source).map(|category| StdlibEntrypointModule {
576                import_path: format!("std/{}", entry.module),
577                category,
578            })
579        })
580        .collect()
581}
582
583fn entrypoint_category_from_source(source: &str) -> Option<String> {
584    for line in source.lines() {
585        let line = line.trim();
586        if line.is_empty() {
587            continue;
588        }
589        if let Some(category) = line.strip_prefix("// @harn-entrypoint-category ") {
590            let category = category.trim();
591            return (!category.is_empty()).then(|| category.to_string());
592        }
593        if !line.starts_with("//") {
594            return None;
595        }
596    }
597    None
598}
599
600fn public_functions_from_source(source: &str) -> Vec<StdlibPublicFunction> {
601    let mut out = Vec::new();
602    let mut doc: Option<String> = None;
603    let lines = source.lines().collect::<Vec<_>>();
604    let mut index = 0usize;
605    while index < lines.len() {
606        let line = lines[index].trim();
607        if line.starts_with("/**") {
608            let (parsed, next) = parse_harndoc(&lines, index);
609            doc = parsed;
610            index = next;
611            continue;
612        }
613        if line.starts_with("pub fn ") {
614            let (signature_line, next) = collect_public_function_signature(&lines, index);
615            if let Some(function) = parse_public_function_line(&signature_line, doc.take()) {
616                out.push(function);
617                index = next;
618                continue;
619            }
620        }
621        if let Some(function) = parse_public_function_line(line, doc.take()) {
622            out.push(function);
623        } else if !line.is_empty() && !line.starts_with("//") {
624            doc = None;
625        }
626        index += 1;
627    }
628    out
629}
630
631fn collect_public_function_signature(lines: &[&str], start: usize) -> (String, usize) {
632    let mut parts = Vec::new();
633    let mut index = start;
634    while index < lines.len() {
635        parts.push(lines[index].trim().to_string());
636        let candidate = parts.join(" ");
637        if public_function_signature_complete(&candidate) {
638            return (candidate, index + 1);
639        }
640        index += 1;
641    }
642    (parts.join(" "), index)
643}
644
645fn public_function_signature_complete(line: &str) -> bool {
646    let Some(rest) = line.strip_prefix("pub fn ") else {
647        return false;
648    };
649    let Some(name_end) = rest.find('(') else {
650        return false;
651    };
652    matching_paren_len(&rest[name_end + 1..]).is_some()
653}
654
655fn parse_harndoc(lines: &[&str], start: usize) -> (Option<String>, usize) {
656    let mut parts = Vec::new();
657    let mut index = start;
658    while index < lines.len() {
659        let mut line = lines[index].trim();
660        if index == start {
661            line = line.trim_start_matches("/**").trim();
662        }
663        let done = line.ends_with("*/");
664        line = line.trim_end_matches("*/").trim();
665        line = line.trim_start_matches('*').trim();
666        if !line.is_empty() {
667            parts.push(line.to_string());
668        }
669        index += 1;
670        if done {
671            break;
672        }
673    }
674    let text = parts.join("\n").trim().to_string();
675    ((!text.is_empty()).then_some(text), index)
676}
677
678fn parse_public_function_line(line: &str, doc: Option<String>) -> Option<StdlibPublicFunction> {
679    let rest = line.strip_prefix("pub fn ")?.trim();
680    let name_end = rest.find('(')?;
681    let name = rest[..name_end].trim();
682    if name.is_empty() {
683        return None;
684    }
685    let params_start = name_end + 1;
686    let params_len = matching_paren_len(&rest[params_start..])?;
687    let params = &rest[params_start..params_start + params_len];
688    let after = rest[params_start + params_len + 1..].trim();
689    let return_type = after
690        .strip_prefix("->")
691        .and_then(|tail| tail.split('{').next())
692        .map(str::trim)
693        .filter(|value| !value.is_empty());
694    let signature = match return_type {
695        Some(ret) => format!("{name}({params}) -> {ret}"),
696        None => format!("{name}({params})"),
697    };
698    let param_parts = split_top_level_params(params);
699    let total_params = param_parts
700        .iter()
701        .filter(|param| !param.trim().is_empty())
702        .count();
703    let variadic = param_parts
704        .iter()
705        .any(|param| param.trim_start().starts_with("..."));
706    let required_params = param_parts
707        .iter()
708        .filter(|param| {
709            let param = param.trim();
710            !param.is_empty() && !param.contains('=') && !param.starts_with("...")
711        })
712        .count();
713    Some(StdlibPublicFunction {
714        name: name.to_string(),
715        signature,
716        required_params,
717        total_params,
718        variadic,
719        doc,
720    })
721}
722
723fn matching_paren_len(input: &str) -> Option<usize> {
724    let mut depth = 1usize;
725    for (offset, ch) in input.char_indices() {
726        match ch {
727            '(' | '[' | '{' => depth += 1,
728            ')' => {
729                depth = depth.saturating_sub(1);
730                if depth == 0 {
731                    return Some(offset);
732                }
733            }
734            ']' | '}' => depth = depth.saturating_sub(1),
735            _ => {}
736        }
737    }
738    None
739}
740
741fn split_top_level_params(params: &str) -> Vec<&str> {
742    let mut out = Vec::new();
743    let mut depth = 0isize;
744    let mut start = 0usize;
745    for (offset, ch) in params.char_indices() {
746        match ch {
747            '(' | '[' | '{' => depth += 1,
748            ')' | ']' | '}' => depth -= 1,
749            ',' if depth == 0 => {
750                out.push(&params[start..offset]);
751                start = offset + 1;
752            }
753            _ => {}
754        }
755    }
756    out.push(&params[start..]);
757    out
758}
759
760#[cfg(test)]
761mod tests {
762    use std::collections::BTreeSet;
763
764    use super::{
765        entrypoint_modules, get_stdlib_prompt_asset, get_stdlib_source,
766        public_functions_for_module, STDLIB_PROMPT_ASSETS, STDLIB_SOURCES,
767    };
768
769    #[test]
770    fn stdlib_sources_are_non_empty() {
771        for entry in STDLIB_SOURCES {
772            assert!(
773                !entry.source.trim().is_empty(),
774                "{} should have non-empty source",
775                entry.module
776            );
777        }
778    }
779
780    #[test]
781    fn stdlib_source_names_are_unique() {
782        let mut names = BTreeSet::new();
783        for entry in STDLIB_SOURCES {
784            assert!(names.insert(entry.module), "duplicate {}", entry.module);
785        }
786    }
787
788    #[test]
789    fn stdlib_prompt_assets_are_non_empty() {
790        for entry in STDLIB_PROMPT_ASSETS {
791            assert!(
792                !entry.source.trim().is_empty(),
793                "{} should have non-empty prompt asset source",
794                entry.path
795            );
796        }
797    }
798
799    #[test]
800    fn stdlib_prompt_asset_paths_are_unique() {
801        let mut paths = BTreeSet::new();
802        for entry in STDLIB_PROMPT_ASSETS {
803            assert!(paths.insert(entry.path), "duplicate {}", entry.path);
804        }
805    }
806
807    #[test]
808    fn key_stdlib_modules_resolve() {
809        for module in [
810            "context",
811            "command",
812            "waitpoint",
813            "llm/handlers",
814            "llm/tool_middleware",
815            "llm/ensemble",
816            "llm/rerank",
817            "personas/prelude",
818            "agent/host_tools",
819            "agent/user",
820            "llm/optimize",
821            "llm/judge",
822            "llm/refine",
823            "connectors/shared",
824            "connectors/github",
825            "connectors/linear",
826            "connectors/notion",
827            "connectors/slack",
828        ] {
829            assert!(
830                get_stdlib_source(module).is_some(),
831                "std/{module} should resolve"
832            );
833        }
834    }
835
836    #[test]
837    fn key_stdlib_prompt_assets_resolve() {
838        for path in [
839            "std/agent/prompts/tool_contract_text.harn.prompt",
840            "std/agent/prompts/action_turn_nudge.harn.prompt",
841            "std/agent/prompts/completion_judge_default.harn.prompt",
842            "std/workflow/prompts/stage.harn.prompt",
843            "std/orchestration/prompts/compaction_summary.harn.prompt",
844        ] {
845            assert!(
846                get_stdlib_prompt_asset(path).is_some(),
847                "{path} should resolve"
848            );
849        }
850    }
851
852    #[test]
853    fn public_function_catalog_derives_signatures_from_harn_source() {
854        let exports = public_functions_for_module("workflow/execute");
855        assert_eq!(exports.len(), 1);
856        assert_eq!(exports[0].name, "workflow_execute");
857        assert_eq!(
858            exports[0].signature,
859            "workflow_execute(task, graph, artifacts = nil, options = nil)"
860        );
861        assert_eq!(exports[0].required_params, 2);
862        assert_eq!(exports[0].total_params, 4);
863    }
864
865    #[test]
866    fn command_stdlib_module_exports_step_helpers() {
867        let exports = public_functions_for_module("command")
868            .into_iter()
869            .map(|function| function.name)
870            .collect::<BTreeSet<_>>();
871        for name in [
872            "command_run",
873            "command_output_tail",
874            "command_step",
875            "command_steps_append",
876            "command_last_failed_step",
877            "command_step_ref",
878        ] {
879            assert!(exports.contains(name), "std/command should export {name}");
880        }
881    }
882
883    #[test]
884    fn async_stdlib_exports_predicate_backoff_name_only() {
885        let exports = public_functions_for_module("async")
886            .into_iter()
887            .map(|function| function.name)
888            .collect::<BTreeSet<_>>();
889        assert!(
890            exports.contains("retry_predicate_with_backoff"),
891            "std/async should export retry_predicate_with_backoff"
892        );
893        assert!(
894            !exports.contains("retry_with_backoff"),
895            "std/async should not retain the old retry_with_backoff export"
896        );
897    }
898
899    #[test]
900    fn git_stdlib_module_exports_local_wrappers() {
901        let exports = public_functions_for_module("git")
902            .into_iter()
903            .map(|function| function.name)
904            .collect::<BTreeSet<_>>();
905        for name in [
906            "git_run",
907            "git_status",
908            "git_current_branch",
909            "git_log",
910            "git_switch",
911            "git_pull_ff_only",
912            "git_find_tool",
913            "git_run_tool",
914            "git_tools",
915            "git_toolbox_tools",
916        ] {
917            assert!(exports.contains(name), "std/git should export {name}");
918        }
919    }
920
921    #[test]
922    fn harn_entrypoint_catalog_is_declared_by_stdlib_sources() {
923        let modules = entrypoint_modules();
924        let entries = modules
925            .iter()
926            .map(|module| (module.import_path.as_str(), module.category.as_str()))
927            .collect::<BTreeSet<_>>();
928        for entry in [
929            ("std/agent/loop", "agent.stdlib"),
930            ("std/agent/turn", "agent.stdlib"),
931            ("std/agent/primitives", "agent.stdlib"),
932            ("std/workflow/execute", "workflow.stdlib"),
933        ] {
934            assert!(entries.contains(&entry), "{entry:?} should be declared");
935        }
936    }
937}