1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
 2//
 3// SPDX-License-Identifier: AGPL-3.0-or-later
 4
 5package cmd
 6
 7import (
 8	"errors"
 9
10	"git.secluded.site/np/cmd/g"
11	"git.secluded.site/np/cmd/t"
12	"git.secluded.site/np/internal/cli"
13	"git.secluded.site/np/internal/db"
14	"github.com/spf13/cobra"
15)
16
17var rootCmd = &cobra.Command{
18	Use:   "np",
19	Short: "nasin pali - task planning for LLM agents",
20	Long:  `A CLI tool for guiding LLMs through structured task planning and execution`,
21}
22
23func RootCmd() *cobra.Command {
24	return rootCmd
25}
26
27func init() {
28	rootCmd.SilenceUsage = true
29	rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
30		if err := openEnvironment(); err != nil {
31			return err
32		}
33		cmd.SetContext(cli.WithEnvironment(cmd.Context(), environment))
34		return nil
35	}
36	rootCmd.PersistentPostRunE = func(cmd *cobra.Command, args []string) error {
37		return closeEnvironment()
38	}
39
40	rootCmd.AddCommand(sCmd)
41	rootCmd.AddCommand(aCmd)
42	rootCmd.AddCommand(pCmd)
43	rootCmd.AddCommand(rCmd)
44	rootCmd.AddCommand(mCmd)
45	rootCmd.AddCommand(g.GCmd)
46	rootCmd.AddCommand(t.TCmd)
47}
48
49var environment *cli.Environment
50
51func openEnvironment() error {
52	if environment != nil {
53		return nil
54	}
55	env, err := cli.OpenEnvironment(db.Options{}, nil)
56	if err != nil {
57		return err
58	}
59	environment = env
60	return nil
61}
62
63func closeEnvironment() error {
64	if environment == nil {
65		return nil
66	}
67	err := environment.Close()
68	environment = nil
69	return err
70}
71
72func requireEnvironment() (*cli.Environment, error) {
73	if environment == nil {
74		return nil, errors.New("cli: environment not initialised")
75	}
76	return environment, nil
77}