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: "ansi",
42        source: include_str!("stdlib/stdlib_ansi.harn"),
43    },
44    StdlibSource {
45        module: "table",
46        source: include_str!("stdlib/stdlib_table.harn"),
47    },
48    StdlibSource {
49        module: "diff",
50        source: include_str!("stdlib/stdlib_diff.harn"),
51    },
52    StdlibSource {
53        module: "edit",
54        source: include_str!("stdlib/stdlib_edit.harn"),
55    },
56    StdlibSource {
57        module: "artifact/web",
58        source: include_str!("stdlib/artifact/web.harn"),
59    },
60    StdlibSource {
61        module: "collections",
62        source: include_str!("stdlib/stdlib_collections.harn"),
63    },
64    StdlibSource {
65        module: "math",
66        source: include_str!("stdlib/stdlib_math.harn"),
67    },
68    StdlibSource {
69        module: "path",
70        source: include_str!("stdlib/stdlib_path.harn"),
71    },
72    StdlibSource {
73        module: "fs",
74        source: include_str!("stdlib/stdlib_fs.harn"),
75    },
76    StdlibSource {
77        module: "os",
78        source: include_str!("stdlib/stdlib_os.harn"),
79    },
80    StdlibSource {
81        module: "json",
82        source: include_str!("stdlib/stdlib_json.harn"),
83    },
84    StdlibSource {
85        module: "json/stream",
86        source: include_str!("stdlib/stdlib_json_stream.harn"),
87    },
88    StdlibSource {
89        module: "cache",
90        source: include_str!("stdlib/stdlib_cache.harn"),
91    },
92    StdlibSource {
93        module: "tools",
94        source: include_str!("stdlib/stdlib_tools.harn"),
95    },
96    StdlibSource {
97        module: "composition",
98        source: include_str!("stdlib/stdlib_composition.harn"),
99    },
100    StdlibSource {
101        module: "web",
102        source: include_str!("stdlib/stdlib_web.harn"),
103    },
104    StdlibSource {
105        module: "graphql",
106        source: include_str!("stdlib/stdlib_graphql.harn"),
107    },
108    StdlibSource {
109        module: "schema",
110        source: include_str!("stdlib/stdlib_schema.harn"),
111    },
112    StdlibSource {
113        module: "testing",
114        source: include_str!("stdlib/stdlib_testing.harn"),
115    },
116    StdlibSource {
117        module: "files",
118        source: include_str!("stdlib/stdlib_files.harn"),
119    },
120    StdlibSource {
121        module: "vision",
122        source: include_str!("stdlib/stdlib_vision.harn"),
123    },
124    StdlibSource {
125        module: "context",
126        source: include_str!("stdlib/stdlib_context.harn"),
127    },
128    StdlibSource {
129        module: "context/maintenance",
130        source: include_str!("stdlib/context/maintenance.harn"),
131    },
132    StdlibSource {
133        module: "runtime",
134        source: include_str!("stdlib/stdlib_runtime.harn"),
135    },
136    StdlibSource {
137        module: "io",
138        source: include_str!("stdlib/stdlib_io.harn"),
139    },
140    StdlibSource {
141        module: "command",
142        source: include_str!("stdlib/stdlib_command.harn"),
143    },
144    StdlibSource {
145        module: "signal",
146        source: include_str!("stdlib/stdlib_signal.harn"),
147    },
148    StdlibSource {
149        module: "review",
150        source: include_str!("stdlib/stdlib_review.harn"),
151    },
152    StdlibSource {
153        module: "experiments",
154        source: include_str!("stdlib/stdlib_experiments.harn"),
155    },
156    StdlibSource {
157        module: "project",
158        source: include_str!("stdlib/stdlib_project.harn"),
159    },
160    StdlibSource {
161        module: "prompt_library",
162        source: include_str!("stdlib/stdlib_prompt_library.harn"),
163    },
164    StdlibSource {
165        module: "async",
166        source: include_str!("stdlib/stdlib_async.harn"),
167    },
168    StdlibSource {
169        module: "poll",
170        source: include_str!("stdlib/stdlib_poll.harn"),
171    },
172    StdlibSource {
173        module: "coerce",
174        source: include_str!("stdlib/stdlib_coerce.harn"),
175    },
176    StdlibSource {
177        module: "settled",
178        source: include_str!("stdlib/stdlib_settled.harn"),
179    },
180    StdlibSource {
181        module: "cli",
182        source: include_str!("stdlib/stdlib_cli.harn"),
183    },
184    StdlibSource {
185        module: "gha",
186        source: include_str!("stdlib/stdlib_gha.harn"),
187    },
188    StdlibSource {
189        module: "tui",
190        source: include_str!("stdlib/stdlib_tui.harn"),
191    },
192    StdlibSource {
193        module: "jsonl",
194        source: include_str!("stdlib/stdlib_jsonl.harn"),
195    },
196    StdlibSource {
197        module: "config",
198        source: include_str!("stdlib/stdlib_config.harn"),
199    },
200    StdlibSource {
201        module: "calendar",
202        source: include_str!("stdlib/stdlib_calendar.harn"),
203    },
204    StdlibSource {
205        module: "agents",
206        source: include_str!("stdlib/stdlib_agents.harn"),
207    },
208    StdlibSource {
209        module: "lifecycle/pool",
210        source: include_str!("stdlib/lifecycle/pool.harn"),
211    },
212    StdlibSource {
213        module: "agent/prompts",
214        source: include_str!("stdlib/agent/prompts.harn"),
215    },
216    StdlibSource {
217        module: "llm/media",
218        source: include_str!("stdlib/llm/media.harn"),
219    },
220    StdlibSource {
221        module: "llm/options",
222        source: include_str!("stdlib/llm/options.harn"),
223    },
224    StdlibSource {
225        module: "llm/catalog",
226        source: include_str!("stdlib/llm/catalog.harn"),
227    },
228    StdlibSource {
229        module: "llm/safe",
230        source: include_str!("stdlib/llm/safe.harn"),
231    },
232    StdlibSource {
233        module: "llm/budget",
234        source: include_str!("stdlib/llm/budget.harn"),
235    },
236    StdlibSource {
237        module: "llm/economics",
238        source: include_str!("stdlib/llm/economics.harn"),
239    },
240    StdlibSource {
241        module: "llm/prompts",
242        source: include_str!("stdlib/llm/prompts.harn"),
243    },
244    StdlibSource {
245        module: "llm/defaults",
246        source: include_str!("stdlib/llm/defaults.harn"),
247    },
248    StdlibSource {
249        module: "llm/handlers",
250        source: include_str!("stdlib/llm/handlers.harn"),
251    },
252    StdlibSource {
253        module: "llm/tool_telemetry",
254        source: include_str!("stdlib/llm/tool_telemetry.harn"),
255    },
256    StdlibSource {
257        module: "llm/tool_middleware",
258        source: include_str!("stdlib/llm/tool_middleware.harn"),
259    },
260    StdlibSource {
261        module: "llm/tool_binder",
262        source: include_str!("stdlib/llm/tool_binder.harn"),
263    },
264    StdlibSource {
265        module: "llm/refine",
266        source: include_str!("stdlib/llm/refine.harn"),
267    },
268    StdlibSource {
269        module: "llm/ensemble",
270        source: include_str!("stdlib/llm/ensemble.harn"),
271    },
272    StdlibSource {
273        module: "llm/rerank",
274        source: include_str!("stdlib/llm/rerank.harn"),
275    },
276    StdlibSource {
277        module: "agent/reasoning",
278        source: include_str!("stdlib/agent/reasoning.harn"),
279    },
280    StdlibSource {
281        module: "agent/options",
282        source: include_str!("stdlib/agent/options.harn"),
283    },
284    StdlibSource {
285        module: "llm/judge",
286        source: include_str!("stdlib/llm/judge.harn"),
287    },
288    StdlibSource {
289        module: "llm/optimize",
290        source: include_str!("stdlib/llm/optimize.harn"),
291    },
292    StdlibSource {
293        module: "agent/events",
294        source: include_str!("stdlib/agent/events.harn"),
295    },
296    StdlibSource {
297        module: "agent/primitives",
298        source: include_str!("stdlib/agent/primitives.harn"),
299    },
300    StdlibSource {
301        module: "agent/progress",
302        source: include_str!("stdlib/agent/progress.harn"),
303    },
304    StdlibSource {
305        module: "agent/loop",
306        source: include_str!("stdlib/agent/loop.harn"),
307    },
308    StdlibSource {
309        module: "agent/chat",
310        source: include_str!("stdlib/agent/chat.harn"),
311    },
312    StdlibSource {
313        module: "agent/user",
314        source: include_str!("stdlib/agent/user.harn"),
315    },
316    StdlibSource {
317        module: "agent/tool_search",
318        source: include_str!("stdlib/agent/tool_search.harn"),
319    },
320    StdlibSource {
321        module: "agent/turn",
322        source: include_str!("stdlib/agent/turn.harn"),
323    },
324    StdlibSource {
325        module: "agent/workers",
326        source: include_str!("stdlib/agent/workers.harn"),
327    },
328    StdlibSource {
329        module: "agent/state",
330        source: include_str!("stdlib/agent/state.harn"),
331    },
332    StdlibSource {
333        module: "agent/skills",
334        source: include_str!("stdlib/agent/skills.harn"),
335    },
336    StdlibSource {
337        module: "agent/autocompact",
338        source: include_str!("stdlib/agent/autocompact.harn"),
339    },
340    StdlibSource {
341        module: "agent/mcp",
342        source: include_str!("stdlib/agent/mcp.harn"),
343    },
344    StdlibSource {
345        module: "agent/host_tools",
346        source: include_str!("stdlib/agent/host_tools.harn"),
347    },
348    StdlibSource {
349        module: "agent/budget",
350        source: include_str!("stdlib/agent/budget.harn"),
351    },
352    StdlibSource {
353        module: "agent/daemon",
354        source: include_str!("stdlib/agent/daemon.harn"),
355    },
356    StdlibSource {
357        module: "agent/preflight",
358        source: include_str!("stdlib/agent/preflight.harn"),
359    },
360    StdlibSource {
361        module: "agent/postturn",
362        source: include_str!("stdlib/agent/postturn.harn"),
363    },
364    StdlibSource {
365        module: "agent/judge",
366        source: include_str!("stdlib/agent/judge.harn"),
367    },
368    StdlibSource {
369        module: "agent/presets",
370        source: include_str!("stdlib/agent/presets.harn"),
371    },
372    StdlibSource {
373        module: "agent_state",
374        source: include_str!("stdlib/stdlib_agent_state.harn"),
375    },
376    StdlibSource {
377        module: "memory",
378        source: include_str!("stdlib/stdlib_memory.harn"),
379    },
380    StdlibSource {
381        module: "postgres",
382        source: include_str!("stdlib/stdlib_postgres.harn"),
383    },
384    StdlibSource {
385        module: "checkpoint",
386        source: include_str!("stdlib/stdlib_checkpoint.harn"),
387    },
388    StdlibSource {
389        module: "host",
390        source: include_str!("stdlib/stdlib_host.harn"),
391    },
392    StdlibSource {
393        module: "git",
394        source: include_str!("stdlib/stdlib_git.harn"),
395    },
396    StdlibSource {
397        module: "hitl",
398        source: include_str!("stdlib/stdlib_hitl.harn"),
399    },
400    StdlibSource {
401        module: "trust",
402        source: include_str!("stdlib/stdlib_trust.harn"),
403    },
404    StdlibSource {
405        module: "corrections",
406        source: include_str!("stdlib/stdlib_corrections.harn"),
407    },
408    StdlibSource {
409        module: "plan",
410        source: include_str!("stdlib/stdlib_plan.harn"),
411    },
412    StdlibSource {
413        module: "waitpoints",
414        source: include_str!("stdlib/stdlib_waitpoints.harn"),
415    },
416    StdlibSource {
417        module: "waitpoint",
418        source: include_str!("stdlib/stdlib_waitpoint.harn"),
419    },
420    StdlibSource {
421        module: "monitors",
422        source: include_str!("stdlib/stdlib_monitors.harn"),
423    },
424    StdlibSource {
425        module: "worktree",
426        source: include_str!("stdlib/stdlib_worktree.harn"),
427    },
428    StdlibSource {
429        module: "acp",
430        source: include_str!("stdlib/stdlib_acp.harn"),
431    },
432    StdlibSource {
433        module: "triggers",
434        source: include_str!("stdlib/stdlib_triggers.harn"),
435    },
436    StdlibSource {
437        module: "triage",
438        source: include_str!("stdlib/stdlib_triage.harn"),
439    },
440    StdlibSource {
441        module: "dashboard/jobs",
442        source: include_str!("stdlib/dashboard/jobs.harn"),
443    },
444    StdlibSource {
445        module: "ui_resource",
446        source: include_str!("stdlib/stdlib_ui_resource.harn"),
447    },
448    StdlibSource {
449        module: "handoffs",
450        source: include_str!("stdlib/stdlib_handoffs.harn"),
451    },
452    StdlibSource {
453        module: "lifecycle",
454        source: include_str!("stdlib/stdlib_lifecycle.harn"),
455    },
456    StdlibSource {
457        module: "personas/prelude",
458        source: include_str!("stdlib/stdlib_personas_prelude.harn"),
459    },
460    StdlibSource {
461        module: "personas/bulletins",
462        source: include_str!("stdlib/stdlib_personas_bulletins.harn"),
463    },
464    StdlibSource {
465        module: "connectors/shared",
466        source: include_str!("stdlib/stdlib_connectors_shared.harn"),
467    },
468    StdlibSource {
469        module: "oauth/providers",
470        source: include_str!("stdlib/oauth/providers.harn"),
471    },
472    StdlibSource {
473        module: "connectors/github",
474        source: include_str!("stdlib/stdlib_connectors_github.harn"),
475    },
476    StdlibSource {
477        module: "connectors/linear",
478        source: include_str!("stdlib/stdlib_connectors_linear.harn"),
479    },
480    StdlibSource {
481        module: "connectors/notion",
482        source: include_str!("stdlib/stdlib_connectors_notion.harn"),
483    },
484    StdlibSource {
485        module: "connectors/slack",
486        source: include_str!("stdlib/stdlib_connectors_slack.harn"),
487    },
488    StdlibSource {
489        module: "workflow/prompts",
490        source: include_str!("stdlib/workflow/prompts.harn"),
491    },
492    StdlibSource {
493        module: "workflow/context",
494        source: include_str!("stdlib/workflow/context.harn"),
495    },
496    StdlibSource {
497        module: "workflow/options",
498        source: include_str!("stdlib/workflow/options.harn"),
499    },
500    StdlibSource {
501        module: "workflow/checkpoints",
502        source: include_str!("stdlib/workflow/checkpoints.harn"),
503    },
504    StdlibSource {
505        module: "workflow/stage",
506        source: include_str!("stdlib/workflow/stage.harn"),
507    },
508    StdlibSource {
509        module: "workflow/map",
510        source: include_str!("stdlib/workflow/map.harn"),
511    },
512    StdlibSource {
513        module: "workflow/schedule",
514        source: include_str!("stdlib/workflow/schedule.harn"),
515    },
516    StdlibSource {
517        module: "workflow/execute",
518        source: include_str!("stdlib/workflow/execute.harn"),
519    },
520];
521
522pub const STDLIB_PROMPT_ASSETS: &[StdlibPromptAsset] = &[
523    StdlibPromptAsset {
524        path: "agent/prompts/tool_contract_text.harn.prompt",
525        source: include_str!("stdlib/agent/prompts/tool_contract_text.harn.prompt"),
526    },
527    StdlibPromptAsset {
528        path: "agent/prompts/tool_contract_native.harn.prompt",
529        source: include_str!("stdlib/agent/prompts/tool_contract_native.harn.prompt"),
530    },
531    StdlibPromptAsset {
532        path: "agent/prompts/tool_contract_text_response_protocol.harn.prompt",
533        source: include_str!(
534            "stdlib/agent/prompts/tool_contract_text_response_protocol.harn.prompt"
535        ),
536    },
537    StdlibPromptAsset {
538        path: "agent/prompts/tool_contract_action_native.harn.prompt",
539        source: include_str!("stdlib/agent/prompts/tool_contract_action_native.harn.prompt"),
540    },
541    StdlibPromptAsset {
542        path: "agent/prompts/tool_contract_action_text.harn.prompt",
543        source: include_str!("stdlib/agent/prompts/tool_contract_action_text.harn.prompt"),
544    },
545    StdlibPromptAsset {
546        path: "agent/prompts/tool_contract_task_ledger.harn.prompt",
547        source: include_str!("stdlib/agent/prompts/tool_contract_task_ledger.harn.prompt"),
548    },
549    StdlibPromptAsset {
550        path: "agent/prompts/tool_contract_deferred_tools.harn.prompt",
551        source: include_str!("stdlib/agent/prompts/tool_contract_deferred_tools.harn.prompt"),
552    },
553    StdlibPromptAsset {
554        path: "agent/prompts/deferred_tool_listing.harn.prompt",
555        source: include_str!("stdlib/agent/prompts/deferred_tool_listing.harn.prompt"),
556    },
557    StdlibPromptAsset {
558        path: "agent/prompts/action_turn_nudge.harn.prompt",
559        source: include_str!("stdlib/agent/prompts/action_turn_nudge.harn.prompt"),
560    },
561    StdlibPromptAsset {
562        path: "agent/prompts/agent_turn_preamble.harn.prompt",
563        source: include_str!("stdlib/agent/prompts/agent_turn_preamble.harn.prompt"),
564    },
565    StdlibPromptAsset {
566        path: "agent/prompts/default_nudge.harn.prompt",
567        source: include_str!("stdlib/agent/prompts/default_nudge.harn.prompt"),
568    },
569    StdlibPromptAsset {
570        path: "agent/prompts/agentic_user_system.harn.prompt",
571        source: include_str!("stdlib/agent/prompts/agentic_user_system.harn.prompt"),
572    },
573    StdlibPromptAsset {
574        path: "agent/prompts/agentic_user_user.harn.prompt",
575        source: include_str!("stdlib/agent/prompts/agentic_user_user.harn.prompt"),
576    },
577    StdlibPromptAsset {
578        path: "agent/prompts/loop_until_done_system.harn.prompt",
579        source: include_str!("stdlib/agent/prompts/loop_until_done_system.harn.prompt"),
580    },
581    StdlibPromptAsset {
582        path: "agent/prompts/completion_judge_default.harn.prompt",
583        source: include_str!("stdlib/agent/prompts/completion_judge_default.harn.prompt"),
584    },
585    StdlibPromptAsset {
586        path: "agent/prompts/completion_judge_feedback_fallback.harn.prompt",
587        source: include_str!("stdlib/agent/prompts/completion_judge_feedback_fallback.harn.prompt"),
588    },
589    StdlibPromptAsset {
590        path: "agent/prompts/completion_judge_user.harn.prompt",
591        source: include_str!("stdlib/agent/prompts/completion_judge_user.harn.prompt"),
592    },
593    StdlibPromptAsset {
594        path: "agent/prompts/parse_guidance.harn.prompt",
595        source: include_str!("stdlib/agent/prompts/parse_guidance.harn.prompt"),
596    },
597    StdlibPromptAsset {
598        path: "agent/prompts/protocol_violation_feedback.harn.prompt",
599        source: include_str!("stdlib/agent/prompts/protocol_violation_feedback.harn.prompt"),
600    },
601    StdlibPromptAsset {
602        path: "agent/prompts/native_tool_contract_feedback.harn.prompt",
603        source: include_str!("stdlib/agent/prompts/native_tool_contract_feedback.harn.prompt"),
604    },
605    StdlibPromptAsset {
606        path: "agent/prompts/verification_gate_feedback.harn.prompt",
607        source: include_str!("stdlib/agent/prompts/verification_gate_feedback.harn.prompt"),
608    },
609    StdlibPromptAsset {
610        path: "agent/prompts/action_required_feedback.harn.prompt",
611        source: include_str!("stdlib/agent/prompts/action_required_feedback.harn.prompt"),
612    },
613    StdlibPromptAsset {
614        path: "agent/prompts/daemon_watch_feedback.harn.prompt",
615        source: include_str!("stdlib/agent/prompts/daemon_watch_feedback.harn.prompt"),
616    },
617    StdlibPromptAsset {
618        path: "agent/prompts/daemon_timer_feedback.harn.prompt",
619        source: include_str!("stdlib/agent/prompts/daemon_timer_feedback.harn.prompt"),
620    },
621    StdlibPromptAsset {
622        path: "llm/prompts/completion_fallback_system.harn.prompt",
623        source: include_str!("stdlib/llm/prompts/completion_fallback_system.harn.prompt"),
624    },
625    StdlibPromptAsset {
626        path: "llm/prompts/completion_fallback_user.harn.prompt",
627        source: include_str!("stdlib/llm/prompts/completion_fallback_user.harn.prompt"),
628    },
629    StdlibPromptAsset {
630        path: "llm/prompts/transcript_summarize_user.harn.prompt",
631        source: include_str!("stdlib/llm/prompts/transcript_summarize_user.harn.prompt"),
632    },
633    StdlibPromptAsset {
634        path: "llm/prompts/structural_chain_of_draft.harn.prompt",
635        source: include_str!("stdlib/llm/prompts/structural_chain_of_draft.harn.prompt"),
636    },
637    StdlibPromptAsset {
638        path: "llm/prompts/schema_recover_repair.harn.prompt",
639        source: include_str!("stdlib/llm/prompts/schema_recover_repair.harn.prompt"),
640    },
641    StdlibPromptAsset {
642        path: "llm/prompts/structured_envelope_schema_contract.harn.prompt",
643        source: include_str!("stdlib/llm/prompts/structured_envelope_schema_contract.harn.prompt"),
644    },
645    StdlibPromptAsset {
646        path: "llm/prompts/structured_envelope_repair.harn.prompt",
647        source: include_str!("stdlib/llm/prompts/structured_envelope_repair.harn.prompt"),
648    },
649    StdlibPromptAsset {
650        path: "llm/prompts/pairwise_rerank_user.harn.prompt",
651        source: include_str!("stdlib/llm/prompts/pairwise_rerank_user.harn.prompt"),
652    },
653    StdlibPromptAsset {
654        path: "llm/prompts/tool_binder_user.harn.prompt",
655        source: include_str!("stdlib/llm/prompts/tool_binder_user.harn.prompt"),
656    },
657    StdlibPromptAsset {
658        path: "workflow/prompts/stage.harn.prompt",
659        source: include_str!("stdlib/workflow/prompts/stage.harn.prompt"),
660    },
661    StdlibPromptAsset {
662        path: "workflow/prompts/verification_context_intro.harn.prompt",
663        source: include_str!("stdlib/workflow/prompts/verification_context_intro.harn.prompt"),
664    },
665    StdlibPromptAsset {
666        path: "orchestration/prompts/compaction_summary.harn.prompt",
667        source: include_str!("stdlib/orchestration/prompts/compaction_summary.harn.prompt"),
668    },
669];
670
671pub fn get_stdlib_source(module: &str) -> Option<&'static str> {
672    STDLIB_SOURCES
673        .iter()
674        .find_map(|entry| (entry.module == module).then_some(entry.source))
675}
676
677pub fn get_stdlib_prompt_asset(path: &str) -> Option<&'static str> {
678    let path = path.strip_prefix("std/").unwrap_or(path);
679    STDLIB_PROMPT_ASSETS
680        .iter()
681        .find_map(|entry| (entry.path == path).then_some(entry.source))
682}
683
684pub fn public_functions_for_module(module: &str) -> Vec<StdlibPublicFunction> {
685    let Some(source) = get_stdlib_source(module) else {
686        return Vec::new();
687    };
688    public_functions_from_source(source)
689}
690
691pub fn entrypoint_modules() -> Vec<StdlibEntrypointModule> {
692    STDLIB_SOURCES
693        .iter()
694        .filter_map(|entry| {
695            entrypoint_category_from_source(entry.source).map(|category| StdlibEntrypointModule {
696                import_path: format!("std/{}", entry.module),
697                category,
698            })
699        })
700        .collect()
701}
702
703fn entrypoint_category_from_source(source: &str) -> Option<String> {
704    for line in source.lines() {
705        let line = line.trim();
706        if line.is_empty() {
707            continue;
708        }
709        if let Some(category) = line.strip_prefix("// @harn-entrypoint-category ") {
710            let category = category.trim();
711            return (!category.is_empty()).then(|| category.to_string());
712        }
713        if !line.starts_with("//") {
714            return None;
715        }
716    }
717    None
718}
719
720fn public_functions_from_source(source: &str) -> Vec<StdlibPublicFunction> {
721    let mut out = Vec::new();
722    let mut doc: Option<String> = None;
723    let lines = source.lines().collect::<Vec<_>>();
724    let mut index = 0usize;
725    while index < lines.len() {
726        let line = lines[index].trim();
727        if line.starts_with("/**") {
728            let (parsed, next) = parse_harndoc(&lines, index);
729            doc = parsed;
730            index = next;
731            continue;
732        }
733        if line.starts_with("pub fn ") {
734            let (signature_line, next) = collect_public_function_signature(&lines, index);
735            if let Some(function) = parse_public_function_line(&signature_line, doc.take()) {
736                out.push(function);
737                index = next;
738                continue;
739            }
740        }
741        if let Some(function) = parse_public_function_line(line, doc.take()) {
742            out.push(function);
743        } else if !line.is_empty() && !line.starts_with("//") {
744            doc = None;
745        }
746        index += 1;
747    }
748    out
749}
750
751fn collect_public_function_signature(lines: &[&str], start: usize) -> (String, usize) {
752    let mut parts = Vec::new();
753    let mut index = start;
754    while index < lines.len() {
755        parts.push(lines[index].trim().to_string());
756        let candidate = parts.join(" ");
757        if public_function_signature_complete(&candidate) {
758            return (candidate, index + 1);
759        }
760        index += 1;
761    }
762    (parts.join(" "), index)
763}
764
765fn public_function_signature_complete(line: &str) -> bool {
766    let Some(rest) = line.strip_prefix("pub fn ") else {
767        return false;
768    };
769    let Some(name_end) = rest.find('(') else {
770        return false;
771    };
772    matching_paren_len(&rest[name_end + 1..]).is_some()
773}
774
775fn parse_harndoc(lines: &[&str], start: usize) -> (Option<String>, usize) {
776    let mut parts = Vec::new();
777    let mut index = start;
778    while index < lines.len() {
779        let mut line = lines[index].trim();
780        if index == start {
781            line = line.trim_start_matches("/**").trim();
782        }
783        let done = line.ends_with("*/");
784        line = line.trim_end_matches("*/").trim();
785        line = line.trim_start_matches('*').trim();
786        if !line.is_empty() {
787            parts.push(line.to_string());
788        }
789        index += 1;
790        if done {
791            break;
792        }
793    }
794    let text = parts.join("\n").trim().to_string();
795    ((!text.is_empty()).then_some(text), index)
796}
797
798fn parse_public_function_line(line: &str, doc: Option<String>) -> Option<StdlibPublicFunction> {
799    let rest = line.strip_prefix("pub fn ")?.trim();
800    let name_end = rest.find('(')?;
801    let name = rest[..name_end].trim();
802    if name.is_empty() {
803        return None;
804    }
805    let params_start = name_end + 1;
806    let params_len = matching_paren_len(&rest[params_start..])?;
807    let params = &rest[params_start..params_start + params_len];
808    let after = rest[params_start + params_len + 1..].trim();
809    let return_type = after
810        .strip_prefix("->")
811        .and_then(|tail| tail.split('{').next())
812        .map(str::trim)
813        .filter(|value| !value.is_empty());
814    let signature = match return_type {
815        Some(ret) => format!("{name}({params}) -> {ret}"),
816        None => format!("{name}({params})"),
817    };
818    let param_parts = split_top_level_params(params);
819    let total_params = param_parts
820        .iter()
821        .filter(|param| !param.trim().is_empty())
822        .count();
823    let variadic = param_parts
824        .iter()
825        .any(|param| param.trim_start().starts_with("..."));
826    let required_params = param_parts
827        .iter()
828        .filter(|param| {
829            let param = param.trim();
830            !param.is_empty() && !param.contains('=') && !param.starts_with("...")
831        })
832        .count();
833    Some(StdlibPublicFunction {
834        name: name.to_string(),
835        signature,
836        required_params,
837        total_params,
838        variadic,
839        doc,
840    })
841}
842
843fn matching_paren_len(input: &str) -> Option<usize> {
844    let mut depth = 1usize;
845    for (offset, ch) in input.char_indices() {
846        match ch {
847            '(' | '[' | '{' => depth += 1,
848            ')' => {
849                depth = depth.saturating_sub(1);
850                if depth == 0 {
851                    return Some(offset);
852                }
853            }
854            ']' | '}' => depth = depth.saturating_sub(1),
855            _ => {}
856        }
857    }
858    None
859}
860
861fn split_top_level_params(params: &str) -> Vec<&str> {
862    let mut out = Vec::new();
863    let mut depth = 0isize;
864    let mut start = 0usize;
865    for (offset, ch) in params.char_indices() {
866        match ch {
867            '(' | '[' | '{' => depth += 1,
868            ')' | ']' | '}' => depth -= 1,
869            ',' if depth == 0 => {
870                out.push(&params[start..offset]);
871                start = offset + 1;
872            }
873            _ => {}
874        }
875    }
876    out.push(&params[start..]);
877    out
878}
879
880#[cfg(test)]
881mod tests {
882    use std::collections::BTreeSet;
883
884    use super::{
885        entrypoint_modules, get_stdlib_prompt_asset, get_stdlib_source,
886        public_functions_for_module, STDLIB_PROMPT_ASSETS, STDLIB_SOURCES,
887    };
888
889    #[test]
890    fn stdlib_sources_are_non_empty() {
891        for entry in STDLIB_SOURCES {
892            assert!(
893                !entry.source.trim().is_empty(),
894                "{} should have non-empty source",
895                entry.module
896            );
897        }
898    }
899
900    #[test]
901    fn stdlib_source_names_are_unique() {
902        let mut names = BTreeSet::new();
903        for entry in STDLIB_SOURCES {
904            assert!(names.insert(entry.module), "duplicate {}", entry.module);
905        }
906    }
907
908    #[test]
909    fn stdlib_prompt_assets_are_non_empty() {
910        for entry in STDLIB_PROMPT_ASSETS {
911            assert!(
912                !entry.source.trim().is_empty(),
913                "{} should have non-empty prompt asset source",
914                entry.path
915            );
916        }
917    }
918
919    #[test]
920    fn stdlib_prompt_asset_paths_are_unique() {
921        let mut paths = BTreeSet::new();
922        for entry in STDLIB_PROMPT_ASSETS {
923            assert!(paths.insert(entry.path), "duplicate {}", entry.path);
924        }
925    }
926
927    #[test]
928    fn key_stdlib_modules_resolve() {
929        for module in [
930            "context",
931            "context/maintenance",
932            "edit",
933            "artifact/web",
934            "command",
935            "waitpoint",
936            "llm/handlers",
937            "llm/tool_middleware",
938            "llm/tool_binder",
939            "llm/ensemble",
940            "llm/rerank",
941            "personas/prelude",
942            "personas/bulletins",
943            "agent/host_tools",
944            "agent/user",
945            "llm/optimize",
946            "llm/judge",
947            "llm/refine",
948            "connectors/shared",
949            "connectors/github",
950            "connectors/linear",
951            "connectors/notion",
952            "connectors/slack",
953            "triage",
954            "dashboard/jobs",
955            "ui_resource",
956        ] {
957            assert!(
958                get_stdlib_source(module).is_some(),
959                "std/{module} should resolve"
960            );
961        }
962    }
963
964    #[test]
965    fn key_stdlib_prompt_assets_resolve() {
966        for path in [
967            "std/agent/prompts/tool_contract_text.harn.prompt",
968            "std/agent/prompts/action_turn_nudge.harn.prompt",
969            "std/agent/prompts/completion_judge_default.harn.prompt",
970            "std/workflow/prompts/stage.harn.prompt",
971            "std/orchestration/prompts/compaction_summary.harn.prompt",
972        ] {
973            assert!(
974                get_stdlib_prompt_asset(path).is_some(),
975                "{path} should resolve"
976            );
977        }
978    }
979
980    #[test]
981    fn public_function_catalog_derives_signatures_from_harn_source() {
982        let exports = public_functions_for_module("workflow/execute");
983        assert_eq!(exports.len(), 1);
984        assert_eq!(exports[0].name, "workflow_execute");
985        assert_eq!(
986            exports[0].signature,
987            "workflow_execute(task, graph, artifacts = nil, options = nil)"
988        );
989        assert_eq!(exports[0].required_params, 2);
990        assert_eq!(exports[0].total_params, 4);
991    }
992
993    #[test]
994    fn command_stdlib_module_exports_step_helpers() {
995        let exports = public_functions_for_module("command")
996            .into_iter()
997            .map(|function| function.name)
998            .collect::<BTreeSet<_>>();
999        for name in [
1000            "command_run",
1001            "command_output_tail",
1002            "command_step",
1003            "command_steps_append",
1004            "command_last_failed_step",
1005            "command_step_ref",
1006        ] {
1007            assert!(exports.contains(name), "std/command should export {name}");
1008        }
1009    }
1010
1011    #[test]
1012    fn async_stdlib_exports_predicate_backoff_name_only() {
1013        let exports = public_functions_for_module("async")
1014            .into_iter()
1015            .map(|function| function.name)
1016            .collect::<BTreeSet<_>>();
1017        assert!(
1018            exports.contains("retry_predicate_with_backoff"),
1019            "std/async should export retry_predicate_with_backoff"
1020        );
1021        assert!(
1022            !exports.contains("retry_with_backoff"),
1023            "std/async should not retain the old retry_with_backoff export"
1024        );
1025    }
1026
1027    #[test]
1028    fn signal_stdlib_module_exports_interrupt_helpers() {
1029        let exports = public_functions_for_module("signal")
1030            .into_iter()
1031            .map(|function| function.name)
1032            .collect::<BTreeSet<_>>();
1033        for name in [
1034            "on_interrupt",
1035            "off_interrupt",
1036            "interrupted",
1037            "with_interrupt",
1038        ] {
1039            assert!(exports.contains(name), "std/signal should export {name}");
1040        }
1041    }
1042
1043    #[test]
1044    fn git_stdlib_module_exports_local_wrappers() {
1045        let exports = public_functions_for_module("git")
1046            .into_iter()
1047            .map(|function| function.name)
1048            .collect::<BTreeSet<_>>();
1049        for name in [
1050            "git_run",
1051            "git_status",
1052            "git_current_branch",
1053            "git_log",
1054            "git_switch",
1055            "git_pull_ff_only",
1056            "git_find_tool",
1057            "git_run_tool",
1058            "git_tools",
1059            "git_toolbox_tools",
1060        ] {
1061            assert!(exports.contains(name), "std/git should export {name}");
1062        }
1063    }
1064
1065    #[test]
1066    fn agent_workers_exports_suspend_resume_wrappers() {
1067        let exports = public_functions_for_module("agent/workers");
1068        let suspend = exports
1069            .iter()
1070            .find(|function| function.name == "suspend_agent")
1071            .expect("std/agent/workers should export suspend_agent");
1072        assert_eq!(
1073            suspend.signature,
1074            "suspend_agent(worker, reason = \"\", options = nil)"
1075        );
1076        assert_eq!(suspend.required_params, 1);
1077        assert_eq!(suspend.total_params, 3);
1078
1079        let resume = exports
1080            .iter()
1081            .find(|function| function.name == "resume_agent")
1082            .expect("std/agent/workers should export resume_agent");
1083        assert_eq!(
1084            resume.signature,
1085            "resume_agent(worker_or_snapshot, resume_input = nil, continue_transcript = true)"
1086        );
1087        assert_eq!(resume.required_params, 1);
1088        assert_eq!(resume.total_params, 3);
1089
1090        let parse_resume = exports
1091            .iter()
1092            .find(|function| function.name == "parse_resume_conditions")
1093            .expect("std/agent/workers should export parse_resume_conditions");
1094        assert_eq!(
1095            parse_resume.signature,
1096            "parse_resume_conditions(conditions = nil) -> ResumeConditions?"
1097        );
1098        assert_eq!(parse_resume.required_params, 0);
1099        assert_eq!(parse_resume.total_params, 1);
1100
1101        let lifecycle = exports
1102            .iter()
1103            .find(|function| function.name == "agent_lifecycle_tools")
1104            .expect("std/agent/workers should export agent_lifecycle_tools");
1105        assert_eq!(
1106            lifecycle.signature,
1107            "agent_lifecycle_tools(registry = nil, options = nil)"
1108        );
1109        assert_eq!(lifecycle.required_params, 0);
1110        assert_eq!(lifecycle.total_params, 2);
1111    }
1112
1113    #[test]
1114    fn tui_stdlib_module_exports_terminal_helpers() {
1115        let exports = public_functions_for_module("tui")
1116            .into_iter()
1117            .map(|function| function.name)
1118            .collect::<BTreeSet<_>>();
1119        for name in ["page", "terminal_width", "rule", "clear", "select_from"] {
1120            assert!(exports.contains(name), "std/tui should export {name}");
1121        }
1122    }
1123
1124    #[test]
1125    fn harn_entrypoint_catalog_is_declared_by_stdlib_sources() {
1126        let modules = entrypoint_modules();
1127        let entries = modules
1128            .iter()
1129            .map(|module| (module.import_path.as_str(), module.category.as_str()))
1130            .collect::<BTreeSet<_>>();
1131        for entry in [
1132            ("std/agent/loop", "agent.stdlib"),
1133            ("std/agent/turn", "agent.stdlib"),
1134            ("std/agent/primitives", "agent.stdlib"),
1135            ("std/workflow/execute", "workflow.stdlib"),
1136        ] {
1137            assert!(entries.contains(&entry), "{entry:?} should be declared");
1138        }
1139    }
1140}